diff --git a/KerbalVR/KerbalVR.csproj b/KerbalVR/KerbalVR.csproj index ef8c77bd..94f1098d 100644 --- a/KerbalVR/KerbalVR.csproj +++ b/KerbalVR/KerbalVR.csproj @@ -31,7 +31,7 @@ - ksp_lib\Assembly-CSharp.dll + ..\..\..\..\..\..\GOG Games\Kerbal Space Program\KSP_x64_Data\Managed\Assembly-CSharp.dll @@ -40,11 +40,10 @@ - ksp_lib\UnityEngine.dll + ..\..\..\..\..\..\GOG Games\Kerbal Space Program\KSP_x64_Data\Managed\UnityEngine.dll - - False - ksp_lib\UnityEngine.UI.dll + + ..\..\..\..\..\..\GOG Games\Kerbal Space Program\KSP_x64_Data\Managed\UnityEngine.UI.dll diff --git a/KerbalVR/KerbalVR_AppGUI.cs b/KerbalVR/KerbalVR_AppGUI.cs index 6dd683ac..13f53ab4 100644 --- a/KerbalVR/KerbalVR_AppGUI.cs +++ b/KerbalVR/KerbalVR_AppGUI.cs @@ -8,25 +8,30 @@ namespace KerbalVR { public class AppGUI { - private class TextFieldFloat { + private class TextFieldFloat + { private string parameterName; private Action parameterCallback; private string valueStr; - public TextFieldFloat(string parameterName, float parameter, Action parameterCallback) { + public TextFieldFloat(string parameterName, float parameter, Action parameterCallback) + { this.parameterName = parameterName; this.parameterCallback = parameterCallback; valueStr = parameter.ToString("F3"); } - public void UpdateGUI() { + public void UpdateGUI() + { GUILayout.BeginHorizontal(); GUILayout.Label(parameterName + ":", HighLogic.Skin.label); valueStr = GUILayout.TextField(valueStr, HighLogic.Skin.textField); - if (GUI.changed) { + if (GUI.changed) + { float updatedValue; bool parseSuccess = System.Single.TryParse(valueStr, out updatedValue); - if (parseSuccess) { + if (parseSuccess) + { parameterCallback(updatedValue); } } @@ -35,15 +40,19 @@ public void UpdateGUI() { } #region Constants - public static string AppButtonLogo { - get { + public static string AppButtonLogo + { + get + { string path = Path.Combine(Globals.KERBALVR_TEXTURES_DIR, "app_button_logo"); return path.Replace("\\", "/"); } } - public static bool SceneAllowsAppGUI { - get { + public static bool SceneAllowsAppGUI + { + get + { return ( #if DEBUG (HighLogic.LoadedScene == GameScenes.MAINMENU) || @@ -93,7 +102,8 @@ public static bool SceneAllowsAppGUI { /// application launcher. Note that this callback can be called multiple times /// throughout the game. /// - public void OnAppLauncherReady() { + public void OnAppLauncherReady() + { // define where should the app button be visible /* @@ -107,7 +117,8 @@ public void OnAppLauncherReady() { */ // create new app button instance if it doesn't already exist - if (appButton == null) { + if (appButton == null) + { // init variables worldScaleStr = Scene.Instance.WorldScale.ToString("F1"); @@ -128,11 +139,13 @@ public void OnAppLauncherReady() { } } - void OnShow() { + void OnShow() + { appButtonGuiActive = appButtonGuiActiveLastState; } - void OnHide() { + void OnHide() + { appButtonGuiActiveLastState = appButtonGuiActive; appButtonGuiActive = false; } @@ -142,8 +155,10 @@ void OnHide() { /// at the time the plugin is loaded. It destroys the application button on the /// application launcher. /// - public void OnAppLauncherDestroyed() { - if (appButton != null) { + public void OnAppLauncherDestroyed() + { + if (appButton != null) + { OnToggleFalse(); ApplicationLauncher.Instance.RemoveApplication(appButton); ApplicationLauncher.Instance.RemoveOnShowCallback(OnShow); @@ -154,19 +169,23 @@ public void OnAppLauncherDestroyed() { /// /// Callback when the application button is toggled on. /// - public void OnToggleTrue() { + public void OnToggleTrue() + { appButtonGuiActive = true; } /// /// Callback when the application button is toggled off. /// - public void OnToggleFalse() { + public void OnToggleFalse() + { appButtonGuiActive = false; } - public void OnGUI() { - if (SceneAllowsAppGUI && appButtonGuiActive) { + public void OnGUI() + { + if (SceneAllowsAppGUI && appButtonGuiActive) + { appGuiWindowRect = GUILayout.Window( APP_GUI_ID, appGuiWindowRect, @@ -176,20 +195,23 @@ public void OnGUI() { } } - private void GenerateGUI(int windowId) { + private void GenerateGUI(int windowId) + { string buttonStringToggleVr = BUTTON_STRING_ENABLE_VR; string labelStringVrActive = LABEL_STRING_VR_INACTIVE; string buttonStringToggleMirror = BUTTON_STRING_ENABLE_MIRROR; GUIStyle labelStyleVrActive = new GUIStyle(HighLogic.Skin.label); labelStyleVrActive.normal.textColor = Color.red; - if (Core.HmdIsRunning) { + if (Core.HmdIsRunning) + { buttonStringToggleVr = BUTTON_STRING_DISABLE_VR; labelStringVrActive = LABEL_STRING_VR_ACTIVE; labelStyleVrActive.normal.textColor = Color.green; } - if (Core.RenderHmdToScreen) { + if (Core.RenderHmdToScreen) + { buttonStringToggleMirror = BUTTON_STRING_DISABLE_MIRROR; } @@ -198,25 +220,36 @@ private void GenerateGUI(int windowId) { // VR toggle button //------------------------------------------------------------------ UnityEngine.GUI.enabled = Scene.Instance.SceneAllowsVR(); - if (GUILayout.Button(buttonStringToggleVr, HighLogic.Skin.button)) { - if (Core.HmdIsEnabled) { + if (GUILayout.Button(buttonStringToggleVr, HighLogic.Skin.button)) + { + if (Core.HmdIsEnabled) + { Core.HmdIsEnabled = false; - } else { + } + else + { Core.HmdIsEnabled = true; } } - if (Core.CanResetSeatedPose()) { - if (GUILayout.Button("Reset Headset Position", HighLogic.Skin.button)) { + if (Core.CanResetSeatedPose()) + { + if (GUILayout.Button("Reset Headset Position", HighLogic.Skin.button)) + { Core.ResetInitialHmdPosition(); } } - if (Core.HmdIsRunning) { - if (GUILayout.Button(buttonStringToggleMirror, HighLogic.Skin.button)) { - if (Core.RenderHmdToScreen) { + if (Core.HmdIsRunning) + { + if (GUILayout.Button(buttonStringToggleMirror, HighLogic.Skin.button)) + { + if (Core.RenderHmdToScreen) + { Core.RenderHmdToScreen = false; - } else { + } + else + { Core.RenderHmdToScreen = true; } } @@ -240,17 +273,37 @@ private void GenerateGUI(int windowId) { #if DEBUG GUILayout.BeginHorizontal(); GUILayout.Label("Hand Size:", HighLogic.Skin.label); - int handSizeScale = (int)(DeviceManager.Instance.ManipulatorSize * 100f + 0.5f); - string handSizeStr = handSizeScale.ToString(); - handSizeStr = GUILayout.TextField(handSizeStr, HighLogic.Skin.textField); - if (GUI.changed) { - bool parseSuccess = System.Int32.TryParse(handSizeStr, out handSizeScale); - if (parseSuccess && - handSizeScale >= 1 && - handSizeScale <= 100) { - DeviceManager.Instance.ManipulatorSize = handSizeScale * 0.01f; - } else { - DeviceManager.Instance.ManipulatorSize = 0.45f; + int handSizeScaleLeft = (int)(DeviceManager.Instance.ManipulatorLeft.ManipulatorSize * 100f + 0.5f); + int handSizeScaleRight = (int)(DeviceManager.Instance.ManipulatorRight.ManipulatorSize * 100f + 0.5f); + string handSizeStrLeft = handSizeScaleLeft.ToString(); + string handSizeStrRight = handSizeScaleRight.ToString(); + handSizeStrLeft = GUILayout.TextField(handSizeStrLeft, HighLogic.Skin.textField); + handSizeStrRight = GUILayout.TextField(handSizeStrRight, HighLogic.Skin.textField); + if (GUI.changed) + { + bool parseSuccessLeft = System.Int32.TryParse(handSizeStrLeft, out handSizeScaleLeft); + bool parseSuccessRight = System.Int32.TryParse(handSizeStrRight, out handSizeScaleRight); + + if (parseSuccessLeft && + handSizeScaleLeft >= 1 && + handSizeScaleLeft <= 100) + { + DeviceManager.Instance.ManipulatorLeft.ManipulatorSize = handSizeScaleLeft * 0.01f; + } + else + { + DeviceManager.Instance.ManipulatorLeft.ManipulatorSize = 0.45f; + } + + if (parseSuccessRight && + handSizeScaleRight >= 1 && + handSizeScaleRight <= 100) + { + DeviceManager.Instance.ManipulatorRight.ManipulatorSize = handSizeScaleRight * 0.01f; + } + else + { + DeviceManager.Instance.ManipulatorRight.ManipulatorSize = 0.45f; } } GUILayout.EndHorizontal(); @@ -260,12 +313,14 @@ private void GenerateGUI(int windowId) { GUILayout.BeginHorizontal(); GUILayout.Label("World Scale:", HighLogic.Skin.label); worldScaleStr = GUILayout.TextField(worldScaleStr, HighLogic.Skin.textField); - if (GUI.changed) { + if (GUI.changed) + { float worldScale; bool parseSuccess = System.Single.TryParse(worldScaleStr, out worldScale); if (parseSuccess && worldScale >= 0.1 && - worldScale <= 10) { + worldScale <= 10) + { Scene.Instance.WorldScale = worldScale; } } @@ -274,7 +329,8 @@ private void GenerateGUI(int windowId) { // init at startup toggle GUILayout.BeginHorizontal(); bool initOpenVrAtStartup = GUILayout.Toggle(Configuration.Instance.InitOpenVrAtStartup, "Init OpenVR at startup", HighLogic.Skin.toggle); - if (GUI.changed) { + if (GUI.changed) + { Configuration.Instance.InitOpenVrAtStartup = initOpenVrAtStartup; } GUILayout.EndHorizontal(); @@ -282,7 +338,8 @@ private void GenerateGUI(int windowId) { // swap control stick yaw and roll GUILayout.BeginHorizontal(); bool swapYawRollControls = GUILayout.Toggle(Configuration.Instance.SwapYawRollControls, "Swap Yaw/Roll Controls", HighLogic.Skin.toggle); - if (GUI.changed) { + if (GUI.changed) + { Configuration.Instance.SwapYawRollControls = swapYawRollControls; } GUILayout.EndHorizontal(); diff --git a/KerbalVR/KerbalVR_Manipulator.cs b/KerbalVR/KerbalVR_Manipulator.cs index 8acddaec..078a9af7 100644 --- a/KerbalVR/KerbalVR_Manipulator.cs +++ b/KerbalVR/KerbalVR_Manipulator.cs @@ -21,6 +21,9 @@ public class Manipulator : MonoBehaviour public SteamVR_Controller.Device State { get; private set; } public Vector3 GripPosition { get; private set; } + // if this is 0.66, then the fingertip's collider will be only 66% as big as the glove's model original fingertip sphere collider. 1.0 keeps the original size. + private float _overrideFingertipScale = 0.66f; + // Manipulator object properties private float _manipulatorSize = 0.45f; public float ManipulatorSize { @@ -95,6 +98,9 @@ protected void LoadManipulatorRenderGameObject() { } fingertipCollider = colliderObject.GetComponent(); + // Reduce the size of the finger tip to avoid butterfingers on the square buttons around RasterPropMonitor (the regular fingerTip's sphere clicks 3 at once). + fingertipCollider.transform.localScale = _overrideFingertipScale * fingertipCollider.transform.localScale; + colliderObject = gloveGameObject.transform.Find("HandDummy/Arm Bone L/Wrist Bone L"); if (colliderObject == null) { Utils.LogWarning("Manipulator is missing grip collider child object"); diff --git a/KerbalVR/Library/APIUpdater/project-dependencies.graph b/KerbalVR/Library/APIUpdater/project-dependencies.graph new file mode 100644 index 00000000..eb91ac7b Binary files /dev/null and b/KerbalVR/Library/APIUpdater/project-dependencies.graph differ diff --git a/KerbalVR/Library/AnnotationManager b/KerbalVR/Library/AnnotationManager new file mode 100644 index 00000000..b9c4c180 Binary files /dev/null and b/KerbalVR/Library/AnnotationManager differ diff --git a/KerbalVR/Library/AssetImportState b/KerbalVR/Library/AssetImportState new file mode 100644 index 00000000..715f58c1 --- /dev/null +++ b/KerbalVR/Library/AssetImportState @@ -0,0 +1 @@ +19;0;4;0;0 \ No newline at end of file diff --git a/KerbalVR/Library/BuildPlayer.prefs b/KerbalVR/Library/BuildPlayer.prefs new file mode 100644 index 00000000..e69de29b diff --git a/KerbalVR/Library/BuildSettings.asset b/KerbalVR/Library/BuildSettings.asset new file mode 100644 index 00000000..1106cfef Binary files /dev/null and b/KerbalVR/Library/BuildSettings.asset differ diff --git a/KerbalVR/Library/CurrentLayout-default.dwlt b/KerbalVR/Library/CurrentLayout-default.dwlt new file mode 100644 index 00000000..14b6433a --- /dev/null +++ b/KerbalVR/Library/CurrentLayout-default.dwlt @@ -0,0 +1,733 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!114 &1 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12004, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_PixelRect: + serializedVersion: 2 + x: 11.2 + y: -1108.8 + width: 2048 + height: 1028 + m_ShowMode: 4 + m_Title: + m_RootView: {fileID: 6} + m_MinSize: {x: 950, y: 544} + m_MaxSize: {x: 10000, y: 10000} +--- !u!114 &2 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12010, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_Children: + - {fileID: 9} + - {fileID: 3} + m_Position: + serializedVersion: 2 + x: 0 + y: 30 + width: 2048 + height: 978 + m_MinSize: {x: 685, y: 494} + m_MaxSize: {x: 14006, y: 14044} + vertical: 0 + controlID: 114 +--- !u!114 &3 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12006, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_Children: [] + m_Position: + serializedVersion: 2 + x: 1632 + y: 0 + width: 416 + height: 978 + m_MinSize: {x: 279, y: 72} + m_MaxSize: {x: 4004, y: 4022} + m_ActualView: {fileID: 14} + m_Panes: + - {fileID: 14} + m_Selected: 0 + m_LastSelected: 0 +--- !u!114 &4 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12006, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_Children: [] + m_Position: + serializedVersion: 2 + x: 0 + y: 0 + width: 403 + height: 592 + m_MinSize: {x: 202, y: 222} + m_MaxSize: {x: 4002, y: 4022} + m_ActualView: {fileID: 15} + m_Panes: + - {fileID: 15} + m_Selected: 0 + m_LastSelected: 0 +--- !u!114 &5 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12006, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_Children: [] + m_Position: + serializedVersion: 2 + x: 0 + y: 592 + width: 1632 + height: 386 + m_MinSize: {x: 232, y: 272} + m_MaxSize: {x: 10002, y: 10022} + m_ActualView: {fileID: 13} + m_Panes: + - {fileID: 13} + - {fileID: 18} + m_Selected: 0 + m_LastSelected: 0 +--- !u!114 &6 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12008, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_Children: + - {fileID: 7} + - {fileID: 2} + - {fileID: 8} + m_Position: + serializedVersion: 2 + x: 0 + y: 0 + width: 2048 + height: 1028 + m_MinSize: {x: 950, y: 544} + m_MaxSize: {x: 10000, y: 10000} +--- !u!114 &7 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12011, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_Children: [] + m_Position: + serializedVersion: 2 + x: 0 + y: 0 + width: 2048 + height: 30 + m_MinSize: {x: 0, y: 0} + m_MaxSize: {x: 0, y: 0} + m_LastLoadedLayoutName: +--- !u!114 &8 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12042, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_Children: [] + m_Position: + serializedVersion: 2 + x: 0 + y: 1008 + width: 2048 + height: 20 + m_MinSize: {x: 0, y: 0} + m_MaxSize: {x: 0, y: 0} +--- !u!114 &9 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12010, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_Children: + - {fileID: 10} + - {fileID: 5} + m_Position: + serializedVersion: 2 + x: 0 + y: 0 + width: 1632 + height: 978 + m_MinSize: {x: 406, y: 494} + m_MaxSize: {x: 10002, y: 14044} + vertical: 1 + controlID: 51 +--- !u!114 &10 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12010, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_Children: + - {fileID: 4} + - {fileID: 11} + m_Position: + serializedVersion: 2 + x: 0 + y: 0 + width: 1632 + height: 592 + m_MinSize: {x: 406, y: 222} + m_MaxSize: {x: 8006, y: 4022} + vertical: 0 + controlID: 52 +--- !u!114 &11 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12006, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_Children: [] + m_Position: + serializedVersion: 2 + x: 403 + y: 0 + width: 1229 + height: 592 + m_MinSize: {x: 204, y: 222} + m_MaxSize: {x: 4004, y: 4022} + m_ActualView: {fileID: 16} + m_Panes: + - {fileID: 16} + - {fileID: 17} + - {fileID: 12} + m_Selected: 0 + m_LastSelected: 1 +--- !u!114 &12 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12111, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_MinSize: {x: 400, y: 100} + m_MaxSize: {x: 2048, y: 2048} + m_TitleContent: + m_Text: Asset Store + m_Image: {fileID: 357073275683767465, guid: 0000000000000000d000000000000000, + type: 0} + m_Tooltip: + m_Pos: + serializedVersion: 2 + x: 468 + y: 181 + width: 973 + height: 501 + m_ViewDataDictionary: {fileID: 0} +--- !u!114 &13 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12014, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_MinSize: {x: 230, y: 250} + m_MaxSize: {x: 10000, y: 10000} + m_TitleContent: + m_Text: Project + m_Image: {fileID: -7501376956915960154, guid: 0000000000000000d000000000000000, + type: 0} + m_Tooltip: + m_Pos: + serializedVersion: 2 + x: 11.2 + y: -486.39996 + width: 1632 + height: 367 + m_ViewDataDictionary: {fileID: 0} + m_SearchFilter: + m_NameFilter: + m_ClassNames: [] + m_AssetLabels: [] + m_AssetBundleNames: [] + m_VersionControlStates: [] + m_SoftLockControlStates: [] + m_ReferencingInstanceIDs: + m_SceneHandles: + m_ShowAllHits: 0 + m_SkipHidden: 0 + m_SearchArea: 1 + m_Folders: + - Assets + m_ViewMode: 1 + m_StartGridSize: 64 + m_LastFolders: + - Assets + m_LastFoldersGridSize: -1 + m_LastProjectPath: C:\Users\MathieuBergounioux\source\repos\Kerbal-VR\KerbalVR + m_LockTracker: + m_IsLocked: 0 + m_FolderTreeState: + scrollPos: {x: 0, y: 0} + m_SelectedIDs: 724c0000 + m_LastClickedID: 19570 + m_ExpandedIDs: 0000000000ca9a3b + m_RenameOverlay: + m_UserAcceptedRename: 0 + m_Name: + m_OriginalName: + m_EditFieldRect: + serializedVersion: 2 + x: 0 + y: 0 + width: 0 + height: 0 + m_UserData: 0 + m_IsWaitingForDelay: 0 + m_IsRenaming: 0 + m_OriginalEventType: 11 + m_IsRenamingFilename: 1 + m_ClientGUIView: {fileID: 0} + m_SearchString: + m_CreateAssetUtility: + m_EndAction: {fileID: 0} + m_InstanceID: 0 + m_Path: + m_Icon: {fileID: 0} + m_ResourceFile: + m_AssetTreeState: + scrollPos: {x: 0, y: 0} + m_SelectedIDs: + m_LastClickedID: 0 + m_ExpandedIDs: + m_RenameOverlay: + m_UserAcceptedRename: 0 + m_Name: + m_OriginalName: + m_EditFieldRect: + serializedVersion: 2 + x: 0 + y: 0 + width: 0 + height: 0 + m_UserData: 0 + m_IsWaitingForDelay: 0 + m_IsRenaming: 0 + m_OriginalEventType: 11 + m_IsRenamingFilename: 1 + m_ClientGUIView: {fileID: 0} + m_SearchString: + m_CreateAssetUtility: + m_EndAction: {fileID: 0} + m_InstanceID: 0 + m_Path: + m_Icon: {fileID: 0} + m_ResourceFile: + m_ListAreaState: + m_SelectedInstanceIDs: + m_LastClickedInstanceID: 0 + m_HadKeyboardFocusLastEvent: 0 + m_ExpandedInstanceIDs: c6230000 + m_RenameOverlay: + m_UserAcceptedRename: 0 + m_Name: + m_OriginalName: + m_EditFieldRect: + serializedVersion: 2 + x: 0 + y: 0 + width: 0 + height: 0 + m_UserData: 0 + m_IsWaitingForDelay: 0 + m_IsRenaming: 0 + m_OriginalEventType: 11 + m_IsRenamingFilename: 1 + m_ClientGUIView: {fileID: 0} + m_CreateAssetUtility: + m_EndAction: {fileID: 0} + m_InstanceID: 0 + m_Path: + m_Icon: {fileID: 0} + m_ResourceFile: + m_NewAssetIndexInList: -1 + m_ScrollPosition: {x: 0, y: 0} + m_GridSize: 64 + m_SkipHiddenPackages: 0 + m_DirectoriesAreaWidth: 115 +--- !u!114 &14 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12019, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_MinSize: {x: 275, y: 50} + m_MaxSize: {x: 4000, y: 4000} + m_TitleContent: + m_Text: Inspector + m_Image: {fileID: -6905738622615590433, guid: 0000000000000000d000000000000000, + type: 0} + m_Tooltip: + m_Pos: + serializedVersion: 2 + x: 1643.2 + y: -1078.4 + width: 414 + height: 959 + m_ViewDataDictionary: {fileID: 0} + m_OpenAddComponentMenu: 0 + m_ObjectsLockedBeforeSerialization: [] + m_InstanceIDsLockedBeforeSerialization: + m_LockTracker: + m_IsLocked: 0 + m_PreviewResizer: + m_CachedPref: 160 + m_ControlHash: -371814159 + m_PrefName: Preview_InspectorPreview + m_PreviewWindow: {fileID: 0} +--- !u!114 &15 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12061, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_MinSize: {x: 200, y: 200} + m_MaxSize: {x: 4000, y: 4000} + m_TitleContent: + m_Text: Hierarchy + m_Image: {fileID: -590624980919486359, guid: 0000000000000000d000000000000000, + type: 0} + m_Tooltip: + m_Pos: + serializedVersion: 2 + x: 11.2 + y: -1078.4 + width: 403 + height: 573 + m_ViewDataDictionary: {fileID: 0} + m_SceneHierarchy: + m_TreeViewState: + scrollPos: {x: 0, y: 0} + m_SelectedIDs: + m_LastClickedID: 0 + m_ExpandedIDs: 26d7ffff + m_RenameOverlay: + m_UserAcceptedRename: 0 + m_Name: + m_OriginalName: + m_EditFieldRect: + serializedVersion: 2 + x: 0 + y: 0 + width: 0 + height: 0 + m_UserData: 0 + m_IsWaitingForDelay: 0 + m_IsRenaming: 0 + m_OriginalEventType: 11 + m_IsRenamingFilename: 0 + m_ClientGUIView: {fileID: 0} + m_SearchString: + m_ExpandedScenes: [] + m_CurrenRootInstanceID: 0 + m_LockTracker: + m_IsLocked: 0 + m_CurrentSortingName: TransformSorting + m_WindowGUID: 4cdb5ba75b10c254e864619070e3bc7c +--- !u!114 &16 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12013, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_MinSize: {x: 200, y: 200} + m_MaxSize: {x: 4000, y: 4000} + m_TitleContent: + m_Text: Scene + m_Image: {fileID: 2318424515335265636, guid: 0000000000000000d000000000000000, + type: 0} + m_Tooltip: + m_Pos: + serializedVersion: 2 + x: 414.40002 + y: -1078.4 + width: 1227 + height: 573 + m_ViewDataDictionary: {fileID: 0} + m_ShowContextualTools: 0 + m_WindowGUID: e8420506870631a4e8d0ee01d3f686df + m_Gizmos: 1 + m_SceneIsLit: 1 + m_SceneLighting: 1 + m_2DMode: 0 + m_isRotationLocked: 0 + m_PlayAudio: 0 + m_AudioPlay: 0 + m_Position: + m_Target: {x: 0, y: 0, z: 0} + speed: 2 + m_Value: {x: 0, y: 0, z: 0} + m_RenderMode: 0 + m_CameraMode: + drawMode: 0 + name: Shaded + section: Shading Mode + m_ValidateTrueMetals: 0 + m_DoValidateTrueMetals: 0 + m_SceneViewState: + showFog: 1 + showMaterialUpdate: 0 + showSkybox: 1 + showFlares: 1 + showImageEffects: 1 + showParticleSystems: 1 + grid: + xGrid: + m_Target: 0 + speed: 2 + m_Value: 0 + yGrid: + m_Target: 1 + speed: 2 + m_Value: 1 + zGrid: + m_Target: 0 + speed: 2 + m_Value: 0 + m_Rotation: + m_Target: {x: -0.08717229, y: 0.89959055, z: -0.21045254, w: -0.3726226} + speed: 2 + m_Value: {x: -0.08717229, y: 0.89959055, z: -0.21045254, w: -0.3726226} + m_Size: + m_Target: 10 + speed: 2 + m_Value: 10 + m_Ortho: + m_Target: 0 + speed: 2 + m_Value: 0 + m_CameraSettings: + m_Speed: 1 + m_SpeedNormalized: 0.5 + m_SpeedMin: 0.01 + m_SpeedMax: 2 + m_EasingEnabled: 1 + m_EasingDuration: 0.4 + m_AccelerationEnabled: 1 + m_FieldOfView: 90 + m_NearClip: 0.03 + m_FarClip: 10000 + m_DynamicClip: 1 + m_OcclusionCulling: 0 + m_ShowGlobalGrid: 1 + m_LastSceneViewRotation: {x: 0, y: 0, z: 0, w: 0} + m_LastSceneViewOrtho: 0 + m_ReplacementShader: {fileID: 0} + m_ReplacementString: + m_SceneVisActive: 1 + m_LastLockedObject: {fileID: 0} + m_ViewIsLockedToObject: 0 +--- !u!114 &17 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12015, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_MinSize: {x: 200, y: 200} + m_MaxSize: {x: 4000, y: 4000} + m_TitleContent: + m_Text: Game + m_Image: {fileID: -2087823869225018852, guid: 0000000000000000d000000000000000, + type: 0} + m_Tooltip: + m_Pos: + serializedVersion: 2 + x: 507 + y: 94 + width: 1532 + height: 790 + m_ViewDataDictionary: {fileID: 0} + m_VSyncEnabled: 0 + m_MaximizeOnPlay: 0 + m_Gizmos: 0 + m_Stats: 0 + m_SelectedSizes: 00000000000000000000000000000000000000000000000000000000000000000000000000000000 + m_TargetDisplay: 0 + m_ZoomArea: + m_HRangeLocked: 0 + m_VRangeLocked: 0 + hZoomLockedByDefault: 0 + vZoomLockedByDefault: 0 + m_HBaseRangeMin: -766 + m_HBaseRangeMax: 766 + m_VBaseRangeMin: -386.5 + m_VBaseRangeMax: 386.5 + m_HAllowExceedBaseRangeMin: 1 + m_HAllowExceedBaseRangeMax: 1 + m_VAllowExceedBaseRangeMin: 1 + m_VAllowExceedBaseRangeMax: 1 + m_ScaleWithWindow: 0 + m_HSlider: 0 + m_VSlider: 0 + m_IgnoreScrollWheelUntilClicked: 0 + m_EnableMouseInput: 1 + m_EnableSliderZoomHorizontal: 0 + m_EnableSliderZoomVertical: 0 + m_UniformScale: 1 + m_UpDirection: 1 + m_DrawArea: + serializedVersion: 2 + x: 0 + y: 17 + width: 1532 + height: 773 + m_Scale: {x: 1, y: 1} + m_Translation: {x: 766, y: 386.5} + m_MarginLeft: 0 + m_MarginRight: 0 + m_MarginTop: 0 + m_MarginBottom: 0 + m_LastShownAreaInsideMargins: + serializedVersion: 2 + x: -766 + y: -386.5 + width: 1532 + height: 773 + m_MinimalGUI: 1 + m_defaultScale: 1 + m_TargetTexture: {fileID: 0} + m_CurrentColorSpace: 1 + m_LastWindowPixelSize: {x: 1532, y: 790} + m_ClearInEditMode: 1 + m_NoCameraWarning: 1 + m_LowResolutionForAspectRatios: 01000000000000000000 + m_XRRenderMode: 0 +--- !u!114 &18 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12003, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_MinSize: {x: 100, y: 100} + m_MaxSize: {x: 4000, y: 4000} + m_TitleContent: + m_Text: Console + m_Image: {fileID: 111653112392082826, guid: 0000000000000000d000000000000000, + type: 0} + m_Tooltip: + m_Pos: + serializedVersion: 2 + x: 8 + y: 718 + width: 1366 + height: 308 + m_ViewDataDictionary: {fileID: 0} diff --git a/KerbalVR/Library/EditorUserBuildSettings.asset b/KerbalVR/Library/EditorUserBuildSettings.asset new file mode 100644 index 00000000..b9ed8bf3 Binary files /dev/null and b/KerbalVR/Library/EditorUserBuildSettings.asset differ diff --git a/KerbalVR/Library/EditorUserSettings.asset b/KerbalVR/Library/EditorUserSettings.asset new file mode 100644 index 00000000..a66c287f --- /dev/null +++ b/KerbalVR/Library/EditorUserSettings.asset @@ -0,0 +1,21 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!162 &1 +EditorUserSettings: + m_ObjectHideFlags: 0 + serializedVersion: 4 + m_ConfigSettings: + vcSharedLogLevel: + value: 0d5e400f0650 + flags: 0 + m_VCAutomaticAdd: 1 + m_VCDebugCom: 0 + m_VCDebugCmd: 0 + m_VCDebugOut: 0 + m_SemanticMergeMode: 2 + m_VCShowFailedCheckout: 1 + m_VCOverwriteFailedCheckoutAssets: 1 + m_VCAllowAsyncUpdate: 0 + m_AssetPipelineMode: 0 + m_CacheServerMode: 0 + m_CacheServers: [] diff --git a/KerbalVR/Library/InspectorExpandedItems.asset b/KerbalVR/Library/InspectorExpandedItems.asset new file mode 100644 index 00000000..10769034 Binary files /dev/null and b/KerbalVR/Library/InspectorExpandedItems.asset differ diff --git a/KerbalVR/Library/LastSceneManagerSetup.txt b/KerbalVR/Library/LastSceneManagerSetup.txt new file mode 100644 index 00000000..dd18ea70 --- /dev/null +++ b/KerbalVR/Library/LastSceneManagerSetup.txt @@ -0,0 +1 @@ +sceneSetups: [] diff --git a/KerbalVR/Library/LibraryFormatVersion.txt b/KerbalVR/Library/LibraryFormatVersion.txt new file mode 100644 index 00000000..6185f096 --- /dev/null +++ b/KerbalVR/Library/LibraryFormatVersion.txt @@ -0,0 +1,2 @@ +unityRebuildLibraryVersion: 11 +unityForwardCompatibleVersion: 40 diff --git a/KerbalVR/Library/MonoManager.asset b/KerbalVR/Library/MonoManager.asset new file mode 100644 index 00000000..b2508975 Binary files /dev/null and b/KerbalVR/Library/MonoManager.asset differ diff --git a/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/CHANGELOG.md b/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/CHANGELOG.md new file mode 100644 index 00000000..ceaa4264 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/CHANGELOG.md @@ -0,0 +1,37 @@ + +[1.0.1] + +Adding Readme file +Adding local plugin importer callbacks. +Removing Bintray references in package.json + +[2.0.3] + +Fix bug where importing the asset store ads package would cause duiplicate symbols, +and removing the asset store ads package would cause missing symbols. + +[2.0.4] + +Added new description string to package.json +Fixed art assets to use no compression (fixes issue switching between iOS and PC builds) + +[2.0.5] - 2018-03-29 + +Fix for https://fogbugz.unity3d.com/f/cases/1011363 +Fixes an incorrect guid that the importer used to include/exclude the runtime assembly from the build. + +[2.0.6] - 2018-03-29 + +Update changelog for this and 2.0.5 + +[2.0.7] - 2018-04-06 + +Fix editor assembly project file to include the importer script. + +[2.0.8] - 2018-05-01 + +Add call to SetShouldOverridePredicate to exclude package dll when asset store dlls are present. +Update unity version attribute to support 2017.4 LTS + +Fix an issue with the editor assembly to add back in some iOS platform specific code that was removed +via conditionals (which is fine for source packages, but doesn't work with precompiled assemblies) diff --git a/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/Resources/Android/builds/unity-ads.aar b/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/Resources/Android/builds/unity-ads.aar new file mode 100644 index 00000000..a05fc299 Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/Resources/Android/builds/unity-ads.aar differ diff --git a/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/Resources/Editor/landscape.jpg b/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/Resources/Editor/landscape.jpg new file mode 100644 index 00000000..4fa7f280 Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/Resources/Editor/landscape.jpg differ diff --git a/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/Resources/Editor/portrait.jpg b/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/Resources/Editor/portrait.jpg new file mode 100644 index 00000000..5d8fb0b9 Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/Resources/Editor/portrait.jpg differ diff --git a/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/Resources/iOS/builds/UnityAds.framework/Headers/UADSInAppPurchaseMetaData.h b/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/Resources/iOS/builds/UnityAds.framework/Headers/UADSInAppPurchaseMetaData.h new file mode 100644 index 00000000..8edc8c14 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/Resources/iOS/builds/UnityAds.framework/Headers/UADSInAppPurchaseMetaData.h @@ -0,0 +1,11 @@ +#import "UADSMetaData.h" + +@interface UADSInAppPurchaseMetaData : UADSMetaData + +- (void)setProductId:(NSString *)productId; +- (void)setPrice:(NSNumber *)price; +- (void)setCurrency:(NSString *)currency; +- (void)setReceiptPurchaseData:(NSString *)receiptPurchaseData; +- (void)setSignature:(NSString *)signature; + +@end diff --git a/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/Resources/iOS/builds/UnityAds.framework/Headers/UADSJsonStorage.h b/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/Resources/iOS/builds/UnityAds.framework/Headers/UADSJsonStorage.h new file mode 100644 index 00000000..1ed3c431 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/Resources/iOS/builds/UnityAds.framework/Headers/UADSJsonStorage.h @@ -0,0 +1,13 @@ +@interface UADSJsonStorage : NSObject + +@property (nonatomic, strong) NSMutableDictionary *storageContents; + +- (BOOL)set:(NSString *)key value:(id)value; +- (id)getValueForKey:(NSString *)key; +- (BOOL)deleteKey:(NSString *)key; +- (NSArray *)getKeys:(NSString *)key recursive:(BOOL)recursive; +- (void)clearData; +- (BOOL)initData; +- (BOOL)hasData; + +@end diff --git a/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/Resources/iOS/builds/UnityAds.framework/Headers/UADSMediationMetaData.h b/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/Resources/iOS/builds/UnityAds.framework/Headers/UADSMediationMetaData.h new file mode 100644 index 00000000..5f49a285 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/Resources/iOS/builds/UnityAds.framework/Headers/UADSMediationMetaData.h @@ -0,0 +1,9 @@ +#import "UADSMetaData.h" + +@interface UADSMediationMetaData : UADSMetaData + +- (void)setName:(NSString *)mediationNetworkName; +- (void)setVersion:(NSString *)mediationSdkVersion; +- (void)setOrdinal:(int)mediationOrdinal; + +@end \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/Resources/iOS/builds/UnityAds.framework/Headers/UADSMetaData.h b/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/Resources/iOS/builds/UnityAds.framework/Headers/UADSMetaData.h new file mode 100644 index 00000000..791d3138 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/Resources/iOS/builds/UnityAds.framework/Headers/UADSMetaData.h @@ -0,0 +1,12 @@ + + +@interface UADSMetaData : NSObject + +@property (nonatomic, strong) NSString *category; +@property (nonatomic, strong) NSMutableDictionary *entries; + +- (instancetype)initWithCategory:(NSString *)category; +- (void)set:(NSString *)key value:(id)value; +- (void)commit; + +@end \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/Resources/iOS/builds/UnityAds.framework/Headers/UADSPlayerMetaData.h b/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/Resources/iOS/builds/UnityAds.framework/Headers/UADSPlayerMetaData.h new file mode 100644 index 00000000..5d0db483 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/Resources/iOS/builds/UnityAds.framework/Headers/UADSPlayerMetaData.h @@ -0,0 +1,7 @@ +#import "UADSMetaData.h" + +@interface UADSPlayerMetaData : UADSMetaData + +- (void)setServerId:(NSString *)serverId; + +@end \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/Resources/iOS/builds/UnityAds.framework/Headers/UnityAds.h b/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/Resources/iOS/builds/UnityAds.framework/Headers/UnityAds.h new file mode 100644 index 00000000..8e1ccfda --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/Resources/iOS/builds/UnityAds.framework/Headers/UnityAds.h @@ -0,0 +1,255 @@ +#import + +#import +#import + +/** + * An enumerate that describes the state of `UnityAds` placements. + * @note All placement states, other than `kUnityAdsPlacementStateReady`, indicate that the placement is not currently ready to show ads. + */ +typedef NS_ENUM(NSInteger, UnityAdsPlacementState) { + /** + * A state that indicates that the placement is ready to show an ad. The `show:` selector can be called. + */ + kUnityAdsPlacementStateReady, + /** + * A state that indicates that no state is information is available. + * @warning This state can that UnityAds is not initialized or that the placement is not correctly configured in the Unity Ads admin tool. + */ + kUnityAdsPlacementStateNotAvailable, + /** + * A state that indicates that the placement is currently disabled. The placement can be enabled in the Unity Ads admin tools. + */ + kUnityAdsPlacementStateDisabled, + /** + * A state that indicates that the placement is not currently ready, but will be in the future. + * @note This state most likely indicates that the ad content is currently caching. + */ + kUnityAdsPlacementStateWaiting, + /** + * A state that indicates that the placement is properly configured, but there are currently no ads available for the placement. + */ + kUnityAdsPlacementStateNoFill +}; + +/** + * An enumeration for the completion state of an ad. + */ +typedef NS_ENUM(NSInteger, UnityAdsFinishState) { + /** + * A state that indicates that the ad did not successfully display. + */ + kUnityAdsFinishStateError, + /** + * A state that indicates that the user skipped the ad. + */ + kUnityAdsFinishStateSkipped, + /** + * A state that indicates that the ad was played entirely. + */ + kUnityAdsFinishStateCompleted +}; + +/** + * An enumeration for the various errors that can be emitted through the `UnityAdsDelegate` `unityAdsDidError:withMessage:` method. + */ +typedef NS_ENUM(NSInteger, UnityAdsError) { + /** + * An error that indicates failure due to `UnityAds` currently being uninitialized. + */ + kUnityAdsErrorNotInitialized = 0, + /** + * An error that indicates failure due to a failure in the initialization process. + */ + kUnityAdsErrorInitializedFailed, + /** + * An error that indicates failure due to attempting to initialize `UnityAds` with invalid parameters. + */ + kUnityAdsErrorInvalidArgument, + /** + * An error that indicates failure of the video player. + */ + kUnityAdsErrorVideoPlayerError, + /** + * An error that indicates failure due to having attempted to initialize the `UnityAds` class in an invalid environment. + */ + kUnityAdsErrorInitSanityCheckFail, + /** + * An error that indicates failure due to the presence of an ad blocker. + */ + kUnityAdsErrorAdBlockerDetected, + /** + * An error that indicates failure due to inability to read or write a file. + */ + kUnityAdsErrorFileIoError, + /** + * An error that indicates failure due to a bad device identifier. + */ + kUnityAdsErrorDeviceIdError, + /** + * An error that indicates a failure when attempting to show an ad. + */ + kUnityAdsErrorShowError, + /** + * An error that indicates an internal failure in `UnityAds`. + */ + kUnityAdsErrorInternalError, +}; + +/** + * The `UnityAdsDelegate` protocol defines the required methods for receiving messages from UnityAds. + * Must be implemented by the hosting app. + * The unityAdsReady: method is called when it's possible to show an ad. + * All other methods are used to provide notifications of events of the ad lifecycle. + * @note On initialization, there are ready (or error) callbacks for each placement attached to the game identifier. + */ +NS_ASSUME_NONNULL_BEGIN +@protocol UnityAdsDelegate +/** + * Called when `UnityAds` is ready to show an ad. After this callback you can call the `UnityAds` `show:` method for this placement. + * Note that sometimes placement might no longer be ready due to exceptional reasons. These situations will give no new callbacks. + * + * @warning To avoid error situations, it is always best to check `isReady` method status before calling show. + * @param placementId The ID of the placement that is ready to show, as defined in Unity Ads admin tools. + */ +- (void)unityAdsReady:(NSString *)placementId; +/** + * Called when `UnityAds` encounters an error. All errors will be logged but this method can be used as an additional debugging aid. This callback can also be used for collecting statistics from different error scenarios. + * + * @param error A `UnityAdsError` error enum value indicating the type of error encountered. + * @param message A human readable string indicating the type of error encountered. + */ +- (void)unityAdsDidError:(UnityAdsError)error withMessage:(NSString *)message; +/** + * Called on a successful start of advertisement after calling the `UnityAds` `show:` method. + * + * @warning If there are errors in starting the advertisement, this method may never be called. Unity Ads will directly call `unityAdsDidFinish:withFinishState:` with error status. + * + * @param placementId The ID of the placement that has started, as defined in Unity Ads admin tools. + */ +- (void)unityAdsDidStart:(NSString *)placementId; +/** + * Called after the ad has closed. + * + * @param placementId The ID of the placement that has finished, as defined in Unity Ads admin tools. + * @param state An enum value indicating the finish state of the ad. Possible values are `Completed`, `Skipped`, and `Error`. + */ +- (void)unityAdsDidFinish:(NSString *)placementId + withFinishState:(UnityAdsFinishState)state; +@end + +/** + * `UnityAds` is a static class with methods for preparing and showing ads. + * + * @warning In order to ensure expected behaviour, the delegate must always be set. + */ + +@interface UnityAds : NSObject + +- (instancetype)init NS_UNAVAILABLE; ++ (instancetype)initialize NS_UNAVAILABLE; + +/** + * Initializes UnityAds. UnityAds should be initialized when app starts. + * + * @param gameId Unique identifier for a game, given by Unity Ads admin tools or Unity editor. + * @param delegate delegate for UnityAdsDelegate callbacks + */ ++ (void)initialize:(NSString *)gameId + delegate:(nullable id)delegate; +/** + * Initializes UnityAds. UnityAds should be initialized when app starts. + * + * @param gameId Unique identifier for a game, given by Unity Ads admin tools or Unity editor. + * @param delegate delegate for UnityAdsDelegate callbacks + * @param testMode Set this flag to `YES` to indicate test mode and show only test ads. + */ ++ (void)initialize:(NSString *)gameId + delegate:(nullable id)delegate + testMode:(BOOL)testMode; +/** + * Show an ad using the defaul placement. + * + * @param viewController The `UIViewController` that is to present the ad view controller. + */ ++ (void)show:(UIViewController *)viewController; +/** + * Show an ad using the provided placement ID. + * + * @param viewController The `UIViewController` that is to present the ad view controller. + * @param placementId The placement ID, as defined in Unity Ads admin tools. + */ ++ (void)show:(UIViewController *)viewController placementId:(NSString *)placementId; +/** + * Provides the currently assigned `UnityAdsDelegate`. + * + * @return The current `UnityAdsDelegate`. + */ ++ (id)getDelegate; +/** + * Allows the delegate to be reassigned after UnityAds has already been initialized. + * + * @param delegate The new `UnityAdsDelegate' for UnityAds to send callbacks to. + */ ++ (void)setDelegate:(id)delegate; +/** + * Get the current debug status of `UnityAds`. + * + * @return If `YES`, `UnityAds` will provide verbose logs. + */ ++ (BOOL)getDebugMode; +/** + * Set the logging verbosity of `UnityAds`. Debug mode indicates verbose logging. + * @warning Does not relate to test mode for ad content. + * @param enableDebugMode `YES` for verbose logging. + */ ++ (void)setDebugMode:(BOOL)enableDebugMode; +/** + * Check to see if the current device supports using Unity Ads. + * + * @return If `NO`, the current device cannot initialize `UnityAds` or show ads. + */ ++ (BOOL)isSupported; +/** + * Check if the default placement is ready to show an ad. + * + * @return If `YES`, the default placement is ready to show an ad. + */ ++ (BOOL)isReady; +/** + * Check if a particular placement is ready to show an ad. + * + * @param placementId The placement ID being checked. + * + * @return If `YES`, the placement is ready to show an ad. + */ ++ (BOOL)isReady:(NSString *)placementId; +/** + * Check the current state of the default placement. + * + * @return If this is `kUnityAdsPlacementStateReady`, the placement is ready to show ads. Other states represent errors. + */ ++ (UnityAdsPlacementState)getPlacementState; +/** + * Check the current state of a placement. + * + * @param placementId The placement ID, as defined in Unity Ads admin tools. + * + * @return If this is `kUnityAdsPlacementStateReady`, the placement is ready to show ads. Other states represent errors. + */ ++ (UnityAdsPlacementState)getPlacementState:(NSString *)placementId; +/** + * Check the version of this `UnityAds` SDK + * + * @return String representing the current version name. + */ ++ (NSString *)getVersion; +/** + * Check that `UnityAds` has been initialized. This might be useful for debugging initialization problems. + * + * @return If `YES`, Unity Ads has been successfully initialized. + */ ++ (BOOL)isInitialized; + +@end +NS_ASSUME_NONNULL_END \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/Resources/iOS/builds/UnityAds.framework/Headers/UnityAdsExtended.h b/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/Resources/iOS/builds/UnityAds.framework/Headers/UnityAdsExtended.h new file mode 100644 index 00000000..1435037b --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/Resources/iOS/builds/UnityAds.framework/Headers/UnityAdsExtended.h @@ -0,0 +1,21 @@ +#import "UnityAds.h" + +NS_ASSUME_NONNULL_BEGIN +@protocol UnityAdsExtendedDelegate +/** + * Called when a click event happens. + * + * @param placementId The ID of the placement that was clicked. + */ +- (void)unityAdsDidClick:(NSString *)placementId; + +/** + * Called when a placement changes state. + * + * @param placementId The ID of the placement that changed state. + * @param oldState The state before the change. + * @param newState The state after the change. + */ +- (void)unityAdsPlacementStateChanged:(NSString *)placementId oldState:(UnityAdsPlacementState)oldState newState:(UnityAdsPlacementState)newState; +@end +NS_ASSUME_NONNULL_END diff --git a/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/Resources/iOS/builds/UnityAds.framework/Headers/UnityAdsUnityDelegate.h b/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/Resources/iOS/builds/UnityAds.framework/Headers/UnityAdsUnityDelegate.h new file mode 100644 index 00000000..0fa6e362 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/Resources/iOS/builds/UnityAds.framework/Headers/UnityAdsUnityDelegate.h @@ -0,0 +1,11 @@ +#import "UnityAds.h" +NS_ASSUME_NONNULL_BEGIN +@protocol UnityAdsUnityDelegate +/** + * Called when an in-app purchase is initiated from an ad. + * + * @param eventString The string provided via the ad. + */ +- (void)unityAdsDidInitiatePurchase:(NSString *)eventString; +@end +NS_ASSUME_NONNULL_END diff --git a/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/Resources/iOS/builds/UnityAds.framework/Info.plist b/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/Resources/iOS/builds/UnityAds.framework/Info.plist new file mode 100644 index 00000000..31b03797 Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/Resources/iOS/builds/UnityAds.framework/Info.plist differ diff --git a/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/Resources/iOS/builds/UnityAds.framework/Modules/module.modulemap b/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/Resources/iOS/builds/UnityAds.framework/Modules/module.modulemap new file mode 100644 index 00000000..9b448d57 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/Resources/iOS/builds/UnityAds.framework/Modules/module.modulemap @@ -0,0 +1,7 @@ +framework module UnityAds { + umbrella header "UnityAds.h" + header "UnityAdsExtended.h" + + export * + module * { export * } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/Resources/iOS/builds/UnityAds.framework/UnityAds b/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/Resources/iOS/builds/UnityAds.framework/UnityAds new file mode 100644 index 00000000..53184164 Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/Resources/iOS/builds/UnityAds.framework/UnityAds differ diff --git a/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/UnityEditor.Advertisements.dll b/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/UnityEditor.Advertisements.dll new file mode 100644 index 00000000..77409dde Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/UnityEditor.Advertisements.dll differ diff --git a/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/UnityEditor.Advertisements.dll.mdb b/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/UnityEditor.Advertisements.dll.mdb new file mode 100644 index 00000000..7ee35e88 Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/Editor/UnityEditor.Advertisements.dll.mdb differ diff --git a/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/License.md b/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/License.md new file mode 100644 index 00000000..27c17ac4 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/License.md @@ -0,0 +1,32 @@ +**Unity Companion Package License v1.0 ("_License_")** + +Copyright © 2017 Unity Technologies ApS ("**_Unity_**") + +Unity hereby grants to you a worldwide, non-exclusive, no-charge, and royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, sublicense, and distribute the software that is made available with this License ("**_Software_**"), subject to the following terms and conditions: + +1. *Unity Companion Use Only*. Exercise of the license granted herein is limited to exercise for the creation, use, and/or distribution of applications, software, or other content pursuant to a valid Unity development engine software license ("**_Engine License_**"). That means while use of the Software is not limited to use in the software licensed under the Engine License, the Software may not be used for any purpose other than the creation, use, and/or distribution of Engine License-dependent applications, software, or other content. No other exercise of the license granted herein is permitted. + +1. *No Modification of Engine License*. Neither this License nor any exercise of the license granted herein modifies the Engine License in any way. + +1. *Ownership & Grant Back to You*. + + 3.1. You own your content. In this License, "derivative works" means derivatives of the Software itself--works derived only from the Software by you under this License (for example, modifying the code of the Software itself to improve its efficacy); “derivative works” of the Software do not include, for example, games, apps, or content that you create using the Software. You keep all right, title, and interest to your own content. + + 3.2. Unity owns its content. While you keep all right, title, and interest to your own content per the above, as between Unity and you, Unity will own all right, title, and interest to all intellectual property rights (including patent, trademark, and copyright) in the Software and derivative works of the Software, and you hereby assign and agree to assign all such rights in those derivative works to Unity. + + 3.3. You have a license to those derivative works. Subject to this License, Unity grants to you the same worldwide, non-exclusive, no-charge, and royalty-free copyright license to derivative works of the Software you create as is granted to you for the Software under this License. + +1. *Trademarks*. You are not granted any right or license under this License to use any trademarks, service marks, trade names, products names, or branding of Unity or its affiliates ("**_Trademarks_**"). Descriptive uses of Trademarks are permitted; see, for example, Unity’s Branding Usage Guidelines at [https://unity3d.com/public-relations/brand](https://unity3d.com/public-relations/brand). + +1. *Notices & Third-Party Rights*. This License, including the copyright notice above, must be provided in all substantial portions of the Software and derivative works thereof (or, if that is impracticable, in any other location where such notices are customarily placed). Further, if the Software is accompanied by a Unity "third-party notices" or similar file, you acknowledge and agree that software identified in that file is governed by those separate license terms. + +1. *DISCLAIMER, LIMITATION OF LIABILITY*. THE SOFTWARE AND ANY DERIVATIVE WORKS THEREOF IS PROVIDED ON AN "AS IS" BASIS, AND IS PROVIDED WITHOUT WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND/OR NONINFRINGEMENT. IN NO EVENT SHALL ANY COPYRIGHT HOLDER OR AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES (WHETHER DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL, INCLUDING PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, LOSS OF USE, DATA, OR PROFITS, AND BUSINESS INTERRUPTION), OR OTHER LIABILITY WHATSOEVER, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE, ARISING FROM OR OUT OF, OR IN CONNECTION WITH, THE SOFTWARE OR ANY DERIVATIVE WORKS THEREOF OR THE USE OF OR OTHER DEALINGS IN SAME, EVEN WHERE ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +1. *USE IS ACCEPTANCE and License Versions*. Your receipt and use of the Software constitutes your acceptance of this License and its terms and conditions. Software released by Unity under this License may be modified or updated and the License with it; upon any such modification or update, you will comply with the terms of the updated License for any use of any of the Software under the updated License. + +1. *Use in Compliance with Law and Termination*. Your exercise of the license granted herein will at all times be in compliance with applicable law and will not infringe any proprietary rights (including intellectual property rights); this License will terminate immediately on any breach by you of this License. + +1. *Severability*. If any provision of this License is held to be unenforceable or invalid, that provision will be enforced to the maximum extent possible and the other provisions will remain in full force and effect. + +1. *Governing Law and Venue*. This License is governed by and construed in accordance with the laws of Denmark, except for its conflict of laws rules; the United Nations Convention on Contracts for the International Sale of Goods will not apply. If you reside (or your principal place of business is) within the United States, you and Unity agree to submit to the personal and exclusive jurisdiction of and venue in the state and federal courts located in San Francisco County, California concerning any dispute arising out of this License ("**_Dispute_**"). If you reside (or your principal place of business is) outside the United States, you and Unity agree to submit to the personal and exclusive jurisdiction of and venue in the courts located in Copenhagen, Denmark concerning any Dispute. + diff --git a/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/README.md b/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/README.md new file mode 100644 index 00000000..9ed6019f --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/README.md @@ -0,0 +1,4 @@ +# Unity Ads + +Implementation of the Unity Ads API. + diff --git a/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/UnityEngine.Advertisements.dll b/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/UnityEngine.Advertisements.dll new file mode 100644 index 00000000..e9486522 Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/UnityEngine.Advertisements.dll differ diff --git a/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/UnityEngine.Advertisements.dll.mdb b/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/UnityEngine.Advertisements.dll.mdb new file mode 100644 index 00000000..5ec8e50d Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/UnityEngine.Advertisements.dll.mdb differ diff --git a/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/package.json b/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/package.json new file mode 100644 index 00000000..881daf2c --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ads@2.0.8/package.json @@ -0,0 +1,17 @@ +{ + "category": "AssetStore/Unity", + "description": "Unity Ads is a video ad network for iOS and Android that allows you to quickly and effectively monetize your games.", + "gitHead": "0d2114387a99011be685886f8ea902242e323e70", + "keywords": [ + "ads", + "unity" + ], + "name": "com.unity.ads", + "repoPackagePath": "build/install/com.unity.ads", + "repository": { + "type": "git", + "url": "ssh://git@github.com/Unity-Technologies/com.unity.ads.git" + }, + "unity": "2017.4", + "version": "2.0.8" +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/CHANGELOG.md b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/CHANGELOG.md new file mode 100644 index 00000000..dbb63e1a --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/CHANGELOG.md @@ -0,0 +1,67 @@ +## [3.3.2] - 2019-01-15 +- Update com.unity.ugui version dependency to new format. +- Add explicit dll dependencies to asmdefs needed for Test Platform changes. + +## [3.3.1] - 2018-11-21 +- Fixed missing dependency to com.unity.ugui to package.json + +## [3.3.0] - 2018-11-16 +- Removed dependency on UGUI extension in favor of new core package. + +## [3.2.2] - 2018-11-02 +- Removed FetchOptOutStatus and Initialize call. All application of opt out + status will be handled by the engine. The Analytics/Data Privacy package still + provides FetchPrivacyUrl to provide a URL from which to opt out. + +## [3.2.1] - 2018-10-25 +- Move editor and playmode tests to be packed within the package. + +## [3.2.0] - 2018-10-11 +- Prevent double-registration of standard events. +- Fixed build error on platforms that don't support analytics. +- Update package docs so they can be built and published and be accessible from + the Package Manager UI. +- Fixed a crash occurring on iOS device when the device has cellular capability + but was never configured with any carrier service. +- Fixed an android build failure occurring due to conflicting install referrer + AIDL files. + +## [3.1.1] - 2018-08-21 +- Add DataPrivacy plugin into package. +- Fixed an issue where Android project build would fail when proguard is enabled + in publishing settings. +- Fixed an issue where iOS product archive would fail because bitcode was not + enabled. + +## [3.0.9] - 2018-07-31 +- Fixing issue with NullReferenceException during editor playmode + +## [3.0.8] - 2018-07-26 +- Fixing linking issue when building Android il2cpp + +## [3.0.7] - 2018-07-10 +- Adding in continuous events for signal strength, battery level, battery + temperature, memory usage, available storage + +## [3.0.6] - 2018-06-01 +- Reorganizing platformInfo event around session start/resume/pause + +## [3.0.5] - 2018-05-29 +- Fixing cellular signal strength incorrect array format + +## [3.0.4] - 2018-05-04 +- Breaking change to only work with 2018.2 (change name of whitelisted dll's in + engine to conform to PackageManager standard) +- Changed name of old Analytics dll to the Unity.Analytics.Tracker.dll and + replaced the old one with the new platform information package. +- Changed naming convention of dlls to the PackageManager Standard: + Unity.Analytics.dll, Unity.Analytics.Editor.dll, Unity.Analytics.Tracker.dll, + Unity.Analytics.StandardEvents.dll. +- Deprecated old Analytics tracker and removed it from the add component menu. +- Merged Standardevents package into Analytics package. + +## [2.0.14] - 2018-02-08 +- Added proper documentation and better description text. + +## [2.0.5] - +- Update analytics tracker to 2.0 (1.0 version is still available) diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/DataPrivacy/AssemblyInfo.cs b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/DataPrivacy/AssemblyInfo.cs new file mode 100644 index 00000000..a97f2747 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/DataPrivacy/AssemblyInfo.cs @@ -0,0 +1,4 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Unity.Analytics.DataPrivacy.Tests")] +[assembly: InternalsVisibleTo("Unity.Analytics.DataPrivacy.WebRequest.Tests")] diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/DataPrivacy/DataPrivacy.cs b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/DataPrivacy/DataPrivacy.cs new file mode 100644 index 00000000..f48eb131 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/DataPrivacy/DataPrivacy.cs @@ -0,0 +1,132 @@ +#if ENABLE_CLOUD_SERVICES_ANALYTICS +using System; +using System.Text; +using UnityEngine.Networking; + +namespace UnityEngine.Analytics +{ + public class DataPrivacy + { + [Serializable] + internal struct UserPostData + { + public string appid; + public string userid; + public long sessionid; + public string platform; + public UInt32 platformid; + public string sdk_ver; + public bool debug_device; + public string deviceid; + public string plugin_ver; + } + + [Serializable] + internal struct TokenData + { + public string url; + public string token; + } + + const string kVersion = "3.0.0"; + const string kVersionString = "DataPrivacyPackage/" + kVersion; + + internal const string kBaseUrl = "https://data-optout-service.uca.cloud.unity3d.com"; + const string kTokenUrl = kBaseUrl + "/token"; + + internal static UserPostData GetUserData() + { + var postData = new UserPostData + { + appid = Application.cloudProjectId, + userid = AnalyticsSessionInfo.userId, + sessionid = AnalyticsSessionInfo.sessionId, + platform = Application.platform.ToString(), + platformid = (UInt32)Application.platform, + sdk_ver = Application.unityVersion, + debug_device = Debug.isDebugBuild, + deviceid = SystemInfo.deviceUniqueIdentifier, + plugin_ver = kVersionString + }; + + return postData; + } + + static string GetUserAgent() + { + var message = "UnityPlayer/{0} ({1}/{2}{3} {4})"; + return String.Format(message, + Application.unityVersion, + Application.platform.ToString(), + (UInt32)Application.platform, + Debug.isDebugBuild ? "-dev" : "", + kVersionString); + } + + static String getErrorString(UnityWebRequest www) + { + var json = www.downloadHandler.text; + var error = www.error; + if (String.IsNullOrEmpty(error)) + { + // 5.5 sometimes fails to parse an error response, and the only clue will be + // in www.responseHeadersString, which isn't accessible. + error = "Empty response"; + } + + if (!String.IsNullOrEmpty(json)) + { + error += ": " + json; + } + + return error; + } + + public static void FetchPrivacyUrl(Action success, Action failure = null) + { + string postJson = JsonUtility.ToJson(GetUserData()); + byte[] bytes = Encoding.UTF8.GetBytes(postJson); + var uploadHandler = new UploadHandlerRaw(bytes); + uploadHandler.contentType = "application/json"; + + var www = UnityWebRequest.Post(kTokenUrl, ""); + www.uploadHandler = uploadHandler; +#if !UNITY_WEBGL + www.SetRequestHeader("User-Agent", GetUserAgent()); +#endif + var async = www.SendWebRequest(); + + async.completed += (AsyncOperation async2) => + { + var json = www.downloadHandler.text; + if (!String.IsNullOrEmpty(www.error) || String.IsNullOrEmpty(json)) + { + var error = getErrorString(www); + if (failure != null) + { + failure(error); + } + } + else + { + TokenData tokenData; + tokenData.url = ""; // Just to quell "possibly unassigned" error + try + { + tokenData = JsonUtility.FromJson(json); + } + catch (Exception e) + { + if (failure != null) + { + failure(e.ToString()); + } + } + + success(tokenData.url); + } + }; + } + } +} +#endif //ENABLE_CLOUD_SERVICES_ANALYTICS diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/DataPrivacy/DataPrivacyButton.cs b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/DataPrivacy/DataPrivacyButton.cs new file mode 100644 index 00000000..412b430c --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/DataPrivacy/DataPrivacyButton.cs @@ -0,0 +1,52 @@ +#if ENABLE_CLOUD_SERVICES_ANALYTICS +using System; +using UnityEngine.UI; + +namespace UnityEngine.Analytics +{ + public class DataPrivacyButton : Button + { + bool urlOpened = false; + + DataPrivacyButton() + { + onClick.AddListener(OpenDataPrivacyUrl); + } + + void OnFailure(string reason) + { + interactable = true; + Debug.LogWarning(String.Format("Failed to get data privacy url: {0}", reason)); + } + + void OpenUrl(string url) + { + interactable = true; + urlOpened = true; + + #if UNITY_WEBGL && !UNITY_EDITOR + Application.ExternalEval("window.open(\"" + url + "\",\"_blank\")"); + #else + Application.OpenURL(url); + #endif + } + + void OpenDataPrivacyUrl() + { + interactable = false; + DataPrivacy.FetchPrivacyUrl(OpenUrl, OnFailure); + } + + void OnApplicationFocus(bool hasFocus) + { + if (hasFocus && urlOpened) + { + urlOpened = false; + // Immediately refresh the remote config so new privacy settings can be enabled + // as soon as possible if they have changed. + RemoteSettings.ForceUpdate(); + } + } + } +} +#endif //ENABLE_CLOUD_SERVICES_ANALYTICS diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/DataPrivacy/DataPrivacyButton.prefab b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/DataPrivacy/DataPrivacyButton.prefab new file mode 100644 index 00000000..53543550 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/DataPrivacy/DataPrivacyButton.prefab @@ -0,0 +1,246 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!1 &109074 +GameObject: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + serializedVersion: 4 + m_Component: + - 224: {fileID: 22409074} + - 222: {fileID: 22209074} + - 114: {fileID: 11409072} + m_Layer: 5 + m_Name: Image + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!1 &109076 +GameObject: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + serializedVersion: 4 + m_Component: + - 224: {fileID: 22409076} + - 222: {fileID: 22209076} + - 114: {fileID: 11409074} + - 114: {fileID: 11409076} + m_Layer: 5 + m_Name: DataPrivacyButton + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!1 &109078 +GameObject: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + serializedVersion: 4 + m_Component: + - 224: {fileID: 22409078} + - 222: {fileID: 22209078} + - 114: {fileID: 11409078} + m_Layer: 0 + m_Name: Text + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!114 &11409072 +MonoBehaviour: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 109074} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: -765806418, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: .196078405, g: .196078405, b: .196078405, a: 1} + m_Sprite: {fileID: 21300000, guid: 599a5fd92bab81a4ab02e52d0b1b1c60, type: 3} + m_Type: 0 + m_PreserveAspect: 0 + m_FillCenter: 1 + m_FillMethod: 4 + m_FillAmount: 1 + m_FillClockwise: 1 + m_FillOrigin: 0 +--- !u!114 &11409074 +MonoBehaviour: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 109076} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: -765806418, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 1, g: 1, b: 1, a: 1} + m_Sprite: {fileID: 10905, guid: 0000000000000000f000000000000000, type: 0} + m_Type: 1 + m_PreserveAspect: 0 + m_FillCenter: 1 + m_FillMethod: 4 + m_FillAmount: 1 + m_FillClockwise: 1 + m_FillOrigin: 0 +--- !u!114 &11409076 +MonoBehaviour: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 109076} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: a5ebb11c6fc3a2f498bd89593f7744aa, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Navigation: + m_Mode: 3 + m_SelectOnUp: {fileID: 0} + m_SelectOnDown: {fileID: 0} + m_SelectOnLeft: {fileID: 0} + m_SelectOnRight: {fileID: 0} + m_Transition: 1 + m_Colors: + m_NormalColor: {r: 1, g: 1, b: 1, a: 1} + m_HighlightedColor: {r: .960784316, g: .960784316, b: .960784316, a: 1} + m_PressedColor: {r: .784313738, g: .784313738, b: .784313738, a: 1} + m_DisabledColor: {r: .784313738, g: .784313738, b: .784313738, a: .501960814} + m_ColorMultiplier: 1 + m_FadeDuration: .100000001 + m_SpriteState: + m_HighlightedSprite: {fileID: 0} + m_PressedSprite: {fileID: 0} + m_DisabledSprite: {fileID: 0} + m_AnimationTriggers: + m_NormalTrigger: Normal + m_HighlightedTrigger: Highlighted + m_PressedTrigger: Pressed + m_DisabledTrigger: Disabled + m_Interactable: 1 + m_TargetGraphic: {fileID: 11409074} + m_OnClick: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.Button+ButtonClickedEvent, UnityEngine.UI, Version=1.0.0.0, + Culture=neutral, PublicKeyToken=null +--- !u!114 &11409078 +MonoBehaviour: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 109078} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 708705254, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: .196078405, g: .196078405, b: .196078405, a: 1} + m_FontData: + m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} + m_FontSize: 14 + m_FontStyle: 0 + m_BestFit: 0 + m_MinSize: 10 + m_MaxSize: 40 + m_Alignment: 4 + m_RichText: 0 + m_HorizontalOverflow: 0 + m_VerticalOverflow: 0 + m_LineSpacing: 1 + m_Text: Open Data Privacy Page +--- !u!222 &22209074 +CanvasRenderer: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 109074} +--- !u!222 &22209076 +CanvasRenderer: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 109076} +--- !u!222 &22209078 +CanvasRenderer: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 109078} +--- !u!224 &22409074 +RectTransform: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 109074} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 22409076} + m_RootOrder: 1 + m_AnchorMin: {x: 1, y: .5} + m_AnchorMax: {x: 1, y: .5} + m_AnchoredPosition: {x: -8, y: 0} + m_SizeDelta: {x: 20, y: 20} + m_Pivot: {x: 1, y: .5} +--- !u!224 &22409076 +RectTransform: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 109076} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 22409078} + - {fileID: 22409074} + m_Father: {fileID: 0} + m_RootOrder: 0 + m_AnchorMin: {x: .5, y: .5} + m_AnchorMax: {x: .5, y: .5} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 200, y: 30} + m_Pivot: {x: .5, y: .5} +--- !u!224 &22409078 +RectTransform: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 109078} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 22409076} + m_RootOrder: 0 + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: .850000024, y: 1} + m_AnchoredPosition: {x: 8, y: 0} + m_SizeDelta: {x: -12, y: 0} + m_Pivot: {x: 0, y: .5} +--- !u!1001 &100100000 +Prefab: + m_ObjectHideFlags: 1 + serializedVersion: 2 + m_Modification: + m_TransformParent: {fileID: 0} + m_Modifications: [] + m_RemovedComponents: [] + m_ParentPrefab: {fileID: 0} + m_RootGameObject: {fileID: 109076} + m_IsPrefabParent: 1 + m_IsExploded: 1 diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/DataPrivacy/DataPrivacyIcon.png b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/DataPrivacy/DataPrivacyIcon.png new file mode 100644 index 00000000..564b374b Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/DataPrivacy/DataPrivacyIcon.png differ diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/DataPrivacy/Unity.Analytics.DataPrivacy.asmdef b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/DataPrivacy/Unity.Analytics.DataPrivacy.asmdef new file mode 100644 index 00000000..0bf89c3e --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/DataPrivacy/Unity.Analytics.DataPrivacy.asmdef @@ -0,0 +1,8 @@ +{ + "name": "Unity.Analytics.DataPrivacy", + "references": ["Unity.ugui"], + "optionalUnityReferences": [], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": false +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Editor/AnalyticsEventTracker icon.png b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Editor/AnalyticsEventTracker icon.png new file mode 100644 index 00000000..23763936 Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Editor/AnalyticsEventTracker icon.png differ diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/License.md b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/License.md new file mode 100644 index 00000000..27c17ac4 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/License.md @@ -0,0 +1,32 @@ +**Unity Companion Package License v1.0 ("_License_")** + +Copyright © 2017 Unity Technologies ApS ("**_Unity_**") + +Unity hereby grants to you a worldwide, non-exclusive, no-charge, and royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, sublicense, and distribute the software that is made available with this License ("**_Software_**"), subject to the following terms and conditions: + +1. *Unity Companion Use Only*. Exercise of the license granted herein is limited to exercise for the creation, use, and/or distribution of applications, software, or other content pursuant to a valid Unity development engine software license ("**_Engine License_**"). That means while use of the Software is not limited to use in the software licensed under the Engine License, the Software may not be used for any purpose other than the creation, use, and/or distribution of Engine License-dependent applications, software, or other content. No other exercise of the license granted herein is permitted. + +1. *No Modification of Engine License*. Neither this License nor any exercise of the license granted herein modifies the Engine License in any way. + +1. *Ownership & Grant Back to You*. + + 3.1. You own your content. In this License, "derivative works" means derivatives of the Software itself--works derived only from the Software by you under this License (for example, modifying the code of the Software itself to improve its efficacy); “derivative works” of the Software do not include, for example, games, apps, or content that you create using the Software. You keep all right, title, and interest to your own content. + + 3.2. Unity owns its content. While you keep all right, title, and interest to your own content per the above, as between Unity and you, Unity will own all right, title, and interest to all intellectual property rights (including patent, trademark, and copyright) in the Software and derivative works of the Software, and you hereby assign and agree to assign all such rights in those derivative works to Unity. + + 3.3. You have a license to those derivative works. Subject to this License, Unity grants to you the same worldwide, non-exclusive, no-charge, and royalty-free copyright license to derivative works of the Software you create as is granted to you for the Software under this License. + +1. *Trademarks*. You are not granted any right or license under this License to use any trademarks, service marks, trade names, products names, or branding of Unity or its affiliates ("**_Trademarks_**"). Descriptive uses of Trademarks are permitted; see, for example, Unity’s Branding Usage Guidelines at [https://unity3d.com/public-relations/brand](https://unity3d.com/public-relations/brand). + +1. *Notices & Third-Party Rights*. This License, including the copyright notice above, must be provided in all substantial portions of the Software and derivative works thereof (or, if that is impracticable, in any other location where such notices are customarily placed). Further, if the Software is accompanied by a Unity "third-party notices" or similar file, you acknowledge and agree that software identified in that file is governed by those separate license terms. + +1. *DISCLAIMER, LIMITATION OF LIABILITY*. THE SOFTWARE AND ANY DERIVATIVE WORKS THEREOF IS PROVIDED ON AN "AS IS" BASIS, AND IS PROVIDED WITHOUT WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND/OR NONINFRINGEMENT. IN NO EVENT SHALL ANY COPYRIGHT HOLDER OR AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES (WHETHER DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL, INCLUDING PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, LOSS OF USE, DATA, OR PROFITS, AND BUSINESS INTERRUPTION), OR OTHER LIABILITY WHATSOEVER, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE, ARISING FROM OR OUT OF, OR IN CONNECTION WITH, THE SOFTWARE OR ANY DERIVATIVE WORKS THEREOF OR THE USE OF OR OTHER DEALINGS IN SAME, EVEN WHERE ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +1. *USE IS ACCEPTANCE and License Versions*. Your receipt and use of the Software constitutes your acceptance of this License and its terms and conditions. Software released by Unity under this License may be modified or updated and the License with it; upon any such modification or update, you will comply with the terms of the updated License for any use of any of the Software under the updated License. + +1. *Use in Compliance with Law and Termination*. Your exercise of the license granted herein will at all times be in compliance with applicable law and will not infringe any proprietary rights (including intellectual property rights); this License will terminate immediately on any breach by you of this License. + +1. *Severability*. If any provision of this License is held to be unenforceable or invalid, that provision will be enforced to the maximum extent possible and the other provisions will remain in full force and effect. + +1. *Governing Law and Venue*. This License is governed by and construed in accordance with the laws of Denmark, except for its conflict of laws rules; the United Nations Convention on Contracts for the International Sale of Goods will not apply. If you reside (or your principal place of business is) within the United States, you and Unity agree to submit to the personal and exclusive jurisdiction of and venue in the state and federal courts located in San Francisco County, California concerning any dispute arising out of this License ("**_Dispute_**"). If you reside (or your principal place of business is) outside the United States, you and Unity agree to submit to the personal and exclusive jurisdiction of and venue in the courts located in Copenhagen, Denmark concerning any Dispute. + diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/README.md b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/README.md new file mode 100644 index 00000000..9d6fd499 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/README.md @@ -0,0 +1,14 @@ +Unity Analytics: Tracker +------------------------------ +Please visit the following URL to see documentation for the Analytics Event Tracker. + +https://docs.google.com/document/d/1glh4zEk0KQ_FhOgk95H-VOubcdzrVGyu5BYCmhFQCh0/edit# + +Please note, the documentation at this URL is considered a "living" document and subject to change. + + +Unity Analytics: Standard Events +------------------------------ +Track player behavior specific to your game + +Standard Events are a set of curated custom events focused on player experience. diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/.tests.json b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/.tests.json new file mode 100644 index 00000000..327abb29 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/.tests.json @@ -0,0 +1,3 @@ +{ + "createSeparatePackage": false +} diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/AchievementStepTests.cs b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/AchievementStepTests.cs new file mode 100644 index 00000000..f4c1af3e --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/AchievementStepTests.cs @@ -0,0 +1,48 @@ +using System; +using NUnit.Framework; + +namespace UnityEngine.Analytics.Tests +{ + public partial class AnalyticsEventTests + { + [Test] + public void AchievementStep_StepIndexTest( + [Values(-1, 0, 1)] int stepIndex + ) + { + var achievementId = "unit_tester"; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.AchievementStep(stepIndex, achievementId)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void AchievementStep_AchievementIdTest( + [Values("unit_tester", "", null)] string achievementId + ) + { + var stepIndex = 0; + + if (string.IsNullOrEmpty(achievementId)) + { + Assert.Throws(() => AnalyticsEvent.AchievementStep(stepIndex, achievementId)); + } + else + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.AchievementStep(stepIndex, achievementId)); + EvaluateAnalyticsResult(m_Result); + } + } + + [Test] + public void AchievementStep_CustomDataTest() + { + var stepIndex = 0; + var achievementId = "unit_tester"; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.AchievementStep(stepIndex, achievementId, m_CustomData)); + EvaluateCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/AchievementUnlockedTests.cs b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/AchievementUnlockedTests.cs new file mode 100644 index 00000000..4cb4c4bd --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/AchievementUnlockedTests.cs @@ -0,0 +1,34 @@ +using System; +using NUnit.Framework; + +namespace UnityEngine.Analytics.Tests +{ + public partial class AnalyticsEventTests + { + [Test] + public void AchievementUnlocked_AchievementIdTest( + [Values("unit_tester", "", null)] string achievementId + ) + { + if (string.IsNullOrEmpty(achievementId)) + { + Assert.Throws(() => AnalyticsEvent.AchievementUnlocked(achievementId)); + } + else + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.AchievementUnlocked(achievementId)); + EvaluateAnalyticsResult(m_Result); + } + } + + [Test] + public void AchievementUnlocked_CustomDataTest() + { + var achievementId = "unit_tester"; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.AchievementUnlocked(achievementId, m_CustomData)); + EvaluateCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/AdCompleteTests.cs b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/AdCompleteTests.cs new file mode 100644 index 00000000..5efd551a --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/AdCompleteTests.cs @@ -0,0 +1,62 @@ +using NUnit.Framework; + +namespace UnityEngine.Analytics.Tests +{ + public partial class AnalyticsEventTests + { + [Test] + public void AdComplete_RewardedTest( + [Values(true, false)] bool rewarded + ) + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.AdComplete(rewarded)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void AdComplete_NetworkStringTest( + [Values("unityads", "", null)] string network + ) + { + var rewarded = true; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.AdComplete(rewarded, network)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void AdComplete_NetworkEnumTest( + [Values(AdvertisingNetwork.UnityAds, AdvertisingNetwork.None)] AdvertisingNetwork network + ) + { + var rewarded = true; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.AdComplete(rewarded, network)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void AdComplete_PlacementIdTest( + [Values("rewardedVideo", "", null)] string placementId + ) + { + var rewarded = true; + var network = AdvertisingNetwork.UnityAds; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.AdComplete(rewarded, network, placementId)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void AdComplete_CustomDataTest() + { + var rewarded = true; + var network = AdvertisingNetwork.UnityAds; + var placementId = "rewardedVideo"; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.AdComplete(rewarded, network, placementId, m_CustomData)); + EvaluateCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/AdOfferTests.cs b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/AdOfferTests.cs new file mode 100644 index 00000000..c5dfedb4 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/AdOfferTests.cs @@ -0,0 +1,62 @@ +using NUnit.Framework; + +namespace UnityEngine.Analytics.Tests +{ + public partial class AnalyticsEventTests + { + [Test] + public void AdOffer_RewardedTest( + [Values(true, false)] bool rewarded + ) + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.AdOffer(rewarded)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void AdOffer_NetworkStringTest( + [Values("unityads", "", null)] string network + ) + { + var rewarded = true; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.AdOffer(rewarded, network)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void AdOffer_NetworkEnumTest( + [Values(AdvertisingNetwork.UnityAds, AdvertisingNetwork.None)] AdvertisingNetwork network + ) + { + var rewarded = true; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.AdOffer(rewarded, network)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void AdOffer_PlacementIdTest( + [Values("rewardedVideo", "", null)] string placementId + ) + { + var rewarded = true; + var network = AdvertisingNetwork.UnityAds; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.AdOffer(rewarded, network, placementId)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void AdOffer_CustomDataTest() + { + var rewarded = true; + var network = AdvertisingNetwork.UnityAds; + var placementId = "rewardedVideo"; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.AdOffer(rewarded, network, placementId, m_CustomData)); + EvaluateCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/AdSkipTests.cs b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/AdSkipTests.cs new file mode 100644 index 00000000..8c554b65 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/AdSkipTests.cs @@ -0,0 +1,62 @@ +using NUnit.Framework; + +namespace UnityEngine.Analytics.Tests +{ + public partial class AnalyticsEventTests + { + [Test] + public void AdSkip_RewardedTest( + [Values(true, false)] bool rewarded + ) + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.AdSkip(rewarded)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void AdSkip_NetworkStringTest( + [Values("unityads", "", null)] string network + ) + { + var rewarded = true; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.AdSkip(rewarded, network)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void AdSkip_NetworkEnumTest( + [Values(AdvertisingNetwork.UnityAds, AdvertisingNetwork.None)] AdvertisingNetwork network + ) + { + var rewarded = true; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.AdSkip(rewarded, network)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void AdSkip_PlacementIdTest( + [Values("rewardedVideo", "", null)] string placementId + ) + { + var rewarded = true; + var network = AdvertisingNetwork.UnityAds; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.AdSkip(rewarded, network, placementId)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void AdSkip_CustomDataTest() + { + var rewarded = true; + var network = AdvertisingNetwork.UnityAds; + var placementId = "rewardedVideo"; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.AdSkip(rewarded, network, placementId, m_CustomData)); + EvaluateCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/AdStartTests.cs b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/AdStartTests.cs new file mode 100644 index 00000000..ae104d88 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/AdStartTests.cs @@ -0,0 +1,62 @@ +using NUnit.Framework; + +namespace UnityEngine.Analytics.Tests +{ + public partial class AnalyticsEventTests + { + [Test] + public void AdStart_RewardedTest( + [Values(true, false)] bool rewarded + ) + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.AdStart(rewarded)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void AdStart_NetworkStringTest( + [Values("unityads", "", null)] string network + ) + { + var rewarded = true; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.AdStart(rewarded, network)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void AdStart_NetworkEnumTest( + [Values(AdvertisingNetwork.UnityAds, AdvertisingNetwork.None)] AdvertisingNetwork network + ) + { + var rewarded = true; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.AdStart(rewarded, network)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void AdStart_PlacementIdTest( + [Values("rewardedVideo", "", null)] string placementId + ) + { + var rewarded = true; + var network = AdvertisingNetwork.UnityAds; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.AdStart(rewarded, network, placementId)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void AdStart_CustomDataTest() + { + var rewarded = true; + var network = AdvertisingNetwork.UnityAds; + var placementId = "rewardedVideo"; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.AdStart(rewarded, network, placementId, m_CustomData)); + EvaluateCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/AnalyticsEventTests.cs b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/AnalyticsEventTests.cs new file mode 100644 index 00000000..e24c6919 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/AnalyticsEventTests.cs @@ -0,0 +1,115 @@ +#pragma warning disable 0612, 0618 + +using System; +using System.Collections.Generic; +using NUnit.Framework; + +namespace UnityEngine.Analytics.Tests +{ + [TestFixture, Category("Standard Event SDK")] + public partial class AnalyticsEventTests + { + readonly Dictionary m_CustomData = new Dictionary(); + AnalyticsResult m_Result = AnalyticsResult.Ok; + + [SetUp] + public void TestCaseSetUp() + { + m_Result = AnalyticsResult.Ok; + + m_CustomData.Clear(); + m_CustomData.Add("custom_param", "test"); + } + + [Test] + public void SdkVersion_FormatTest() + { + int major, minor, patch; + var versions = AnalyticsEvent.sdkVersion.Split('.'); + + Assert.AreEqual(3, versions.Length, "Number of integer fields in version format"); + + Assert.IsTrue(int.TryParse(versions[0], out major), "Major version is an integer"); + Assert.IsTrue(int.TryParse(versions[1], out minor), "Minor version is an integer"); + Assert.IsTrue(int.TryParse(versions[2], out patch), "Patch version is an integer"); + + Assert.LessOrEqual(0, major, "Major version"); + Assert.LessOrEqual(0, minor, "Minor version"); + Assert.LessOrEqual(0, patch, "Patch version"); + } + + [Test] + public void Custom_EventNameTest( + [Values("custom_event", "", null)] string eventName + ) + { + if (string.IsNullOrEmpty(eventName)) + { + Assert.Throws(() => m_Result = AnalyticsEvent.Custom(eventName)); + } + else + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.Custom(eventName)); + EvaluateAnalyticsResult(m_Result); + } + } + + [Test] + public void Custom_EventDataTest() + { + var eventName = "custom_event"; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.Custom(eventName, m_CustomData)); + EvaluateCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void Custom_RegisterUnregisterUnnamedTest() + { + Action> myAction = + eventData => eventData.Add("my_key", "my_value"); + + AnalyticsEvent.Register(myAction); // Registering for a named AnalyticsEvent + + var eventName = "custom_event"; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.Custom(eventName, m_CustomData)); + + EvaluateRegisteredCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + + AnalyticsEvent.Unregister(myAction); + } + + /// Normal. Unregistered. + public static void EvaluateCustomData(IDictionary customData) + { + Assert.AreEqual(1, customData.Count, "Custom param count"); + } + + /// For Registered case. + public static void EvaluateRegisteredCustomData(IDictionary customData) + { + Assert.AreEqual(2, customData.Count, "Custom param count"); + } + + public static void EvaluateAnalyticsResult(AnalyticsResult result) + { + switch (result) + { + case AnalyticsResult.Ok: + break; + case AnalyticsResult.InvalidData: + Assert.Fail("Event data is invalid."); + break; + case AnalyticsResult.TooManyItems: + Assert.Fail("Event data consists of too many parameters."); + break; + default: + Debug.LogFormat("A result of {0} is passable for the purpose of this test.", result); + break; + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/ChatMessageSentTests.cs b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/ChatMessageSentTests.cs new file mode 100644 index 00000000..56496550 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/ChatMessageSentTests.cs @@ -0,0 +1,22 @@ +using NUnit.Framework; + +namespace UnityEngine.Analytics.Tests +{ + public partial class AnalyticsEventTests + { + [Test] + public void ChatMessageSent_NoArgsTest() + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.ChatMessageSent()); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void ChatMessageSent_CustomDataTest() + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.ChatMessageSent(m_CustomData)); + EvaluateCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/CutsceneSkipTests.cs b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/CutsceneSkipTests.cs new file mode 100644 index 00000000..4b3cfd35 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/CutsceneSkipTests.cs @@ -0,0 +1,34 @@ +using System; +using NUnit.Framework; + +namespace UnityEngine.Analytics.Tests +{ + public partial class AnalyticsEventTests + { + [Test] + public void CutsceneSkip_CutsceneNameTest( + [Values("test_cutscene", "", null)] string name + ) + { + if (string.IsNullOrEmpty(name)) + { + Assert.Throws(() => AnalyticsEvent.CutsceneSkip(name)); + } + else + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.CutsceneSkip(name)); + EvaluateAnalyticsResult(m_Result); + } + } + + [Test] + public void CutsceneSkip_CustomDataTest() + { + var name = "test_cutscene"; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.CutsceneSkip(name, m_CustomData)); + EvaluateCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/CutsceneStartTests.cs b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/CutsceneStartTests.cs new file mode 100644 index 00000000..508cc790 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/CutsceneStartTests.cs @@ -0,0 +1,34 @@ +using System; +using NUnit.Framework; + +namespace UnityEngine.Analytics.Tests +{ + public partial class AnalyticsEventTests + { + [Test] + public void CutsceneStart_CutsceneNameTest( + [Values("test_cutscene", "", null)] string name + ) + { + if (string.IsNullOrEmpty(name)) + { + Assert.Throws(() => AnalyticsEvent.CutsceneStart(name)); + } + else + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.CutsceneStart(name)); + EvaluateAnalyticsResult(m_Result); + } + } + + [Test] + public void CutsceneStart_CustomDataTest() + { + var name = "test_cutscene"; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.CutsceneStart(name, m_CustomData)); + EvaluateCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/FirstInteractionTests.cs b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/FirstInteractionTests.cs new file mode 100644 index 00000000..a5cc8442 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/FirstInteractionTests.cs @@ -0,0 +1,33 @@ +using NUnit.Framework; + +namespace UnityEngine.Analytics.Tests +{ + public partial class AnalyticsEventTests + { + [Test] + public void FirstInteraction_NoArgsTest() + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.FirstInteraction()); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void FirstInteraction_ActionIdTest( + [Values("test_user_action", "", null)] string actionId + ) + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.FirstInteraction(actionId)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void FirstInteraction_CustomDataTest() + { + var actionId = "test_user_action"; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.FirstInteraction(actionId, m_CustomData)); + EvaluateCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/GameOverTests.cs b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/GameOverTests.cs new file mode 100644 index 00000000..8e88f445 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/GameOverTests.cs @@ -0,0 +1,58 @@ +using System; +using NUnit.Framework; + +namespace UnityEngine.Analytics.Tests +{ + public partial class AnalyticsEventTests + { + [Test] + public void GameOver_NoArgsTest() + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.GameOver()); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void GameOver_LevelIndexTest( + [Values(-1, 0, 1)] int levelIndex + ) + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.GameOver(levelIndex)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void GameOver_LevelNameTest( + [Values("test_level", "", null)] string levelName + ) + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.GameOver(levelName)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void GameOver_LevelIndex_LevelNameTest( + [Values(0)] int levelIndex, + [Values("test_level", "", null)] string levelName + ) + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.GameOver(levelIndex, levelName)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void GameOver_CustomDataTest() + { + var levelIndex = 0; + var levelName = "test_level"; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.GameOver(levelName, m_CustomData)); + EvaluateCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.GameOver(levelIndex, levelName, m_CustomData)); + EvaluateCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/GameStartTests.cs b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/GameStartTests.cs new file mode 100644 index 00000000..18749c7c --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/GameStartTests.cs @@ -0,0 +1,22 @@ +using NUnit.Framework; + +namespace UnityEngine.Analytics.Tests +{ + public partial class AnalyticsEventTests + { + [Test] + public void GameStart_NoArgsTest() + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.GameStart()); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void GameStart_CustomDataTest() + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.GameStart(m_CustomData)); + EvaluateCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/IAPTransactionTests.cs b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/IAPTransactionTests.cs new file mode 100644 index 00000000..439d4e77 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/IAPTransactionTests.cs @@ -0,0 +1,111 @@ +using System; +using NUnit.Framework; + +namespace UnityEngine.Analytics.Tests +{ + public partial class AnalyticsEventTests + { + [Test] + public void IAPTransaction_ContextTest( + [Values("test", "", null)] string context) + { + var price = 1f; + var itemId = "test_item"; + + if (string.IsNullOrEmpty(context)) + { + Assert.Throws(() => AnalyticsEvent.IAPTransaction(context, price, itemId)); + } + else + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.IAPTransaction(context, price, itemId)); + } + + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void IAPTransaction_PriceTest( + [Values(-1f, 0f, 1f)] float price) + { + var context = "test"; + var itemId = "test_item"; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.IAPTransaction(context, price, itemId)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void IAPTransaction_ItemIdTest( + [Values("test_item", "", null)] string itemId) + { + var context = "test"; + var price = 1f; + + if (string.IsNullOrEmpty(itemId)) + { + Assert.Throws(() => AnalyticsEvent.IAPTransaction(context, price, itemId)); + } + else + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.IAPTransaction(context, price, itemId)); + } + + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void IAPTransaction_ItemTypeTest( + [Values("test_type", "", null)] string itemType) + { + var context = "test"; + var price = 1f; + var itemId = "test_item"; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.IAPTransaction(context, price, itemId, itemType)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void IAPTransaction_LevelTest( + [Values("test_level", "", null)] string level) + { + var context = "test"; + var price = 1f; + var itemId = "test_item"; + var itemType = "test_type"; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.IAPTransaction(context, price, itemId, itemType, level)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void IAPTransaction_TransactionIdTest( + [Values("test_id", "", null)] string transactionId) + { + var context = "test"; + var price = 1f; + var itemId = "test_item"; + var itemType = "test_type"; + var level = "test_level"; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.IAPTransaction(context, price, itemId, itemType, level, transactionId)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void IAPTransaction_CustomDataTest() + { + var context = "test"; + var price = 1f; + var itemId = "test_item"; + var itemType = "test_type"; + var level = "test_level"; + var transactionId = "test_id"; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.IAPTransaction(context, price, itemId, itemType, level, transactionId, m_CustomData)); + EvaluateCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/ItemAcquiredTests.cs b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/ItemAcquiredTests.cs new file mode 100644 index 00000000..ec2b6683 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/ItemAcquiredTests.cs @@ -0,0 +1,176 @@ +using System; +using NUnit.Framework; + +namespace UnityEngine.Analytics.Tests +{ + public partial class AnalyticsEventTests + { + [Test] + public void ItemAcquired_CurrencyTypeTest( + [Values(AcquisitionType.Premium, AcquisitionType.Soft)] AcquisitionType currencyType) + { + var context = "test"; + var amount = 1f; + var itemId = "test_item"; + var balance = 1f; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.ItemAcquired(currencyType, context, amount, itemId)); + EvaluateAnalyticsResult(m_Result); + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.ItemAcquired(currencyType, context, amount, itemId, balance)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void ItemAcquired_ContextTest( + [Values("test", "", null)] string context) + { + var currencyType = AcquisitionType.Soft; + var amount = 1f; + var itemId = "test_item"; + var balance = 1f; + + if (string.IsNullOrEmpty(context)) + { + Assert.Throws(() => AnalyticsEvent.ItemAcquired(currencyType, context, amount, itemId)); + Assert.Throws(() => AnalyticsEvent.ItemAcquired(currencyType, context, amount, itemId, balance)); + } + else + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.ItemAcquired(currencyType, context, amount, itemId, balance)); + EvaluateAnalyticsResult(m_Result); + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.ItemAcquired(currencyType, context, amount, itemId, balance)); + EvaluateAnalyticsResult(m_Result); + } + } + + [Test] + public void ItemAcquired_AmountTest( + [Values(-1f, 0f, 1f)] float amount) + { + var currencyType = AcquisitionType.Soft; + var context = "test"; + var itemId = "test_item"; + var balance = 1f; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.ItemAcquired(currencyType, context, amount, itemId)); + EvaluateAnalyticsResult(m_Result); + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.ItemAcquired(currencyType, context, amount, itemId, balance)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void ItemAcquired_ItemIdTest( + [Values("test_item", "", null)] string itemId) + { + var currencyType = AcquisitionType.Soft; + var context = "test"; + var amount = 1f; + var balance = 1f; + + if (string.IsNullOrEmpty(itemId)) + { + Assert.Throws(() => AnalyticsEvent.ItemAcquired(currencyType, context, amount, itemId)); + Assert.Throws(() => AnalyticsEvent.ItemAcquired(currencyType, context, amount, itemId, balance)); + } + else + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.ItemAcquired(currencyType, context, amount, itemId)); + EvaluateAnalyticsResult(m_Result); + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.ItemAcquired(currencyType, context, amount, itemId, balance)); + EvaluateAnalyticsResult(m_Result); + } + } + + [Test] + public void ItemAcquired_BalanceTest( + [Values(-1f, 0, 1f)] float balance) + { + var currencyType = AcquisitionType.Soft; + var context = "test"; + var amount = 1f; + var itemId = "test_item"; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.ItemAcquired(currencyType, context, amount, itemId, balance)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void ItemAcquired_ItemTypeTest( + [Values("test_type", "", null)] string itemType) + { + var currencyType = AcquisitionType.Soft; + var context = "test"; + var amount = 1f; + var itemId = "test_item"; + var balance = 1f; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.ItemAcquired(currencyType, context, amount, itemId, itemType)); + EvaluateAnalyticsResult(m_Result); + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.ItemAcquired(currencyType, context, amount, itemId, balance, itemType)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void ItemAcquired_LevelTest( + [Values("test_level", "", null)] string level) + { + var currencyType = AcquisitionType.Soft; + var context = "test"; + var amount = 1f; + var itemId = "test_item"; + var balance = 1f; + var itemType = "test_type"; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.ItemAcquired(currencyType, context, amount, itemId, itemType, level)); + EvaluateAnalyticsResult(m_Result); + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.ItemAcquired(currencyType, context, amount, itemId, balance, itemType, level)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void ItemAcquired_TransactionIdTest( + [Values("test_id", "", null)] string transactionId) + { + var currencyType = AcquisitionType.Soft; + var context = "test"; + var amount = 1f; + var itemId = "test_item"; + var balance = 1f; + var itemType = "test_type"; + var level = "test_level"; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.ItemAcquired(currencyType, context, amount, itemId, itemType, level, transactionId)); + EvaluateAnalyticsResult(m_Result); + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.ItemAcquired(currencyType, context, amount, itemId, balance, itemType, level, transactionId)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void ItemAcquired_CustomDataTest() + { + var currencyType = AcquisitionType.Soft; + var context = "test"; + var amount = 1f; + var itemId = "test_item"; + var balance = 1f; + var itemType = "test_type"; + var level = "test_level"; + var transactionId = "test_id"; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.ItemAcquired(currencyType, context, amount, itemId, itemType, level, transactionId, m_CustomData)); + EvaluateCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.ItemAcquired(currencyType, context, amount, itemId, balance, itemType, level, transactionId, m_CustomData)); + EvaluateCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/ItemSpentTests.cs b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/ItemSpentTests.cs new file mode 100644 index 00000000..52ee9422 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/ItemSpentTests.cs @@ -0,0 +1,176 @@ +using System; +using NUnit.Framework; + +namespace UnityEngine.Analytics.Tests +{ + public partial class AnalyticsEventTests + { + [Test] + public void ItemSpent_CurrencyTypeTest( + [Values(AcquisitionType.Premium, AcquisitionType.Soft)] AcquisitionType currencyType) + { + var context = "test"; + var amount = 1f; + var itemId = "test_item"; + var balance = 1f; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.ItemSpent(currencyType, context, amount, itemId)); + EvaluateAnalyticsResult(m_Result); + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.ItemSpent(currencyType, context, amount, itemId, balance)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void ItemSpent_ContextTest( + [Values("test", "", null)] string context) + { + var currencyType = AcquisitionType.Soft; + var amount = 1f; + var itemId = "test_item"; + var balance = 1f; + + if (string.IsNullOrEmpty(context)) + { + Assert.Throws(() => AnalyticsEvent.ItemSpent(currencyType, context, amount, itemId)); + Assert.Throws(() => AnalyticsEvent.ItemSpent(currencyType, context, amount, itemId, balance)); + } + else + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.ItemSpent(currencyType, context, amount, itemId, balance)); + EvaluateAnalyticsResult(m_Result); + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.ItemSpent(currencyType, context, amount, itemId, balance)); + EvaluateAnalyticsResult(m_Result); + } + } + + [Test] + public void ItemSpent_AmountTest( + [Values(-1f, 0f, 1f)] float amount) + { + var currencyType = AcquisitionType.Soft; + var context = "test"; + var itemId = "test_item"; + var balance = 1f; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.ItemSpent(currencyType, context, amount, itemId)); + EvaluateAnalyticsResult(m_Result); + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.ItemSpent(currencyType, context, amount, itemId, balance)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void ItemSpent_ItemIdTest( + [Values("test_item", "", null)] string itemId) + { + var currencyType = AcquisitionType.Soft; + var context = "test"; + var amount = 1f; + var balance = 1f; + + if (string.IsNullOrEmpty(itemId)) + { + Assert.Throws(() => AnalyticsEvent.ItemSpent(currencyType, context, amount, itemId)); + Assert.Throws(() => AnalyticsEvent.ItemSpent(currencyType, context, amount, itemId, balance)); + } + else + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.ItemSpent(currencyType, context, amount, itemId)); + EvaluateAnalyticsResult(m_Result); + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.ItemSpent(currencyType, context, amount, itemId, balance)); + EvaluateAnalyticsResult(m_Result); + } + } + + [Test] + public void ItemSpent_BalanceTest( + [Values(-1f, 0, 1f)] float balance) + { + var currencyType = AcquisitionType.Soft; + var context = "test"; + var amount = 1f; + var itemId = "test_item"; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.ItemSpent(currencyType, context, amount, itemId, balance)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void ItemSpent_ItemTypeTest( + [Values("test_type", "", null)] string itemType) + { + var currencyType = AcquisitionType.Soft; + var context = "test"; + var amount = 1f; + var itemId = "test_item"; + var balance = 1f; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.ItemSpent(currencyType, context, amount, itemId, itemType)); + EvaluateAnalyticsResult(m_Result); + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.ItemSpent(currencyType, context, amount, itemId, balance, itemType)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void ItemSpent_LevelTest( + [Values("test_level", "", null)] string level) + { + var currencyType = AcquisitionType.Soft; + var context = "test"; + var amount = 1f; + var itemId = "test_item"; + var balance = 1f; + var itemType = "test_type"; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.ItemSpent(currencyType, context, amount, itemId, itemType, level)); + EvaluateAnalyticsResult(m_Result); + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.ItemSpent(currencyType, context, amount, itemId, balance, itemType, level)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void ItemSpent_TransactionIdTest( + [Values("test_id", "", null)] string transactionId) + { + var currencyType = AcquisitionType.Soft; + var context = "test"; + var amount = 1f; + var itemId = "test_item"; + var balance = 1f; + var itemType = "test_type"; + var level = "test_level"; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.ItemSpent(currencyType, context, amount, itemId, itemType, level, transactionId)); + EvaluateAnalyticsResult(m_Result); + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.ItemSpent(currencyType, context, amount, itemId, balance, itemType, level, transactionId)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void ItemSpent_CustomDataTest() + { + var currencyType = AcquisitionType.Soft; + var context = "test"; + var amount = 1f; + var itemId = "test_item"; + var balance = 1f; + var itemType = "test_type"; + var level = "test_level"; + var transactionId = "test_id"; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.ItemSpent(currencyType, context, amount, itemId, itemType, level, transactionId, m_CustomData)); + EvaluateCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.ItemSpent(currencyType, context, amount, itemId, balance, itemType, level, transactionId, m_CustomData)); + EvaluateCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/LevelCompleteTests.cs b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/LevelCompleteTests.cs new file mode 100644 index 00000000..274e37c4 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/LevelCompleteTests.cs @@ -0,0 +1,58 @@ +using System; +using NUnit.Framework; + +namespace UnityEngine.Analytics.Tests +{ + public partial class AnalyticsEventTests + { + [Test] + public void LevelComplete_LevelIndexTest( + [Values(-1, 0, 1)] int levelIndex + ) + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.LevelComplete(levelIndex)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void LevelComplete_LevelNameTest( + [Values("test_level", "", null)] string levelName + ) + { + if (string.IsNullOrEmpty(levelName)) + { + Assert.Throws(() => AnalyticsEvent.LevelComplete(levelName)); + } + else + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.LevelComplete(levelName)); + EvaluateAnalyticsResult(m_Result); + } + } + + // [Test] + // public void LevelComplete_LevelIndex_LevelNameTest ( + // [Values(0)] int levelIndex, + // [Values("test_level", "", null)] string levelName + // ) + // { + // Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.LevelComplete(levelIndex, levelName)); + // EvaluateAnalyticsResult(m_Result); + // } + + [Test] + public void LevelComplete_CustomDataTest() + { + var levelIndex = 0; + var levelName = "test_level"; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.LevelComplete(levelName, m_CustomData)); + EvaluateCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.LevelComplete(levelIndex, m_CustomData)); + EvaluateCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/LevelFailTests.cs b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/LevelFailTests.cs new file mode 100644 index 00000000..fece2ead --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/LevelFailTests.cs @@ -0,0 +1,58 @@ +using System; +using NUnit.Framework; + +namespace UnityEngine.Analytics.Tests +{ + public partial class AnalyticsEventTests + { + [Test] + public void LevelFail_LevelIndexTest( + [Values(-1, 0, 1)] int levelIndex + ) + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.LevelFail(levelIndex)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void LevelFail_LevelNameTest( + [Values("test_level", "", null)] string levelName + ) + { + if (string.IsNullOrEmpty(levelName)) + { + Assert.Throws(() => AnalyticsEvent.LevelFail(levelName)); + } + else + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.LevelFail(levelName)); + EvaluateAnalyticsResult(m_Result); + } + } + + // [Test] + // public void LevelFail_LevelIndex_LevelNameTest ( + // [Values(-1, 0, 1)] int levelIndex, + // [Values("test_level", "", null)] string levelName + // ) + // { + // Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.LevelFail(levelIndex, levelName)); + // EvaluateAnalyticsResult(m_Result); + // } + + [Test] + public void LevelFail_CustomDataTest() + { + var levelIndex = 0; + var levelName = "test_level"; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.LevelFail(levelName, m_CustomData)); + EvaluateCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.LevelFail(levelIndex, m_CustomData)); + EvaluateCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/LevelQuitTests.cs b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/LevelQuitTests.cs new file mode 100644 index 00000000..e4859aba --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/LevelQuitTests.cs @@ -0,0 +1,58 @@ +using System; +using NUnit.Framework; + +namespace UnityEngine.Analytics.Tests +{ + public partial class AnalyticsEventTests + { + [Test] + public void LevelQuit_LevelIndexTest( + [Values(-1, 0, 1)] int levelIndex + ) + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.LevelQuit(levelIndex)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void LevelQuit_LevelNameTest( + [Values("test_level", "", null)] string levelName + ) + { + if (string.IsNullOrEmpty(levelName)) + { + Assert.Throws(() => AnalyticsEvent.LevelQuit(levelName)); + } + else + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.LevelQuit(levelName)); + EvaluateAnalyticsResult(m_Result); + } + } + + // [Test] + // public void LevelQuit_LevelIndex_LevelNameTest ( + // [Values(-1, 0, 1)] int levelIndex, + // [Values("test_level", "", null)] string levelName + // ) + // { + // Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.LevelQuit(levelIndex, levelName)); + // EvaluateAnalyticsResult(m_Result); + // } + + [Test] + public void LevelQuit_CustomDataTest() + { + var levelIndex = 0; + var levelName = "test_level"; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.LevelQuit(levelName, m_CustomData)); + EvaluateCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.LevelQuit(levelIndex, m_CustomData)); + EvaluateCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/LevelSkipTests.cs b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/LevelSkipTests.cs new file mode 100644 index 00000000..fcbe9eb6 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/LevelSkipTests.cs @@ -0,0 +1,58 @@ +using System; +using NUnit.Framework; + +namespace UnityEngine.Analytics.Tests +{ + public partial class AnalyticsEventTests + { + [Test] + public void LevelSkip_LevelIndexTest( + [Values(-1, 0, 1)] int levelIndex + ) + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.LevelSkip(levelIndex)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void LevelSkip_LevelNameTest( + [Values("test_level", "", null)] string levelName + ) + { + if (string.IsNullOrEmpty(levelName)) + { + Assert.Throws(() => AnalyticsEvent.LevelSkip(levelName)); + } + else + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.LevelSkip(levelName)); + EvaluateAnalyticsResult(m_Result); + } + } + + // [Test] + // public void LevelSkip_LevelIndex_LevelNameTest ( + // [Values(-1, 0, 1)] int levelIndex, + // [Values("test_level", "", null)] string levelName + // ) + // { + // Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.LevelSkip(levelIndex, levelName)); + // EvaluateAnalyticsResult(m_Result); + // } + + [Test] + public void LevelSkip_CustomDataTest() + { + var levelIndex = 0; + var levelName = "test_level"; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.LevelSkip(levelName, m_CustomData)); + EvaluateCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.LevelSkip(levelIndex, m_CustomData)); + EvaluateCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/LevelStartTests.cs b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/LevelStartTests.cs new file mode 100644 index 00000000..ff4ef434 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/LevelStartTests.cs @@ -0,0 +1,58 @@ +using System; +using NUnit.Framework; + +namespace UnityEngine.Analytics.Tests +{ + public partial class AnalyticsEventTests + { + [Test] + public void LevelStart_LevelIndexTest( + [Values(-1, 0, 1)] int levelIndex + ) + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.LevelStart(levelIndex)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void LevelStart_LevelNameTest( + [Values("test_level", "", null)] string levelName + ) + { + if (string.IsNullOrEmpty(levelName)) + { + Assert.Throws(() => AnalyticsEvent.LevelStart(levelName)); + } + else + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.LevelStart(levelName)); + EvaluateAnalyticsResult(m_Result); + } + } + + // [Test] + // public void LevelStart_LevelIndex_LevelNameTest ( + // [Values(0)] int levelIndex, + // [Values("test_level", "", null)] string levelName + // ) + // { + // Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.LevelStart(levelIndex, levelName)); + // EvaluateAnalyticsResult(m_Result); + // } + + [Test] + public void LevelStart_CustomDataTest() + { + var levelIndex = 0; + var levelName = "test_level"; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.LevelStart(levelName, m_CustomData)); + EvaluateCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.LevelStart(levelIndex, m_CustomData)); + EvaluateCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/LevelUpTests.cs b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/LevelUpTests.cs new file mode 100644 index 00000000..96578a71 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/LevelUpTests.cs @@ -0,0 +1,58 @@ +using System; +using NUnit.Framework; + +namespace UnityEngine.Analytics.Tests +{ + public partial class AnalyticsEventTests + { + [Test] + public void LevelUp_LevelIndexTest( + [Values(0, 1, 2)] int newLevelIndex + ) + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.LevelUp(newLevelIndex)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void LevelUp_LevelNameTest( + [Values("new_test_level", "", null)] string newLevelName + ) + { + if (string.IsNullOrEmpty(newLevelName)) + { + Assert.Throws(() => AnalyticsEvent.LevelUp(newLevelName)); + } + else + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.LevelUp(newLevelName)); + EvaluateAnalyticsResult(m_Result); + } + } + + // [Test] + // public void LevelUp_LevelIndex_LevelNameTest ( + // [Values(1)] int newLevelIndex, + // [Values("new_test_level", "", null)] string newLevelName + // ) + // { + // Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.LevelUp(newLevelIndex, newLevelName)); + // EvaluateAnalyticsResult(m_Result); + // } + + [Test] + public void LevelUp_CustomDataTest() + { + var newLevelIndex = 1; + var newLevelName = "new_test_level"; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.LevelUp(newLevelName, m_CustomData)); + EvaluateCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.LevelUp(newLevelIndex, m_CustomData)); + EvaluateCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/PostAdActionTests.cs b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/PostAdActionTests.cs new file mode 100644 index 00000000..80ffa6df --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/PostAdActionTests.cs @@ -0,0 +1,62 @@ +using NUnit.Framework; + +namespace UnityEngine.Analytics.Tests +{ + public partial class AnalyticsEventTests + { + [Test] + public void PostAdAction_RewardedTest( + [Values(true, false)] bool rewarded + ) + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.PostAdAction(rewarded)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void PostAdAction_NetworkStringTest( + [Values("unityads", "", null)] string network + ) + { + var rewarded = true; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.PostAdAction(rewarded, network)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void PostAdAction_NetworkEnumTest( + [Values(AdvertisingNetwork.UnityAds, AdvertisingNetwork.None)] AdvertisingNetwork network + ) + { + var rewarded = true; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.PostAdAction(rewarded, network)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void PostAdAction_PlacementIdTest( + [Values("rewardedVideo", "", null)] string placementId + ) + { + var rewarded = true; + var network = AdvertisingNetwork.UnityAds; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.PostAdAction(rewarded, network, placementId)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void PostAdAction_CustomDataTest() + { + var rewarded = true; + var network = AdvertisingNetwork.UnityAds; + var placementId = "rewardedVideo"; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.PostAdAction(rewarded, network, placementId, m_CustomData)); + EvaluateCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/PushNotificationClickTests.cs b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/PushNotificationClickTests.cs new file mode 100644 index 00000000..5923cedd --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/PushNotificationClickTests.cs @@ -0,0 +1,34 @@ +using System; +using NUnit.Framework; + +namespace UnityEngine.Analytics.Tests +{ + public partial class AnalyticsEventTests + { + [Test] + public void PushNotificationClick_MessageIdTest( + [Values("test_message", "", null)] string messageId + ) + { + if (string.IsNullOrEmpty(messageId)) + { + Assert.Throws(() => AnalyticsEvent.PushNotificationClick(messageId)); + } + else + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.PushNotificationClick(messageId)); + EvaluateAnalyticsResult(m_Result); + } + } + + [Test] + public void PushNotificationClick_CustomDataTest() + { + var messageId = "test_message"; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.PushNotificationClick(messageId, m_CustomData)); + EvaluateCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/PushNotificationEnableTests.cs b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/PushNotificationEnableTests.cs new file mode 100644 index 00000000..2e842bdc --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/PushNotificationEnableTests.cs @@ -0,0 +1,22 @@ +using NUnit.Framework; + +namespace UnityEngine.Analytics.Tests +{ + public partial class AnalyticsEventTests + { + [Test] + public void PushNotificationEnable_NoArgsTest() + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.PushNotificationEnable()); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void PushNotificationEnable_CustomDataTest() + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.PushNotificationEnable(m_CustomData)); + EvaluateCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/ScreenVisitTests.cs b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/ScreenVisitTests.cs new file mode 100644 index 00000000..97a60fcc --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/ScreenVisitTests.cs @@ -0,0 +1,43 @@ +using System; +using NUnit.Framework; + +namespace UnityEngine.Analytics.Tests +{ + public partial class AnalyticsEventTests + { + [Test] + public void ScreenVisit_ScreenNameStringTest( + [Values("test_screen", "", null)] string screenName + ) + { + if (string.IsNullOrEmpty(screenName)) + { + Assert.Throws(() => AnalyticsEvent.ScreenVisit(screenName)); + } + else + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.ScreenVisit(screenName)); + EvaluateAnalyticsResult(m_Result); + } + } + + [Test] + public void ScreenVisit_ScreenNameEnumTest( + [Values(ScreenName.CrossPromo, ScreenName.IAPPromo, ScreenName.None)] ScreenName screenName + ) + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.ScreenVisit(screenName)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void ScreenVisit_CustomDataTest() + { + var screenName = ScreenName.MainMenu; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.ScreenVisit(screenName, m_CustomData)); + EvaluateCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/SocialShareAcceptTests.cs b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/SocialShareAcceptTests.cs new file mode 100644 index 00000000..7cb38a1d --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/SocialShareAcceptTests.cs @@ -0,0 +1,110 @@ +using System; +using NUnit.Framework; + +namespace UnityEngine.Analytics.Tests +{ + public partial class AnalyticsEventTests + { + [Test] + public void SocialShareAccept_ShareTypeStringTest( + [Values("test_share", "", null)] string shareType + ) + { + var socialNetwork = SocialNetwork.Facebook; + + if (string.IsNullOrEmpty(shareType)) + { + Assert.Throws(() => AnalyticsEvent.SocialShare(shareType, socialNetwork)); + } + else + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.SocialShareAccept(shareType, socialNetwork)); + EvaluateAnalyticsResult(m_Result); + } + } + + [Test] + public void SocialShareAccept_ShareTypeEnumTest( + [Values(ShareType.TextOnly, ShareType.Image, ShareType.None)] ShareType shareType + ) + { + var socialNetwork = SocialNetwork.Twitter; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.SocialShareAccept(shareType, socialNetwork)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void SocialShareAccept_SocialNetworkStringTest( + [Values("test_network", "", null)] string socialNetwork + ) + { + var shareType = ShareType.Image; + + if (string.IsNullOrEmpty(socialNetwork)) + { + Assert.Throws(() => AnalyticsEvent.SocialShare(shareType, socialNetwork)); + } + else + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.SocialShareAccept(shareType, socialNetwork)); + EvaluateAnalyticsResult(m_Result); + } + } + + [Test] + public void SocialShareAccept_SocialNetworkEnumTest( + [Values(SocialNetwork.GooglePlus, SocialNetwork.OK_ru, SocialNetwork.None)] SocialNetwork socialNetwork + ) + { + var shareType = ShareType.Video; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.SocialShareAccept(shareType, socialNetwork)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void SocialShareAccept_SenderIdTest( + [Values("test_sender", "", null)] string senderId + ) + { + var shareType = ShareType.TextOnly; + var socialNetwork = SocialNetwork.Twitter; + + Assert.DoesNotThrow( + () => m_Result = AnalyticsEvent.SocialShareAccept(shareType, socialNetwork, senderId) + ); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void SocialShareAccept_RecipientIdTest( + [Values("test_recipient", "", null)] string recipientId + ) + { + var shareType = ShareType.TextOnly; + var socialNetwork = SocialNetwork.Twitter; + var senderId = "test_sender"; + + Assert.DoesNotThrow( + () => m_Result = AnalyticsEvent.SocialShareAccept(shareType, socialNetwork, senderId, recipientId) + ); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void SocialShareAccept_CustomDataTest() + { + var shareType = ShareType.TextOnly; + var socialNetwork = SocialNetwork.Twitter; + var senderId = "test_sender"; + var recipientId = "test_recipient"; + + Assert.DoesNotThrow( + () => m_Result = AnalyticsEvent.SocialShareAccept(shareType, socialNetwork, senderId, recipientId, m_CustomData) + ); + EvaluateCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/SocialShareTests.cs b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/SocialShareTests.cs new file mode 100644 index 00000000..0809d04a --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/SocialShareTests.cs @@ -0,0 +1,110 @@ +using System; +using NUnit.Framework; + +namespace UnityEngine.Analytics.Tests +{ + public partial class AnalyticsEventTests + { + [Test] + public void SocialShare_ShareTypeStringTest( + [Values("test_share", "", null)] string shareType + ) + { + var socialNetwork = SocialNetwork.Facebook; + + if (string.IsNullOrEmpty(shareType)) + { + Assert.Throws(() => AnalyticsEvent.SocialShare(shareType, socialNetwork)); + } + else + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.SocialShare(shareType, socialNetwork)); + EvaluateAnalyticsResult(m_Result); + } + } + + [Test] + public void SocialShare_ShareTypeEnumTest( + [Values(ShareType.TextOnly, ShareType.Image, ShareType.None)] ShareType shareType + ) + { + var socialNetwork = SocialNetwork.Twitter; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.SocialShare(shareType, socialNetwork)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void SocialShare_SocialNetworkStringTest( + [Values("test_network", "", null)] string socialNetwork + ) + { + var shareType = ShareType.Image; + + if (string.IsNullOrEmpty(socialNetwork)) + { + Assert.Throws(() => AnalyticsEvent.SocialShare(shareType, socialNetwork)); + } + else + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.SocialShare(shareType, socialNetwork)); + EvaluateAnalyticsResult(m_Result); + } + } + + [Test] + public void SocialShare_SocialNetworkEnumTest( + [Values(SocialNetwork.GooglePlus, SocialNetwork.OK_ru, SocialNetwork.None)] SocialNetwork socialNetwork + ) + { + var shareType = ShareType.Video; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.SocialShare(shareType, socialNetwork)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void SocialShare_SenderIdTest( + [Values("test_sender", "", null)] string senderId + ) + { + var shareType = ShareType.TextOnly; + var socialNetwork = SocialNetwork.Twitter; + + Assert.DoesNotThrow( + () => m_Result = AnalyticsEvent.SocialShare(shareType, socialNetwork, senderId) + ); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void SocialShare_RecipientIdTest( + [Values("test_recipient", "", null)] string recipientId + ) + { + var shareType = ShareType.TextOnly; + var socialNetwork = SocialNetwork.Twitter; + var senderId = "test_sender"; + + Assert.DoesNotThrow( + () => m_Result = AnalyticsEvent.SocialShare(shareType, socialNetwork, senderId, recipientId) + ); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void SocialShare_CustomDataTest() + { + var shareType = ShareType.TextOnly; + var socialNetwork = SocialNetwork.Twitter; + var senderId = "test_sender"; + var recipientId = "test_recipient"; + + Assert.DoesNotThrow( + () => m_Result = AnalyticsEvent.SocialShare(shareType, socialNetwork, senderId, recipientId, m_CustomData) + ); + EvaluateCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/StoreItemClickTests.cs b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/StoreItemClickTests.cs new file mode 100644 index 00000000..367a4599 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/StoreItemClickTests.cs @@ -0,0 +1,75 @@ +using System; +using NUnit.Framework; + +namespace UnityEngine.Analytics.Tests +{ + public partial class AnalyticsEventTests + { + [Test] + public void StoreItemClick_StoreTypeTest( + [Values(StoreType.Premium, StoreType.Soft)] StoreType storeType + ) + { + var itemId = "test_item"; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.StoreItemClick(storeType, itemId)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void StoreItemClick_ItemIdTest( + [Values("test_item", "", null)] string itemId + ) + { + var storeType = StoreType.Soft; + + if (string.IsNullOrEmpty(itemId)) + { + Assert.Throws(() => AnalyticsEvent.StoreItemClick(storeType, itemId)); + } + else + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.StoreItemClick(storeType, itemId)); + EvaluateAnalyticsResult(m_Result); + } + } + + [Test] + public void StoreItemClick_ItemId_ItemNameTest( + [Values("test_item_id", "", null)] string itemId, + [Values("Test Item Name", "", null)] string itemName + ) + { + var storeType = StoreType.Soft; + + if (string.IsNullOrEmpty(itemId) && string.IsNullOrEmpty(itemName)) + { + Assert.Throws(() => AnalyticsEvent.StoreItemClick(storeType, itemId)); + } + else + { + if (string.IsNullOrEmpty(itemId)) + { + Assert.Throws(() => AnalyticsEvent.StoreItemClick(storeType, itemId)); + } + else + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.StoreItemClick(storeType, itemId, itemName)); + EvaluateAnalyticsResult(m_Result); + } + } + } + + [Test] + public void StoreItemClick_CustomDataTest() + { + var storeType = StoreType.Soft; + var itemId = "test_item"; + var itemName = "Test Item"; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.StoreItemClick(storeType, itemId, itemName, m_CustomData)); + EvaluateCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/StoreOpenedTests.cs b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/StoreOpenedTests.cs new file mode 100644 index 00000000..48918872 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/StoreOpenedTests.cs @@ -0,0 +1,27 @@ +using System.Collections.Generic; +using NUnit.Framework; + +namespace UnityEngine.Analytics.Tests +{ + public partial class AnalyticsEventTests + { + [Test] + public void StoreOpened_StoreTypeTest( + [Values(StoreType.Premium, StoreType.Soft)] StoreType storeType + ) + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.StoreOpened(storeType)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void StoreOpened_CustomDataTest() + { + var storeType = StoreType.Soft; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.StoreOpened(storeType, m_CustomData)); + EvaluateCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/TutorialCompleteTests.cs b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/TutorialCompleteTests.cs new file mode 100644 index 00000000..3e166af2 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/TutorialCompleteTests.cs @@ -0,0 +1,26 @@ +using NUnit.Framework; + +namespace UnityEngine.Analytics.Tests +{ + public partial class AnalyticsEventTests + { + [Test] + public void TutorialComplete_TutorialIdTest( + [Values("test_tutorial", "", null)] string tutorialId + ) + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.TutorialComplete(tutorialId)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void TutorialComplete_CustomDataTest() + { + var tutorialId = "test_tutorial"; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.TutorialComplete(tutorialId, m_CustomData)); + EvaluateCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/TutorialSkipTests.cs b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/TutorialSkipTests.cs new file mode 100644 index 00000000..9b413eda --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/TutorialSkipTests.cs @@ -0,0 +1,26 @@ +using NUnit.Framework; + +namespace UnityEngine.Analytics.Tests +{ + public partial class AnalyticsEventTests + { + [Test] + public void TutorialSkip_TutorialIdTest( + [Values("test_tutorial", "", null)] string tutorialId + ) + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.TutorialSkip(tutorialId)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void TutorialSkip_CustomDataTest() + { + var tutorialId = "test_tutorial"; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.TutorialSkip(tutorialId, m_CustomData)); + EvaluateCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/TutorialStartTests.cs b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/TutorialStartTests.cs new file mode 100644 index 00000000..425f2773 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/TutorialStartTests.cs @@ -0,0 +1,26 @@ +using NUnit.Framework; + +namespace UnityEngine.Analytics.Tests +{ + public partial class AnalyticsEventTests + { + [Test] + public void TutorialStart_TutorialIdTest( + [Values("test_tutorial", "", null)] string tutorialId + ) + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.TutorialStart(tutorialId)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void TutorialStart_CustomDataTest() + { + var tutorialId = "test_tutorial"; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.TutorialStart(tutorialId, m_CustomData)); + EvaluateCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/TutorialStepTests.cs b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/TutorialStepTests.cs new file mode 100644 index 00000000..524d8195 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/TutorialStepTests.cs @@ -0,0 +1,39 @@ +using System; +using NUnit.Framework; + +namespace UnityEngine.Analytics.Tests +{ + public partial class AnalyticsEventTests + { + [Test] + public void TutorialStep_StepIndexTest( + [Values(-1, 0, 1)] int stepIndex + ) + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.TutorialStep(stepIndex)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void TutorialStep_TutorialIdTest( + [Values("test_tutorial", "", null)] string tutorialId + ) + { + var stepIndex = 0; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.TutorialStep(stepIndex, tutorialId)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void TutorialStep_CustomDataTest() + { + var stepIndex = 0; + var tutorialId = "test_tutorial"; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.TutorialStep(stepIndex, tutorialId, m_CustomData)); + EvaluateCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/Unity.Analytics.StandardEvents.EditorTests.asmdef b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/Unity.Analytics.StandardEvents.EditorTests.asmdef new file mode 100644 index 00000000..e2141b4b --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/Unity.Analytics.StandardEvents.EditorTests.asmdef @@ -0,0 +1,19 @@ +{ + "name": "Unity.Analytics.StandardEvents.EditorTests", + "references": [], + "optionalUnityReferences": [ + "TestAssemblies" + ], + "includePlatforms": [ + "Editor" + ], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": true, + "precompiledReferences": [ + "Unity.Analytics.StandardEvents.dll" + ], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [] +} diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/UserSignupTests.cs b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/UserSignupTests.cs new file mode 100644 index 00000000..56920a63 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Editor/Unity.Analytics.StandardEvents/UserSignupTests.cs @@ -0,0 +1,43 @@ +using System; +using NUnit.Framework; + +namespace UnityEngine.Analytics.Tests +{ + public partial class AnalyticsEventTests + { + [Test] + public void UserSignup_AuthorizationNetworkStringTest( + [Values("test_network", "", null)] string network + ) + { + if (string.IsNullOrEmpty(network)) + { + Assert.Throws(() => AnalyticsEvent.UserSignup(network)); + } + else + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.UserSignup(network)); + EvaluateAnalyticsResult(m_Result); + } + } + + [Test] + public void UserSignup_AuthorizationNetworkEnumTest( + [Values(AuthorizationNetwork.Facebook, AuthorizationNetwork.GameCenter, AuthorizationNetwork.None)] AuthorizationNetwork network + ) + { + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.UserSignup(network)); + EvaluateAnalyticsResult(m_Result); + } + + [Test] + public void UserSignup_CustomDataTest() + { + var network = AuthorizationNetwork.Internal; + + Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.UserSignup(network, m_CustomData)); + EvaluateCustomData(m_CustomData); + EvaluateAnalyticsResult(m_Result); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Runtime/DataPrivacy/JsonSerialization.cs b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Runtime/DataPrivacy/JsonSerialization.cs new file mode 100644 index 00000000..921976a5 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Runtime/DataPrivacy/JsonSerialization.cs @@ -0,0 +1,24 @@ +using System; +using NUnit.Framework; +using UnityEngine; +using UnityEngine.Analytics; + +public class JsonSerialization +{ + // This test was create to verifiy JsonUtility could properly deserialize the nested + // structs used for opt-out status. That process is now handled with remote config so + // now we just verify that the expected response from the token API can be deserialized. + + const string kTokenJson = "{" + + "\"url\": \"https://analytics.cloud.unity3d.com/optout?token=24a96770b5c4420a4f930dbb4b72fbb83erfg3edf3ert4r1/\"," + + "\"token\": \"24a96770b5c4420a4f930dbb4b72fbb83erfg3edf3ert4r1\"" + + "}"; + + [Test] + public void TestTokenStruct_JsonUtility() + { + var tokenData = JsonUtility.FromJson(kTokenJson); + Assert.AreEqual("https://analytics.cloud.unity3d.com/optout?token=24a96770b5c4420a4f930dbb4b72fbb83erfg3edf3ert4r1/", tokenData.url); + Assert.AreEqual("24a96770b5c4420a4f930dbb4b72fbb83erfg3edf3ert4r1", tokenData.token); + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Runtime/DataPrivacy/Unity.Analytics.DataPrivacy.Tests.asmdef b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Runtime/DataPrivacy/Unity.Analytics.DataPrivacy.Tests.asmdef new file mode 100644 index 00000000..54d317a0 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Tests/Runtime/DataPrivacy/Unity.Analytics.DataPrivacy.Tests.asmdef @@ -0,0 +1,12 @@ +{ + "name": "Unity.Analytics.DataPrivacy.Tests", + "references": [ + "Unity.Analytics.DataPrivacy" + ], + "optionalUnityReferences": [ + "TestAssemblies" + ], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": false +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Unity.Analytics.Editor.dll b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Unity.Analytics.Editor.dll new file mode 100644 index 00000000..8f567aad Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Unity.Analytics.Editor.dll differ diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Unity.Analytics.Editor.dll.mdb b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Unity.Analytics.Editor.dll.mdb new file mode 100644 index 00000000..ab7a630c Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Unity.Analytics.Editor.dll.mdb differ diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Unity.Analytics.StandardEvents.dll b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Unity.Analytics.StandardEvents.dll new file mode 100644 index 00000000..b8e7ea79 Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Unity.Analytics.StandardEvents.dll differ diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Unity.Analytics.StandardEvents.dll.mdb b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Unity.Analytics.StandardEvents.dll.mdb new file mode 100644 index 00000000..03748075 Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Unity.Analytics.StandardEvents.dll.mdb differ diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Unity.Analytics.Tracker.dll b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Unity.Analytics.Tracker.dll new file mode 100644 index 00000000..21975ccf Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Unity.Analytics.Tracker.dll differ diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Unity.Analytics.Tracker.dll.mdb b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Unity.Analytics.Tracker.dll.mdb new file mode 100644 index 00000000..0811ab65 Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/Unity.Analytics.Tracker.dll.mdb differ diff --git a/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/package.json b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/package.json new file mode 100644 index 00000000..a1f71399 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.analytics@3.3.2/package.json @@ -0,0 +1,21 @@ +{ + "dependencies": { + "com.unity.ugui": "1.0.0" + }, + "description": "The Unity Analytics Library contains the Analytics Event Tracker component, the Data Privacy plug-in, and the Standard Events API.", + "displayName": "Analytics Library", + "keywords": [ + "analytics", + "unity" + ], + "name": "com.unity.analytics", + "readme": "Unity Analytics", + "repoPackagePath": "build/install/com.unity.analytics", + "repository": { + "revision": "8196036181e573933751e8c0296037c7b6ddca65", + "type": "git", + "url": "git@gitlab.cds.internal.unity3d.com:upm-packages/analytics/com.unity.analytics.git" + }, + "unity": "2019.1", + "version": "3.3.2" +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/.npmignore b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/.npmignore new file mode 100644 index 00000000..1586aea7 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/.npmignore @@ -0,0 +1,6 @@ + +automation/** +utr_output/** +.Editor/** +.yamato/** +*.zip* \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/CHANGELOG.md b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/CHANGELOG.md new file mode 100644 index 00000000..3c6c85d5 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/CHANGELOG.md @@ -0,0 +1,31 @@ +# Changelog +All notable changes to this package will be documented in this file. + +The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). + +## [1.2.16] - 2019-02-11 +Update stylesheet to pass USS validation + +## [1.2.15] - 2018-11-16 +Added support for non-experimental UIElements. + +## [1.2.11] - 2018-09-04 +Made some performance improvements to reduce impact on ReloadAssemblies. + +## [1.2.9] - 2018-08-13 +Test issues for the Collab History Window are now fixed. + +## [1.2.7] - 2018-08-07 +Toolbar drop-down will no longer show up when package is uninstalled. + +## [1.2.6] - 2018-06-15 +Fixed an issue where Collab's History window wouldn't load properly. + +## [1.2.5] - 2018-05-21 +This is the first release of *Unity Package CollabProxy*. + +### Added +- Collab history and toolbar windows +- Collab view and presenter classes +- Collab Editor tests for view and presenter diff --git a/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/DEPENDENCIES.md b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/DEPENDENCIES.md new file mode 100644 index 00000000..57808d56 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/DEPENDENCIES.md @@ -0,0 +1,9 @@ + + + + Unity.CollabProxy.Dependencies + 1.1.0-experimental + Rohit Garg + Dependencies for the CollabProxy package + + diff --git a/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/AssemblyInfo.cs b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/AssemblyInfo.cs new file mode 100644 index 00000000..d7266b63 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/AssemblyInfo.cs @@ -0,0 +1,4 @@ +using System.Runtime.CompilerServices; +using UnityEngine; + +[assembly: InternalsVisibleTo("Unity.CollabProxy.EditorTests")] diff --git a/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/Bootstrap.cs b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/Bootstrap.cs new file mode 100644 index 00000000..029ce1c7 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/Bootstrap.cs @@ -0,0 +1,24 @@ +using UnityEditor; +using UnityEditor.Collaboration; +using UnityEngine; + +namespace CollabProxy.UI +{ + [InitializeOnLoad] + public class Bootstrap + { + private const float kCollabToolbarButtonWidth = 78.0f; + + static Bootstrap() + { + Collab.ShowHistoryWindow = CollabHistoryWindow.ShowHistoryWindow; + Collab.ShowToolbarAtPosition = CollabToolbarWindow.ShowCenteredAtPosition; + Collab.IsToolbarVisible = CollabToolbarWindow.IsVisible; + Collab.CloseToolbar = CollabToolbarWindow.CloseToolbar; + Toolbar.AddSubToolbar(new CollabToolbarButton + { + Width = kCollabToolbarButtonWidth + }); + } + } +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/CollabAnalytics.cs b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/CollabAnalytics.cs new file mode 100644 index 00000000..c7f90aa1 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/CollabAnalytics.cs @@ -0,0 +1,21 @@ +using System; + +namespace UnityEditor.Collaboration +{ + internal static class CollabAnalytics + { + [Serializable] + private struct CollabUserActionAnalyticsEvent + { + public string category; + public string action; + } + + public static void SendUserAction(string category, string action) + { + EditorAnalytics.SendCollabUserAction(new CollabUserActionAnalyticsEvent() { category = category, action = action }); + } + + public static readonly string historyCategoryString = "History"; + }; +} diff --git a/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/CollabHistoryWindow.cs b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/CollabHistoryWindow.cs new file mode 100644 index 00000000..b855bce3 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/CollabHistoryWindow.cs @@ -0,0 +1,330 @@ +using System; +using System.Linq; +using System.Collections.Generic; +using UnityEditor.Collaboration; + +#if UNITY_2019_1_OR_NEWER +using UnityEditor.UIElements; +using UnityEngine.UIElements; +#else +using UnityEditor.Experimental.UIElements; +using UnityEngine.Experimental.UIElements; +using UnityEngine.Experimental.UIElements.StyleEnums; +#endif + +using UnityEngine; +using UnityEditor.Connect; + +namespace UnityEditor +{ + internal class CollabHistoryWindow : EditorWindow, ICollabHistoryWindow + { +#if UNITY_2019_1_OR_NEWER + private const string ResourcesPath = "Packages/com.unity.collab-proxy/Editor/Resources/Styles/"; +#else + private const string ResourcesPath = "StyleSheets/"; +#endif + + + const string kWindowTitle = "Collab History"; + const string kServiceUrl = "developer.cloud.unity3d.com"; + + [MenuItem("Window/Asset Management/Collab History", false, 1)] + public static void ShowHistoryWindow() + { + EditorWindow.GetWindow(kWindowTitle); + } + + [MenuItem("Window/Asset Management/Collab History", true)] + public static bool ValidateShowHistoryWindow() + { + return Collab.instance.IsCollabEnabledForCurrentProject(); + } + + CollabHistoryPresenter m_Presenter; + Dictionary m_Views; + List m_HistoryItems = new List(); + HistoryState m_State; + VisualElement m_Container; + PagedListView m_Pager; + ScrollView m_HistoryView; + int m_ItemsPerPage = 5; + string m_InProgressRev; + bool m_RevisionActionsEnabled; + + public CollabHistoryWindow() + { + minSize = new Vector2(275, 50); + } + + public void OnEnable() + { + SetupGUI(); + name = "CollabHistory"; + + if (m_Presenter == null) + { + m_Presenter = new CollabHistoryPresenter(this, new CollabHistoryItemFactory(), new RevisionsService(Collab.instance, UnityConnect.instance)); + } + m_Presenter.OnWindowEnabled(); + } + + public void OnDisable() + { + m_Presenter.OnWindowDisabled(); + } + + public bool revisionActionsEnabled + { + get { return m_RevisionActionsEnabled; } + set + { + if (m_RevisionActionsEnabled == value) + return; + + m_RevisionActionsEnabled = value; + foreach (var historyItem in m_HistoryItems) + { + historyItem.RevisionActionsEnabled = value; + } + } + } + + private void AddStyleSheetPath(VisualElement root, string path) + { +#if UNITY_2019_1_OR_NEWER + root.styleSheets.Add(EditorGUIUtility.Load(path) as StyleSheet); +#else + root.AddStyleSheetPath(path); +#endif + } + + + public void SetupGUI() + { +#if UNITY_2019_1_OR_NEWER + var root = this.rootVisualElement; +#else + var root = this.GetRootVisualContainer(); +#endif + AddStyleSheetPath(root, ResourcesPath + "CollabHistoryCommon.uss"); + if (EditorGUIUtility.isProSkin) + { + AddStyleSheetPath(root, ResourcesPath + "CollabHistoryDark.uss"); + } + else + { + AddStyleSheetPath(root, ResourcesPath + "CollabHistoryLight.uss"); + } + + m_Container = new VisualElement(); + m_Container.StretchToParentSize(); + root.Add(m_Container); + + m_Pager = new PagedListView() + { + name = "PagedElement", + pageSize = m_ItemsPerPage + }; + + var errorView = new StatusView() + { + message = "An Error Occurred", + icon = EditorGUIUtility.LoadIconRequired("Collab.Warning") as Texture, + }; + + var noInternetView = new StatusView() + { + message = "No Internet Connection", + icon = EditorGUIUtility.LoadIconRequired("Collab.NoInternet") as Texture, + }; + + var maintenanceView = new StatusView() + { + message = "Maintenance", + }; + + var loginView = new StatusView() + { + message = "Sign in to access Collaborate", + buttonText = "Sign in...", + callback = SignInClick, + }; + + var noSeatView = new StatusView() + { + message = "Ask your project owner for access to Unity Teams", + buttonText = "Learn More", + callback = NoSeatClick, + }; + + var waitingView = new StatusView() + { + message = "Updating...", + }; + + m_HistoryView = new ScrollView() { name = "HistoryContainer", showHorizontal = false}; + m_HistoryView.contentContainer.StretchToParentWidth(); + m_HistoryView.Add(m_Pager); + + m_Views = new Dictionary() + { + {HistoryState.Error, errorView}, + {HistoryState.Offline, noInternetView}, + {HistoryState.Maintenance, maintenanceView}, + {HistoryState.LoggedOut, loginView}, + {HistoryState.NoSeat, noSeatView}, + {HistoryState.Waiting, waitingView}, + {HistoryState.Ready, m_HistoryView} + }; + } + + public void UpdateState(HistoryState state, bool force) + { + if (state == m_State && !force) + return; + + m_State = state; + switch (state) + { + case HistoryState.Ready: + UpdateHistoryView(m_Pager); + break; + case HistoryState.Disabled: + Close(); + return; + } + + m_Container.Clear(); + m_Container.Add(m_Views[m_State]); + } + + public void UpdateRevisions(IEnumerable datas, string tip, int totalRevisions, int currentPage) + { + var elements = new List(); + var isFullDateObtained = false; // Has everything from this date been obtained? + m_HistoryItems.Clear(); + + if (datas != null) + { + DateTime currentDate = DateTime.MinValue; + foreach (var data in datas) + { + if (data.timeStamp.Date != currentDate.Date) + { + elements.Add(new CollabHistoryRevisionLine(data.timeStamp, isFullDateObtained)); + currentDate = data.timeStamp; + } + + var item = new CollabHistoryItem(data); + m_HistoryItems.Add(item); + + var container = new VisualElement(); + container.style.flexDirection = FlexDirection.Row; + if (data.current) + { + isFullDateObtained = true; + container.AddToClassList("currentRevision"); + container.AddToClassList("obtainedRevision"); + } + else if (data.obtained) + { + container.AddToClassList("obtainedRevision"); + } + else + { + container.AddToClassList("absentRevision"); + } + // If we use the index as-is, the latest commit will become #1, but we want it to be last + container.Add(new CollabHistoryRevisionLine(data.index)); + container.Add(item); + elements.Add(container); + } + } + + m_HistoryView.scrollOffset = new Vector2(0, 0); + m_Pager.totalItems = totalRevisions; + m_Pager.curPage = currentPage; + m_Pager.items = elements; + } + + public string inProgressRevision + { + get { return m_InProgressRev; } + set + { + m_InProgressRev = value; + foreach (var historyItem in m_HistoryItems) + { + historyItem.SetInProgressStatus(value); + } + } + } + + public int itemsPerPage + { + set + { + if (m_ItemsPerPage == value) + return; + m_Pager.pageSize = m_ItemsPerPage; + } + } + + public PageChangeAction OnPageChangeAction + { + set { m_Pager.OnPageChanged = value; } + } + + public RevisionAction OnGoBackAction + { + set { CollabHistoryItem.s_OnGoBack = value; } + } + + public RevisionAction OnUpdateAction + { + set { CollabHistoryItem.s_OnUpdate = value; } + } + + public RevisionAction OnRestoreAction + { + set { CollabHistoryItem.s_OnRestore = value; } + } + + public ShowBuildAction OnShowBuildAction + { + set { CollabHistoryItem.s_OnShowBuild = value; } + } + + public Action OnShowServicesAction + { + set { CollabHistoryItem.s_OnShowServices = value; } + } + + void UpdateHistoryView(VisualElement history) + { + } + + void NoSeatClick() + { + var connection = UnityConnect.instance; + var env = connection.GetEnvironment(); + // Map environment to url - prod is special + if (env == "production") + env = ""; + else + env += "-"; + + var url = "https://" + env + kServiceUrl + + "/orgs/" + connection.GetOrganizationId() + + "/projects/" + connection.GetProjectName() + + "/unity-teams/"; + Application.OpenURL(url); + } + + void SignInClick() + { + UnityConnect.instance.ShowLogin(); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/CollabToolbarButton.cs b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/CollabToolbarButton.cs new file mode 100644 index 00000000..eebe4aca --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/CollabToolbarButton.cs @@ -0,0 +1,297 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEditor.Collaboration; +using UnityEditor.Connect; +using UnityEditor.Web; +using UnityEngine; + +namespace UnityEditor +{ + internal class CollabToolbarButton : SubToolbar, IDisposable + { + // Must match s_CollabIcon array + enum CollabToolbarState + { + NeedToEnableCollab, + UpToDate, + Conflict, + OperationError, + ServerHasChanges, + FilesToPush, + InProgress, + Disabled, + Offline + } + + private class CollabToolbarContent + { + readonly string m_iconName; + readonly string m_toolTip; + readonly CollabToolbarState m_state; + + static Dictionary m_CollabIcons; + + public CollabToolbarState RegisteredForState + { + get { return m_state; } + } + + public GUIContent GuiContent + { + get + { + if (m_CollabIcons == null) + { + m_CollabIcons = new Dictionary(); + } + + if (!m_CollabIcons.ContainsKey(this)) + { + m_CollabIcons.Add(this, EditorGUIUtility.TrTextContentWithIcon("Collab", m_toolTip, m_iconName)); + } + + return m_CollabIcons[this]; + } + } + + public CollabToolbarContent(CollabToolbarState state, string iconName, string toolTip) + { + m_state = state; + m_iconName = iconName; + m_toolTip = toolTip; + } + } + + CollabToolbarContent[] m_toolbarContents; + CollabToolbarState m_CollabToolbarState = CollabToolbarState.UpToDate; + const float kCollabButtonWidth = 78.0f; + ButtonWithAnimatedIconRotation m_CollabButton; + string m_DynamicTooltip; + static bool m_ShowCollabTooltip = false; + + private GUIContent currentCollabContent + { + get + { + CollabToolbarContent toolbarContent = + m_toolbarContents.FirstOrDefault(c => c.RegisteredForState.Equals(m_CollabToolbarState)); + GUIContent content = new GUIContent(toolbarContent == null? m_toolbarContents.First().GuiContent : toolbarContent.GuiContent); + if (!m_ShowCollabTooltip) + { + content.tooltip = null; + } + else if (m_DynamicTooltip != "") + { + content.tooltip = m_DynamicTooltip; + } + + if (Collab.instance.AreTestsRunning()) + { + content.text = "CTF"; + } + + return content; + } + } + + public CollabToolbarButton() + { + m_toolbarContents = new[] + { + new CollabToolbarContent(CollabToolbarState.NeedToEnableCollab, "CollabNew", " You need to enable collab."), + new CollabToolbarContent(CollabToolbarState.UpToDate, "Collab", " You are up to date."), + new CollabToolbarContent(CollabToolbarState.Conflict, "CollabConflict", " Please fix your conflicts prior to publishing."), + new CollabToolbarContent(CollabToolbarState.OperationError, "CollabError", " Last operation failed. Please retry later."), + new CollabToolbarContent(CollabToolbarState.ServerHasChanges, "CollabPull", " Please update, there are server changes."), + new CollabToolbarContent(CollabToolbarState.FilesToPush, "CollabPush", " You have files to publish."), + new CollabToolbarContent(CollabToolbarState.InProgress, "CollabProgress", " Operation in progress."), + new CollabToolbarContent(CollabToolbarState.Disabled, "CollabNew", " Collab is disabled."), + new CollabToolbarContent(CollabToolbarState.Offline, "CollabNew", " Please check your network connection.") + }; + + Collab.instance.StateChanged += OnCollabStateChanged; + UnityConnect.instance.StateChanged += OnUnityConnectStateChanged; + UnityConnect.instance.UserStateChanged += OnUnityConnectUserStateChanged; + } + + void OnUnityConnectUserStateChanged(UserInfo state) + { + UpdateCollabToolbarState(); + } + + void OnUnityConnectStateChanged(ConnectInfo state) + { + UpdateCollabToolbarState(); + } + + public override void OnGUI(Rect rect) + { + DoCollabDropDown(rect); + } + + Rect GUIToScreenRect(Rect guiRect) + { + Vector2 screenPoint = GUIUtility.GUIToScreenPoint(new Vector2(guiRect.x, guiRect.y)); + guiRect.x = screenPoint.x; + guiRect.y = screenPoint.y; + return guiRect; + } + + void ShowPopup(Rect rect) + { + // window should be centered on the button + ReserveRight(kCollabButtonWidth / 2, ref rect); + ReserveBottom(5, ref rect); + // calculate screen rect before saving assets since it might open the AssetSaveDialog window + var screenRect = GUIToScreenRect(rect); + // save all the assets + AssetDatabase.SaveAssets(); + if (Collab.ShowToolbarAtPosition != null && Collab.ShowToolbarAtPosition(screenRect)) + { + GUIUtility.ExitGUI(); + } + } + + void DoCollabDropDown(Rect rect) + { + UpdateCollabToolbarState(); + GUIStyle collabButtonStyle = "OffsetDropDown"; + bool showPopup = Toolbar.requestShowCollabToolbar; + Toolbar.requestShowCollabToolbar = false; + + bool enable = !EditorApplication.isPlaying; + + using (new EditorGUI.DisabledScope(!enable)) + { + bool animate = m_CollabToolbarState == CollabToolbarState.InProgress; + + EditorGUIUtility.SetIconSize(new Vector2(12, 12)); + if (GetCollabButton().OnGUI(rect, currentCollabContent, animate, collabButtonStyle)) + { + showPopup = true; + } + EditorGUIUtility.SetIconSize(Vector2.zero); + } + + if (m_CollabToolbarState == CollabToolbarState.Disabled) + return; + + if (showPopup) + { + ShowPopup(rect); + } + } + + public void OnCollabStateChanged(CollabInfo info) + { + UpdateCollabToolbarState(); + } + + public void UpdateCollabToolbarState() + { + var currentCollabState = CollabToolbarState.UpToDate; + bool networkAvailable = UnityConnect.instance.connectInfo.online && UnityConnect.instance.connectInfo.loggedIn; + m_DynamicTooltip = ""; + + if (UnityConnect.instance.isDisableCollabWindow) + { + currentCollabState = CollabToolbarState.Disabled; + } + else if (networkAvailable) + { + Collab collab = Collab.instance; + CollabInfo currentInfo = collab.collabInfo; + UnityErrorInfo errInfo; + bool error = false; + if (collab.GetError((UnityConnect.UnityErrorFilter.ByContext | UnityConnect.UnityErrorFilter.ByChild), out errInfo)) + { + error = (errInfo.priority <= (int)UnityConnect.UnityErrorPriority.Error); + m_DynamicTooltip = errInfo.shortMsg; + } + + if (!currentInfo.ready) + { + currentCollabState = CollabToolbarState.InProgress; + } + else if (error) + { + currentCollabState = CollabToolbarState.OperationError; + } + else if (currentInfo.inProgress) + { + currentCollabState = CollabToolbarState.InProgress; + } + else + { + bool collabEnable = Collab.instance.IsCollabEnabledForCurrentProject(); + + if (UnityConnect.instance.projectInfo.projectBound == false || !collabEnable) + { + currentCollabState = CollabToolbarState.NeedToEnableCollab; + } + else if (currentInfo.update) + { + currentCollabState = CollabToolbarState.ServerHasChanges; + } + else if (currentInfo.conflict) + { + currentCollabState = CollabToolbarState.Conflict; + } + else if (currentInfo.publish) + { + currentCollabState = CollabToolbarState.FilesToPush; + } + } + } + else + { + currentCollabState = CollabToolbarState.Offline; + } + + if (Collab.IsToolbarVisible != null) + { + if (currentCollabState != m_CollabToolbarState || + Collab.IsToolbarVisible() == m_ShowCollabTooltip) + { + m_CollabToolbarState = currentCollabState; + m_ShowCollabTooltip = !Collab.IsToolbarVisible(); + Toolbar.RepaintToolbar(); + } + } + } + + void ReserveRight(float width, ref Rect pos) + { + pos.x += width; + } + + void ReserveBottom(float height, ref Rect pos) + { + pos.y += height; + } + + ButtonWithAnimatedIconRotation GetCollabButton() + { + if (m_CollabButton == null) + { + const int repaintsPerSecond = 20; + const float animSpeed = 500f; + const bool mouseDownButton = true; + m_CollabButton = new ButtonWithAnimatedIconRotation(() => (float)EditorApplication.timeSinceStartup * animSpeed, Toolbar.RepaintToolbar, repaintsPerSecond, mouseDownButton); + } + + return m_CollabButton; + } + + public void Dispose() + { + Collab.instance.StateChanged -= OnCollabStateChanged; + UnityConnect.instance.StateChanged -= OnUnityConnectStateChanged; + UnityConnect.instance.UserStateChanged -= OnUnityConnectUserStateChanged; + + if (m_CollabButton != null) + m_CollabButton.Clear(); + } + } +} // namespace \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/CollabToolbarWindow.cs b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/CollabToolbarWindow.cs new file mode 100644 index 00000000..27938750 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/CollabToolbarWindow.cs @@ -0,0 +1,137 @@ +using UnityEngine; +using UnityEditor.Collaboration; +using UnityEditor.Web; +using UnityEditor.Connect; + +namespace UnityEditor +{ + [InitializeOnLoad] + internal class WebViewStatic : ScriptableSingleton + { + [SerializeField] + WebView m_WebView; + + static public WebView GetWebView() + { + return instance.m_WebView; + } + + static public void SetWebView(WebView webView) + { + instance.m_WebView = webView; + } + } + + [InitializeOnLoad] + internal class CollabToolbarWindow : WebViewEditorStaticWindow, IHasCustomMenu + { + internal override WebView webView + { + get {return WebViewStatic.GetWebView(); } + set {WebViewStatic.SetWebView(value); } + } + + private const string kWindowName = "Unity Collab Toolbar"; + + private static long s_LastClosedTime; + private static CollabToolbarWindow s_CollabToolbarWindow; + + public static bool s_ToolbarIsVisible = false; + + const int kWindowWidth = 320; + const int kWindowHeight = 350; + + public static void CloseToolbar() + { + foreach (CollabToolbarWindow window in Resources.FindObjectsOfTypeAll()) + window.Close(); + } + + [MenuItem("Window/Asset Management/Collab Toolbar", false /*IsValidateFunction*/, 2, true /* IsInternalMenu */)] + public static CollabToolbarWindow ShowToolbarWindow() + { + //Create a new window if it does not exist + if (s_CollabToolbarWindow == null) + { + s_CollabToolbarWindow = GetWindow(false, kWindowName) as CollabToolbarWindow; + } + + return s_CollabToolbarWindow; + } + + [MenuItem("Window/Asset Management/Collab Toolbar", true /*IsValidateFunction*/)] + public static bool ValidateShowToolbarWindow() + { + return true; + } + + public static bool IsVisible() + { + return s_ToolbarIsVisible; + } + + public static bool ShowCenteredAtPosition(Rect buttonRect) + { + buttonRect.x -= kWindowWidth / 2; + // We could not use realtimeSinceStartUp since it is set to 0 when entering/exitting playmode, we assume an increasing time when comparing time. + long nowMilliSeconds = System.DateTime.Now.Ticks / System.TimeSpan.TicksPerMillisecond; + bool justClosed = nowMilliSeconds < s_LastClosedTime + 50; + if (!justClosed) + { + // Method may have been triggered programmatically, without a user event to consume. + if (Event.current.type != EventType.Layout) + { + Event.current.Use(); + } + if (s_CollabToolbarWindow == null) + s_CollabToolbarWindow = CreateInstance() as CollabToolbarWindow; + var windowSize = new Vector2(kWindowWidth, kWindowHeight); + s_CollabToolbarWindow.initialOpenUrl = "file:///" + EditorApplication.userJavascriptPackagesPath + "unityeditor-collab-toolbar/dist/index.html"; + s_CollabToolbarWindow.Init(); + s_CollabToolbarWindow.ShowAsDropDown(buttonRect, windowSize); + s_CollabToolbarWindow.OnFocus(); + return true; + } + return false; + } + + // Receives HTML title + public void OnReceiveTitle(string title) + { + titleContent.text = title; + } + + public new void OnInitScripting() + { + base.OnInitScripting(); + } + + public override void OnEnable() + { + minSize = new Vector2(kWindowWidth, kWindowHeight); + maxSize = new Vector2(kWindowWidth, kWindowHeight); + initialOpenUrl = "file:///" + EditorApplication.userJavascriptPackagesPath + "unityeditor-collab-toolbar/dist/index.html"; + base.OnEnable(); + s_ToolbarIsVisible = true; + } + + internal new void OnDisable() + { + s_LastClosedTime = System.DateTime.Now.Ticks / System.TimeSpan.TicksPerMillisecond; + if (s_CollabToolbarWindow) + { + s_ToolbarIsVisible = false; + NotifyVisibility(s_ToolbarIsVisible); + } + s_CollabToolbarWindow = null; + + base.OnDisable(); + } + + public new void OnDestroy() + { + OnLostFocus(); + base.OnDestroy(); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/Presenters/CollabHistoryPresenter.cs b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/Presenters/CollabHistoryPresenter.cs new file mode 100644 index 00000000..91d500be --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/Presenters/CollabHistoryPresenter.cs @@ -0,0 +1,228 @@ +using System.Collections.Generic; +using UnityEditor.Connect; +using UnityEditor.Web; + +namespace UnityEditor.Collaboration +{ + internal class CollabHistoryPresenter + { + public const int ItemsPerPage = 5; + ICollabHistoryWindow m_Window; + ICollabHistoryItemFactory m_Factory; + IRevisionsService m_Service; + ConnectInfo m_ConnectState; + CollabInfo m_CollabState; + bool m_IsCollabError; + int m_TotalRevisions; + int m_CurrentPage; + int m_RequestedPage; + bool m_FetchInProgress; + + BuildAccess m_BuildAccess; + string m_ProgressRevision; + public bool BuildServiceEnabled {get; set; } + + public CollabHistoryPresenter(ICollabHistoryWindow window, ICollabHistoryItemFactory factory, IRevisionsService service) + { + m_Window = window; + m_Factory = factory; + m_Service = service; + m_CurrentPage = 0; + m_BuildAccess = new BuildAccess(); + m_Service.FetchRevisionsCallback += OnFetchRevisions; + } + + public void OnWindowEnabled() + { + UnityConnect.instance.StateChanged += OnConnectStateChanged; + Collab.instance.StateChanged += OnCollabStateChanged; + Collab.instance.RevisionUpdated += OnCollabRevisionUpdated; + Collab.instance.JobsCompleted += OnCollabJobsCompleted; + Collab.instance.ErrorOccurred += OnCollabError; + Collab.instance.ErrorCleared += OnCollabErrorCleared; + EditorApplication.playModeStateChanged += OnPlayModeStateChanged; + m_ConnectState = UnityConnect.instance.GetConnectInfo(); + m_CollabState = Collab.instance.GetCollabInfo(); + + m_Window.revisionActionsEnabled = !EditorApplication.isPlayingOrWillChangePlaymode; + + // Setup window callbacks + m_Window.OnPageChangeAction = OnUpdatePage; + m_Window.OnUpdateAction = OnUpdate; + m_Window.OnRestoreAction = OnRestore; + m_Window.OnGoBackAction = OnGoBack; + m_Window.OnShowBuildAction = ShowBuildForCommit; + m_Window.OnShowServicesAction = ShowServicePage; + m_Window.itemsPerPage = ItemsPerPage; + + // Initialize data + UpdateBuildServiceStatus(); + var state = RecalculateState(); + // Only try to load the page if we're ready + if (state == HistoryState.Ready) + OnUpdatePage(m_CurrentPage); + m_Window.UpdateState(state, true); + } + + public void OnWindowDisabled() + { + UnityConnect.instance.StateChanged -= OnConnectStateChanged; + Collab.instance.StateChanged -= OnCollabStateChanged; + Collab.instance.RevisionUpdated -= OnCollabRevisionUpdated; + Collab.instance.JobsCompleted -= OnCollabJobsCompleted; + EditorApplication.playModeStateChanged -= OnPlayModeStateChanged; + } + + private void OnConnectStateChanged(ConnectInfo state) + { + m_ConnectState = state; + + m_Window.UpdateState(RecalculateState(), false); + } + + private void OnCollabStateChanged(CollabInfo state) + { + // Sometimes a collab state change will trigger even though everything is the same + if (m_CollabState.Equals(state)) + return; + + if (m_CollabState.tip != state.tip) + OnUpdatePage(m_CurrentPage); + + m_CollabState = state; + m_Window.UpdateState(RecalculateState(), false); + if (state.inProgress) + { + m_Window.inProgressRevision = m_ProgressRevision; + } + else + { + m_Window.inProgressRevision = null; + } + } + + private void OnCollabRevisionUpdated(CollabInfo state) + { + OnUpdatePage(m_CurrentPage); + } + + private void OnCollabJobsCompleted(CollabInfo state) + { + m_ProgressRevision = null; + } + + private void OnCollabError() + { + m_IsCollabError = true; + m_Window.UpdateState(RecalculateState(), false); + } + + private void OnCollabErrorCleared() + { + m_IsCollabError = false; + m_FetchInProgress = true; + m_Service.GetRevisions(m_CurrentPage * ItemsPerPage, ItemsPerPage); + m_Window.UpdateState(RecalculateState(), false); + } + + private void OnPlayModeStateChanged(PlayModeStateChange stateChange) + { + // If entering play mode, disable + if (stateChange == PlayModeStateChange.ExitingEditMode || + stateChange == PlayModeStateChange.EnteredPlayMode) + { + m_Window.revisionActionsEnabled = false; + } + // If exiting play mode, enable! + else if (stateChange == PlayModeStateChange.EnteredEditMode || + stateChange == PlayModeStateChange.ExitingPlayMode) + { + m_Window.revisionActionsEnabled = true; + } + } + + private HistoryState RecalculateState() + { + if (!m_ConnectState.online) + return HistoryState.Offline; + if (m_ConnectState.maintenance || m_CollabState.maintenance) + return HistoryState.Maintenance; + if (!m_ConnectState.loggedIn) + return HistoryState.LoggedOut; + if (!m_CollabState.seat) + return HistoryState.NoSeat; + if (!Collab.instance.IsCollabEnabledForCurrentProject()) + return HistoryState.Disabled; + if (!Collab.instance.IsConnected() || !m_CollabState.ready || m_FetchInProgress) + return HistoryState.Waiting; + if (m_ConnectState.error || m_IsCollabError) + return HistoryState.Error; + + return HistoryState.Ready; + } + + // TODO: Eventually this can be a listener on the build service status + public void UpdateBuildServiceStatus() + { + foreach (var service in UnityConnectServiceCollection.instance.GetAllServiceInfos()) + { + if (service.name.Equals("Build")) + { + BuildServiceEnabled = service.enabled; + } + } + } + + public void ShowBuildForCommit(string revisionID) + { + m_BuildAccess.ShowBuildForCommit(revisionID); + } + + public void ShowServicePage() + { + m_BuildAccess.ShowServicePage(); + } + + public void OnUpdatePage(int page) + { + m_FetchInProgress = true; + m_Service.GetRevisions(page * ItemsPerPage, ItemsPerPage); + m_Window.UpdateState(RecalculateState(), false); + m_RequestedPage = page; + } + + private void OnFetchRevisions(RevisionsResult data) + { + m_FetchInProgress = false; + IEnumerable items = null; + if (data != null) + { + m_CurrentPage = m_RequestedPage; + m_TotalRevisions = data.RevisionsInRepo; + items = m_Factory.GenerateElements(data.Revisions, m_TotalRevisions, m_CurrentPage * ItemsPerPage, m_Service.tipRevision, m_Window.inProgressRevision, m_Window.revisionActionsEnabled, BuildServiceEnabled, m_Service.currentUser); + } + + // State must be recalculated prior to inserting items + m_Window.UpdateState(RecalculateState(), false); + m_Window.UpdateRevisions(items, m_Service.tipRevision, m_TotalRevisions, m_CurrentPage); + } + + private void OnRestore(string revisionId, bool updatetorevision) + { + m_ProgressRevision = revisionId; + Collab.instance.ResyncToRevision(revisionId); + } + + private void OnGoBack(string revisionId, bool updatetorevision) + { + m_ProgressRevision = revisionId; + Collab.instance.GoBackToRevision(revisionId, false); + } + + private void OnUpdate(string revisionId, bool updatetorevision) + { + m_ProgressRevision = revisionId; + Collab.instance.Update(revisionId, updatetorevision); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/Views/BuildStatusButton.cs b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/Views/BuildStatusButton.cs new file mode 100644 index 00000000..ac3754d2 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/Views/BuildStatusButton.cs @@ -0,0 +1,53 @@ +using System; +using UnityEditor; +using UnityEditor.Collaboration; +using UnityEngine; + +#if UNITY_2019_1_OR_NEWER +using UnityEngine.UIElements; +#else +using UnityEngine.Experimental.UIElements; +#endif + +namespace UnityEditor.Collaboration +{ + internal class BuildStatusButton : Button + { + private readonly string iconPrefix = "Icons/Collab.Build"; + private readonly string iconSuffix = ".png"; + Label labelElement = new Label(); + Image iconElement = new Image() {name = "BuildIcon"}; + + public BuildStatusButton(Action clickEvent) : base(clickEvent) + { + iconElement.image = EditorGUIUtility.Load(iconPrefix + iconSuffix) as Texture; + labelElement.text = "Build Now"; + Add(iconElement); + Add(labelElement); + } + + public BuildStatusButton(Action clickEvent, BuildState state, int failures) : base(clickEvent) + { + switch (state) + { + case BuildState.InProgress: + iconElement.image = EditorGUIUtility.Load(iconPrefix + iconSuffix) as Texture; + labelElement.text = "In progress"; + break; + + case BuildState.Failed: + iconElement.image = EditorGUIUtility.Load(iconPrefix + "Failed" + iconSuffix) as Texture; + labelElement.text = failures + ((failures == 1) ? " failure" : " failures"); + break; + + case BuildState.Success: + iconElement.image = EditorGUIUtility.Load(iconPrefix + "Succeeded" + iconSuffix) as Texture; + labelElement.text = "success"; + break; + } + + Add(iconElement); + Add(labelElement); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/Views/CollabHistoryDropDown.cs b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/Views/CollabHistoryDropDown.cs new file mode 100644 index 00000000..e3bb05a6 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/Views/CollabHistoryDropDown.cs @@ -0,0 +1,78 @@ +using UnityEngine; +using System.Collections.Generic; +using UnityEditor.Connect; + +#if UNITY_2019_1_OR_NEWER +using UnityEngine.UIElements; +#else +using UnityEngine.Experimental.UIElements; +#endif + + +namespace UnityEditor.Collaboration +{ + internal class CollabHistoryDropDown : VisualElement + { + private readonly VisualElement m_FilesContainer; + private readonly Label m_ToggleLabel; + private int m_ChangesTotal; + private string m_RevisionId; + + public CollabHistoryDropDown(ICollection changes, int changesTotal, bool changesTruncated, string revisionId) + { + m_FilesContainer = new VisualElement(); + m_ChangesTotal = changesTotal; + m_RevisionId = revisionId; + + m_ToggleLabel = new Label(ToggleText(false)); + m_ToggleLabel.AddManipulator(new Clickable(ToggleDropdown)); + Add(m_ToggleLabel); + + foreach (ChangeData change in changes) + { + m_FilesContainer.Add(new CollabHistoryDropDownItem(change.path, change.action)); + } + + if (changesTruncated) + { + m_FilesContainer.Add(new Button(ShowAllClick) + { + text = "Show all on dashboard" + }); + } + } + + private void ToggleDropdown() + { + if (Contains(m_FilesContainer)) + { + CollabAnalytics.SendUserAction(CollabAnalytics.historyCategoryString, "CollapseAssets"); + Remove(m_FilesContainer); + m_ToggleLabel.text = ToggleText(false); + } + else + { + CollabAnalytics.SendUserAction(CollabAnalytics.historyCategoryString, "ExpandAssets"); + Add(m_FilesContainer); + m_ToggleLabel.text = ToggleText(true); + } + } + + private string ToggleText(bool open) + { + var icon = open ? "\u25bc" : "\u25b6"; + var change = m_ChangesTotal == 1 ? "Change" : "Changes"; + return string.Format("{0} {1} Asset {2}", icon, m_ChangesTotal, change); + } + + private void ShowAllClick() + { + var host = UnityConnect.instance.GetConfigurationURL(CloudConfigUrl.CloudServicesDashboard); + var org = UnityConnect.instance.GetOrganizationId(); + var proj = UnityConnect.instance.GetProjectGUID(); + var url = string.Format("{0}/collab/orgs/{1}/projects/{2}/commits?commit={3}", host, org, proj, m_RevisionId); + CollabAnalytics.SendUserAction(CollabAnalytics.historyCategoryString, "ShowAllOnDashboard"); + Application.OpenURL(url); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/Views/CollabHistoryDropDownItem.cs b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/Views/CollabHistoryDropDownItem.cs new file mode 100644 index 00000000..3ad43f23 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/Views/CollabHistoryDropDownItem.cs @@ -0,0 +1,53 @@ +using System; +using System.IO; +using System.Linq; +using UnityEngine; + +#if UNITY_2019_1_OR_NEWER +using UnityEngine.UIElements; +#else +using UnityEngine.Experimental.UIElements; +#endif + + +namespace UnityEditor.Collaboration +{ + internal class CollabHistoryDropDownItem : VisualElement + { + public CollabHistoryDropDownItem(string path, string action) + { + var fileName = Path.GetFileName(path); + var isFolder = Path.GetFileNameWithoutExtension(path).Equals(fileName); + var fileIcon = GetIconElement(action, fileName, isFolder); + var metaContainer = new VisualElement(); + var fileNameLabel = new Label + { + name = "FileName", + text = fileName + }; + var filePathLabel = new Label + { + name = "FilePath", + text = path + }; + metaContainer.Add(fileNameLabel); + metaContainer.Add(filePathLabel); + Add(fileIcon); + Add(metaContainer); + } + + private Image GetIconElement(string action, string fileName, bool isFolder) + { + var prefix = isFolder ? "Folder" : "File"; + var actionName = action.First().ToString().ToUpper() + action.Substring(1); + // Use the same icon for renamed and moved files + actionName = actionName.Equals("Renamed") ? "Moved" : actionName; + var iconElement = new Image + { + name = "FileIcon", + image = EditorGUIUtility.LoadIcon("Icons/Collab." + prefix + actionName + ".png") + }; + return iconElement; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/Views/CollabHistoryItem.cs b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/Views/CollabHistoryItem.cs new file mode 100644 index 00000000..24e5d1dd --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/Views/CollabHistoryItem.cs @@ -0,0 +1,229 @@ +using System; +using System.Linq; +using System.Security.Cryptography; +using UnityEditor.Connect; +using UnityEditor.Web; +using UnityEngine; + +#if UNITY_2019_1_OR_NEWER +using UnityEngine.UIElements; +#else +using UnityEngine.Experimental.UIElements; +using UnityEngine.Experimental.UIElements.StyleEnums; +#endif + +namespace UnityEditor.Collaboration +{ + internal class CollabHistoryItem : VisualElement + { + public static RevisionAction s_OnRestore; + public static RevisionAction s_OnGoBack; + public static RevisionAction s_OnUpdate; + public static ShowBuildAction s_OnShowBuild; + public static Action s_OnShowServices; + + private readonly string m_RevisionId; + private readonly string m_FullDescription; + private readonly DateTime m_TimeStamp; + private readonly Button m_Button; + private readonly HistoryProgressSpinner m_ProgressSpinner; + private VisualElement m_ActionsTray; + private VisualElement m_Details; + private Label m_Description; + private Label m_TimeAgo; + private readonly Button m_ExpandCollapseButton; + private bool m_Expanded; + + private const int kMaxDescriptionChars = 500; + + public bool RevisionActionsEnabled + { + set + { + m_Button.SetEnabled(value); + } + } + + public DateTime timeStamp + { + get { return m_TimeStamp; } + } + + public CollabHistoryItem(RevisionData data) + { + m_RevisionId = data.id; + m_TimeStamp = data.timeStamp; + name = "HistoryItem"; + m_ActionsTray = new VisualElement {name = "HistoryItemActionsTray"}; + m_ProgressSpinner = new HistoryProgressSpinner(); + m_Details = new VisualElement {name = "HistoryDetail"}; + var author = new Label(data.authorName) {name = "Author"}; + m_TimeAgo = new Label(TimeAgo.GetString(m_TimeStamp)); + m_FullDescription = data.comment; + var shouldTruncate = ShouldTruncateDescription(m_FullDescription); + if (shouldTruncate) + { + m_Description = new Label(GetTruncatedDescription(m_FullDescription)); + } + else + { + m_Description = new Label(m_FullDescription); + } + m_Description.name = "RevisionDescription"; + var dropdown = new CollabHistoryDropDown(data.changes, data.changesTotal, data.changesTruncated, data.id); + if (data.current) + { + m_Button = new Button(Restore) {name = "ActionButton", text = "Restore"}; + } + else if (data.obtained) + { + m_Button = new Button(GoBackTo) {name = "ActionButton", text = "Go back to..."}; + } + else + { + m_Button = new Button(UpdateTo) {name = "ActionButton", text = "Update"}; + } + m_Button.SetEnabled(data.enabled); + m_ProgressSpinner.ProgressEnabled = data.inProgress; + + m_ActionsTray.Add(m_ProgressSpinner); + m_ActionsTray.Add(m_Button); + + m_Details.Add(author); + m_Details.Add(m_TimeAgo); + m_Details.Add(m_Description); + + if (shouldTruncate) + { + m_ExpandCollapseButton = new Button(ToggleDescription) { name = "ToggleDescription", text = "Show More" }; + m_Details.Add(m_ExpandCollapseButton); + } + + if (data.buildState != BuildState.None) + { + BuildStatusButton buildButton; + if (data.buildState == BuildState.Configure) + buildButton = new BuildStatusButton(ShowServicePage); + else + buildButton = new BuildStatusButton(ShowBuildForCommit, data.buildState, data.buildFailures); + + m_Details.Add(buildButton); + } + + m_Details.Add(m_ActionsTray); + m_Details.Add(dropdown); + + Add(m_Details); + + this.schedule.Execute(UpdateTimeAgo).Every(1000 * 20); + } + + public static void SetUpCallbacks(RevisionAction Restore, RevisionAction GoBack, RevisionAction Update) + { + s_OnRestore = Restore; + s_OnGoBack = GoBack; + s_OnUpdate = Update; + } + + public void SetInProgressStatus(string revisionIdInProgress) + { + if (String.IsNullOrEmpty(revisionIdInProgress)) + { + m_Button.SetEnabled(true); + m_ProgressSpinner.ProgressEnabled = false; + } + else + { + m_Button.SetEnabled(false); + if (m_RevisionId.Equals(revisionIdInProgress)) + { + m_ProgressSpinner.ProgressEnabled = true; + } + } + } + + void ShowBuildForCommit() + { + CollabAnalytics.SendUserAction(CollabAnalytics.historyCategoryString, "ShowBuild"); + if (s_OnShowBuild != null) + { + s_OnShowBuild(m_RevisionId); + } + } + + void ShowServicePage() + { + CollabAnalytics.SendUserAction(CollabAnalytics.historyCategoryString, "ShowServices"); + if (s_OnShowServices != null) + { + s_OnShowServices(); + } + } + + void Restore() + { + CollabAnalytics.SendUserAction(CollabAnalytics.historyCategoryString, "Restore"); + if (s_OnRestore != null) + { + s_OnRestore(m_RevisionId, false); + } + } + + void GoBackTo() + { + CollabAnalytics.SendUserAction(CollabAnalytics.historyCategoryString, "GoBackTo"); + if (s_OnGoBack != null) + { + s_OnGoBack(m_RevisionId, false); + } + } + + void UpdateTo() + { + CollabAnalytics.SendUserAction(CollabAnalytics.historyCategoryString, "Update"); + if (s_OnUpdate != null) + { + s_OnUpdate(m_RevisionId, true); + } + } + + void UpdateTimeAgo() + { + m_TimeAgo.text = TimeAgo.GetString(m_TimeStamp); + } + + bool ShouldTruncateDescription(string description) + { + return description.Contains(Environment.NewLine) || description.Length > kMaxDescriptionChars; + } + + string GetTruncatedDescription(string description) + { + string result = description.Contains(Environment.NewLine) ? + description.Substring(0, description.IndexOf(Environment.NewLine)) : description; + if (result.Length > kMaxDescriptionChars) + { + result = result.Substring(0, kMaxDescriptionChars) + "..."; + } + return result; + } + + void ToggleDescription() + { + if (m_Expanded) + { + CollabAnalytics.SendUserAction(CollabAnalytics.historyCategoryString, "CollapseDescription"); + m_Expanded = false; + m_ExpandCollapseButton.text = "Show More"; + m_Description.text = GetTruncatedDescription(m_FullDescription); + } + else + { + CollabAnalytics.SendUserAction(CollabAnalytics.historyCategoryString, "ExpandDescription"); + m_Expanded = true; + m_ExpandCollapseButton.text = "Show Less"; + m_Description.text = m_FullDescription; + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/Views/CollabHistoryItemFactory.cs b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/Views/CollabHistoryItemFactory.cs new file mode 100644 index 00000000..e7d7aa6c --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/Views/CollabHistoryItemFactory.cs @@ -0,0 +1,121 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEditor.Collaboration; +using UnityEngine; + +#if UNITY_2019_1_OR_NEWER +using UnityEngine.UIElements; +#else +using UnityEngine.Experimental.UIElements; +using UnityEngine.Experimental.UIElements.StyleEnums; +#endif + + +namespace UnityEditor.Collaboration +{ + internal class CollabHistoryItemFactory : ICollabHistoryItemFactory + { + const int k_MaxChangesPerRevision = 10; + + public IEnumerable GenerateElements(IEnumerable revisions, int totalRevisions, int startIndex, string tipRev, string inProgressRevision, bool revisionActionsEnabled, bool buildServiceEnabled, string currentUser) + { + int index = startIndex; + + foreach (var rev in revisions) + { + index++; + var current = rev.revisionID == tipRev; + + // Calculate build status + BuildState buildState = BuildState.None; + int buildFailures = 0; + if (rev.buildStatuses != null && rev.buildStatuses.Length > 0) + { + bool inProgress = false; + foreach (CloudBuildStatus buildStatus in rev.buildStatuses) + { + if (buildStatus.complete) + { + if (!buildStatus.success) + { + buildFailures++; + } + } + else + { + inProgress = true; + break; + } + } + + if (inProgress) + { + buildState = BuildState.InProgress; + } + else if (buildFailures > 0) + { + buildState = BuildState.Failed; + } + else + { + buildState = BuildState.Success; + } + } + else if (current && !buildServiceEnabled) + { + buildState = BuildState.Configure; + } + + // Calculate the number of changes performed on files and folders (not meta files) + var paths = new Dictionary(); + foreach (ChangeAction change in rev.entries) + { + if (change.path.EndsWith(".meta")) + { + var path = change.path.Substring(0, change.path.Length - 5); + // Actions taken on meta files are secondary to any actions taken on the main file + if (!paths.ContainsKey(path)) + paths[path] = new ChangeData() {path = path, action = change.action}; + } + else + { + paths[change.path] = new ChangeData() {path = change.path, action = change.action}; + } + } + + var displayName = (rev.author != currentUser) ? rev.authorName : "You"; + + var item = new RevisionData + { + id = rev.revisionID, + index = totalRevisions - index + 1, + timeStamp = TimeStampToDateTime(rev.timeStamp), + authorName = displayName, + comment = rev.comment, + + obtained = rev.isObtained, + current = current, + inProgress = (rev.revisionID == inProgressRevision), + enabled = revisionActionsEnabled, + + buildState = buildState, + buildFailures = buildFailures, + + changes = paths.Values.Take(k_MaxChangesPerRevision).ToList(), + changesTotal = paths.Values.Count, + changesTruncated = paths.Values.Count > k_MaxChangesPerRevision, + }; + + yield return item; + } + } + + private static DateTime TimeStampToDateTime(double timeStamp) + { + DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); + dateTime = dateTime.AddSeconds(timeStamp).ToLocalTime(); + return dateTime; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/Views/CollabHistoryRevisionLine.cs b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/Views/CollabHistoryRevisionLine.cs new file mode 100644 index 00000000..2b8fe652 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/Views/CollabHistoryRevisionLine.cs @@ -0,0 +1,94 @@ +using System; +using UnityEditor; +using UnityEditor.Collaboration; +using UnityEngine; + +#if UNITY_2019_1_OR_NEWER +using UnityEngine.UIElements; +#else +using UnityEngine.Experimental.UIElements; +#endif + +namespace UnityEditor.Collaboration +{ + internal class CollabHistoryRevisionLine : VisualElement + { + public CollabHistoryRevisionLine(int number) + { + AddNumber(number); + AddLine("topLine"); + AddLine("bottomLine"); + AddIndicator(); + } + + public CollabHistoryRevisionLine(DateTime date, bool isFullDateObtained) + { + AddLine(isFullDateObtained ? "obtainedDateLine" : "absentDateLine"); + AddHeader(GetFormattedHeader(date)); + AddToClassList("revisionLineHeader"); + } + + private void AddHeader(string content) + { + Add(new Label + { + text = content + }); + } + + private void AddIndicator() + { + Add(new VisualElement + { + name = "RevisionIndicator" + }); + } + + private void AddLine(string className = null) + { + var line = new VisualElement + { + name = "RevisionLine" + }; + if (!String.IsNullOrEmpty(className)) + { + line.AddToClassList(className); + } + Add(line); + } + + private void AddNumber(int number) + { + Add(new Label + { + text = number.ToString(), + name = "RevisionIndex" + }); + } + + private string GetFormattedHeader(DateTime date) + { + string result = "Commits on " + date.ToString("MMM d"); + switch (date.Day) + { + case 1: + case 21: + case 31: + result += "st"; + break; + case 2: + case 22: + result += "nd"; + break; + case 3: + case 23: + result += "rd"; + break; + default: + result += "th"; + break; + } + return result; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/Views/HistoryProgressSpinner.cs b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/Views/HistoryProgressSpinner.cs new file mode 100644 index 00000000..fad3b824 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/Views/HistoryProgressSpinner.cs @@ -0,0 +1,69 @@ +using UnityEngine; + +#if UNITY_2019_1_OR_NEWER +using UnityEngine.UIElements; +#else +using UnityEngine.Experimental.UIElements; +#endif + +namespace UnityEditor.Collaboration +{ + internal class HistoryProgressSpinner : Image + { + private readonly Texture2D[] m_StatusWheelTextures; + private bool m_ProgressEnabled; + private IVisualElementScheduledItem m_Animation; + + public bool ProgressEnabled + { + set + { + if (m_ProgressEnabled == value) + return; + + m_ProgressEnabled = value; + visible = value; + + + if (value) + { + if (m_Animation == null) + { + m_Animation = this.schedule.Execute(AnimateProgress).Every(33); + } + else + { + m_Animation.Resume(); + } + } + else + { + if (m_Animation != null) + { + m_Animation.Pause(); + } + } + } + } + + public HistoryProgressSpinner() + { + m_StatusWheelTextures = new Texture2D[12]; + for (int i = 0; i < 12; i++) + { + m_StatusWheelTextures[i] = EditorGUIUtility.LoadIcon("WaitSpin" + i.ToString("00")); + } + image = m_StatusWheelTextures[0]; + style.width = m_StatusWheelTextures[0].width; + style.height = m_StatusWheelTextures[0].height; + visible = false; + } + + private void AnimateProgress(TimerState obj) + { + int frame = (int)Mathf.Repeat(Time.realtimeSinceStartup * 10, 11.99f); + image = m_StatusWheelTextures[frame]; + MarkDirtyRepaint(); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/Views/ICollabHistoryItemFactory.cs b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/Views/ICollabHistoryItemFactory.cs new file mode 100644 index 00000000..03239a33 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/Views/ICollabHistoryItemFactory.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using UnityEditor.Collaboration; + +#if UNITY_2019_1_OR_NEWER +using UnityEngine.UIElements; +#else +using UnityEngine.Experimental.UIElements; +#endif + +namespace UnityEditor.Collaboration +{ + internal interface ICollabHistoryItemFactory + { + IEnumerable GenerateElements(IEnumerable revsRevisions, int mTotalRevisions, int startIndex, string tipRev, string inProgressRevision, bool revisionActionsEnabled, bool buildServiceEnabled, string currentUser); + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/Views/PagedListView.cs b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/Views/PagedListView.cs new file mode 100644 index 00000000..472a70e7 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/Views/PagedListView.cs @@ -0,0 +1,192 @@ +using System; +using System.Collections.Generic; + +#if UNITY_2019_1_OR_NEWER +using UnityEngine.UIElements; +#else +using UnityEngine.Experimental.UIElements; +using UnityEngine.Experimental.UIElements.StyleEnums; +#endif + +namespace UnityEditor.Collaboration +{ + internal interface IPagerData + { + int curPage { get; } + int totalPages { get; } + PageChangeAction OnPageChanged { get; } + } + + internal class PagerElement : VisualElement + { + IPagerData m_Data; + readonly Label m_PageText; + readonly Button m_DownButton; + readonly Button m_UpButton; + + public PagerElement(IPagerData dataSource) + { + m_Data = dataSource; + + this.style.flexDirection = FlexDirection.Row; + this.style.alignSelf = Align.Center; + + Add(m_DownButton = new Button(OnPageDownClicked) {text = "\u25c5 Newer"}); + m_DownButton.AddToClassList("PagerDown"); + + m_PageText = new Label(); + m_PageText.AddToClassList("PagerLabel"); + Add(m_PageText); + + Add(m_UpButton = new Button(OnPageUpClicked) {text = "Older \u25bb"}); + m_UpButton.AddToClassList("PagerUp"); + + UpdateControls(); + } + + void OnPageDownClicked() + { + CollabAnalytics.SendUserAction(CollabAnalytics.historyCategoryString, "NewerPage"); + m_Data.OnPageChanged(m_Data.curPage - 1); + } + + void OnPageUpClicked() + { + CollabAnalytics.SendUserAction(CollabAnalytics.historyCategoryString, "OlderPage"); + m_Data.OnPageChanged(m_Data.curPage + 1); + } + + public void Refresh() + { + UpdateControls(); + } + + void UpdateControls() + { + var curPage = m_Data.curPage; + var totalPages = m_Data.totalPages; + + m_PageText.text = (curPage + 1) + " / " + totalPages; + m_DownButton.SetEnabled(curPage > 0); + m_UpButton.SetEnabled(curPage < totalPages - 1); + } + } + + internal enum PagerLocation + { + Top, + Bottom, + } + + internal class PagedListView : VisualElement, IPagerData + { + public const int DefaultItemsPerPage = 10; + + readonly VisualElement m_ItemContainer; + readonly PagerElement m_PagerTop, m_PagerBottom; + int m_PageSize = DefaultItemsPerPage; + IEnumerable m_Items; + int m_TotalItems; + int m_CurPage; + + public int pageSize + { + set { m_PageSize = value; } + } + + public IEnumerable items + { + set + { + m_Items = value; + LayoutItems(); + } + } + + public int totalItems + { + set + { + if (m_TotalItems == value) + return; + + m_TotalItems = value; + UpdatePager(); + } + } + + public PageChangeAction OnPageChanged { get; set; } + + public PagedListView() + { + m_PagerTop = new PagerElement(this); + + m_ItemContainer = new VisualElement() + { + name = "PagerItems", + }; + Add(m_ItemContainer); + m_Items = new List(); + + m_PagerBottom = new PagerElement(this); + } + + void LayoutItems() + { + m_ItemContainer.Clear(); + foreach (var item in m_Items) + { + m_ItemContainer.Add(item); + } + } + + void UpdatePager() + { + if (m_PagerTop.parent != this && totalPages > 1 && curPage > 0) + Insert(0, m_PagerTop); + if (m_PagerTop.parent == this && (totalPages <= 1 || curPage == 0)) + Remove(m_PagerTop); + + if (m_PagerBottom.parent != this && totalPages > 1) + Add(m_PagerBottom); + if (m_PagerBottom.parent == this && totalPages <= 1) + Remove(m_PagerBottom); + + m_PagerTop.Refresh(); + m_PagerBottom.Refresh(); + } + + int pageCount + { + get + { + var pages = m_TotalItems / m_PageSize; + if (m_TotalItems % m_PageSize > 0) + pages++; + + return pages; + } + } + + public int curPage + { + get { return m_CurPage; } + set + { + m_CurPage = value; + UpdatePager(); + } + } + + public int totalPages + { + get + { + var extraPage = 0; + if (m_TotalItems % m_PageSize > 0) + extraPage = 1; + return m_TotalItems / m_PageSize + extraPage; + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/Views/StatusView.cs b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/Views/StatusView.cs new file mode 100644 index 00000000..9b50e7a5 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Collab/Views/StatusView.cs @@ -0,0 +1,88 @@ +using System; +using UnityEditor; +using UnityEngine; + +#if UNITY_2019_1_OR_NEWER +using UnityEngine.UIElements; +#else +using UnityEngine.Experimental.UIElements; +using UnityEngine.Experimental.UIElements.StyleEnums; +#endif + +namespace UnityEditor.Collaboration +{ + internal class StatusView : VisualElement + { + Image m_Image; + Label m_Message; + Button m_Button; + Action m_Callback; + + public Texture icon + { + get { return m_Image.image; } + set + { + m_Image.image = value; + m_Image.visible = value != null; + // Until "display: hidden" is added, this is the only way to hide an element + m_Image.style.height = value != null ? 150 : 0; + } + } + + public string message + { + get { return m_Message.text; } + set + { + m_Message.text = value; + m_Message.visible = value != null; + } + } + + public string buttonText + { + get { return m_Button.text; } + set + { + m_Button.text = value; + UpdateButton(); + } + } + + public Action callback + { + get { return m_Callback; } + set + { + m_Callback = value; + UpdateButton(); + } + } + + public StatusView() + { + name = "StatusView"; + + this.StretchToParentSize(); + + m_Image = new Image() { name = "StatusIcon", visible = false, style = { height = 0f }}; + m_Message = new Label() { name = "StatusMessage", visible = false}; + m_Button = new Button(InternalCallaback) { name = "StatusButton", visible = false}; + + Add(m_Image); + Add(m_Message); + Add(m_Button); + } + + private void UpdateButton() + { + m_Button.visible = m_Button.text != null && m_Callback != null; + } + + private void InternalCallaback() + { + m_Callback(); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Resources/Styles/CollabHistoryCommon.uss b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Resources/Styles/CollabHistoryCommon.uss new file mode 100644 index 00000000..b20f08e9 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Resources/Styles/CollabHistoryCommon.uss @@ -0,0 +1,259 @@ +.unity-button { + min-height:0; + -unity-text-align:middle-center; + margin-left:4px; + margin-top:3px; + margin-right:4px; + margin-bottom:3px; + border-left-width:6px; + border-top-width:4px; + border-right-width:6px; + border-bottom-width:4px; + padding-left:6px; + padding-top:2px; + padding-right:6px; + padding-bottom:3px; +} + +.unity-label { + overflow: hidden; + margin-left:4px; + margin-top:2px; + margin-right:4px; + margin-bottom:2px; + padding-left:2px; + padding-top:1px; + min-height: 0; +} + +#HistoryContainer { + flex: 1 0 0; +} + +#HistoryItem { + flex: 1 0 0; + flex-direction: row; +} + +#HistoryDetail { + margin-top: 10px; + margin-left: 10px; + margin-bottom: 10px; + margin-right: 10px; + padding-top: 4px; + flex: 1 0 0; +} + +#Author { + -unity-font-style: bold; + font-size: 12px; +} + +#HistoryDetail > Button { + align-self: flex-end; +} + +CollabHistoryRevisionLine { + width: 40px; +} + +#RevisionLine { + flex: 1 0 0; + margin-left: 35px; + width: 1.5px; +} + +#RevisionLine.topLine { + height: 20px; + flex: 0 0 auto; +} + +#RevisionLine.absentDateLine { + background-color: #797676; +} + +.absentRevision #RevisionLine { + background-color: #797676; +} + +.currentRevision #RevisionLine.topLine { + background-color: #797676; +} + +#RevisionIndex { + position: absolute; + min-width: 23px; + -unity-text-align: middle-right; + top: 15.8px; + font-size: 9px; +} + +#RevisionIndicator { + position: absolute; + background-color: #000; + border-radius: 3px; + width: 8px; + height: 8px; + border-bottom-width: 2px; + border-left-width: 2px; + border-right-width: 2px; + border-top-width: 2px; + top: 20px; + left: 32px; +} + +.revisionLineHeader { + width: 200px; + height: 20px; +} + +.revisionLineHeader > .unity-label { + position: absolute; + margin-left: 47px; + margin-top: 3px; +} + +#PagerItems { + flex-direction: column; +} + +PagerElement > .unity-label { + margin-top: 8px; +} + +.absentRevision #RevisionIndicator { + border-color: #797676; +} + +.absentRevision #RevisionIndex { + color: #797676; +} + +.currentRevision #HistoryDetail { + border-top-width: 2px; +} + +#HistoryItem #RevisionDescription { + white-space: normal; +} + +#HistoryItem #ToggleDescription { + align-self: flex-start; + padding-top: 0; + padding-left: 0; + padding-right: 0; + padding-bottom: 2px; +} + +#HistoryItem #ActionButton { + position: absolute; + right: 0; +} + +#HistoryItem #BuildIcon { + width: 16px; + height: 13px; +} + +#HistoryItemActionsTray { + flex: 1 0 0; + flex-direction: row; + align-items: center; + height: 38px; + margin-left: 10px; + margin-right: 10px; +} + +CollabHistoryDropDown { + border-top-width: 1px; +} + +CollabHistoryDropDown > .unity-label { + padding-top: 10px; + padding-bottom: 10px; +} + +CollabHistoryDropDownItem { + flex-direction: row; + border-top-width: 1px; + overflow: hidden; +} + +#FileIcon { + align-self: center; + width: 26px; + height: 26px; +} + +#FileName { + -unity-font-style: bold; + padding-bottom: 0; + margin-bottom: 0; +} + +#FileIcon { + padding-top: 0; + margin-top: 0; +} + +#ErrorBar { + height: 24px; + background-color: #ff0000; + color: #000; + font-size: 12px; +} + +#ErrorBar > #CloseButton { + position: absolute; + right: 0; + top: 0; + width: 24px; + height: 24px; + color: #000; + font-size: 18px; + -unity-font-style: bold; +} + +#StatusView { + flex-direction: column; + justify-content: center; + align-self: center; + align-items: center; + flex: 1 0 0; +} + +#StatusView > #StatusIcon { + width: 115px; + height: 150px; +} + +#StatusView > #StatusMessage { + font-size: 22px; + width: 230px; + white-space: normal; + -unity-text-align: middle-center; +} + +#StatusView > #StatusButton { + font-size: 12px; + margin-top: 20px; + background-image: none; + width: 108px; + height: 29px; +} + +BuildStatusButton.unity-button { + flex-direction: row; + align-self: flex-end; + align-items: center; + margin-right: 10px; + padding-left:0; + padding-top:0; + padding-right:0; + padding-bottom:0; +} + +BuildStatusButton.unity-button .unity-label { + padding-left: 2px; +} + diff --git a/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Resources/Styles/CollabHistoryDark.uss b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Resources/Styles/CollabHistoryDark.uss new file mode 100644 index 00000000..de436f89 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Resources/Styles/CollabHistoryDark.uss @@ -0,0 +1,86 @@ +#HistoryContainer { + background-color: #292929; +} + +.obtainedRevision #HistoryDetail { + background-color: #333; +} + +.absentRevision #HistoryDetail { + background-color: #595959; +} + +#StatusView { + background-color: #292929; +} + +#StatusView > #StatusMessage { + color: #959995; +} + +BuildStatusButton.unity-button { + color: #B4B4B4; + background-image: resource("Builtin Skins/DarkSkin/Images/btn.png"); +} + +BuildStatusButton.unity-button:hover { + color: #FFF; +} + +BuildStatusButton.unity-button:hover:active { + background-image: resource("Builtin Skins/DarkSkin/Images/btn act.png"); +} + +BuildStatusButton.unity-button:checked { + color: #F0F0F0; + background-image: resource("Builtin Skins/DarkSkin/Images/btn on.png"); +} + +BuildStatusButton.unity-button:hover:checked { + color: #FFF; +} + +BuildStatusButton.unity-button:hover:active:checked { + background-image: resource("Builtin Skins/DarkSkin/Images/btn onact.png"); +} + +BuildStatusButton.unity-button:focus:checked { + background-image: resource("Builtin Skins/DarkSkin/Images/btn on focus.png"); +} + +CollabHistoryDropDown { + border-color: #292929; +} + +CollabHistoryDropDownItem { + border-color: #292929; +} + +#RevisionLine.obtainedDateLine { + background-color: #0cb4cc; +} + +.obtainedRevision #RevisionLine { + background-color: #0cb4cc; +} + +#RevisionIndex { + color: #0cb4cc; +} + +#RevisionIndicator { + border-color: #0cb4cc; +} + +.currentRevision #RevisionIndicator { + background-color: #0cb4cc; +} + +.currentRevision #HistoryDetail { + border-color: #0cb4cc; +} + +#StatusView > #StatusButton { + background-color: #0cb4cc; + border-color: #0cb4cc; +} diff --git a/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Resources/Styles/CollabHistoryLight.uss b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Resources/Styles/CollabHistoryLight.uss new file mode 100644 index 00000000..3f9b85f3 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Resources/Styles/CollabHistoryLight.uss @@ -0,0 +1,86 @@ +#HistoryContainer { + background-color: #a2a2a2; +} + +.obtainedRevision #HistoryDetail { + background-color: #c2c2c2; +} + +.absentRevision #HistoryDetail { + background-color: #dedede; +} + +#StatusView { + background-color: #a2a2a3; +} + +#StatusView > #StatusMessage { + color: #000; +} + +BuildStatusButton.unity-button { + color: #111; + background-image: resource("Builtin Skins/LightSkin/Images/btn.png"); +} + +BuildStatusButton.unity-button:hover { + color: #000; +} + +BuildStatusButton.unity-button:hover:active { + background-image: resource("Builtin Skins/LightSkin/Images/btn act.png"); +} + +BuildStatusButton.unity-button:checked { + color: #F0F0F0; + background-image: resource("Builtin Skins/LightSkin/Images/btn on.png"); +} + +BuildStatusButton.unity-button:hover:checked { + color: #000; +} + +BuildStatusButton.unity-button:hover:active:checked { + background-image: resource("Builtin Skins/LightSkin/Images/btn onact.png"); +} + +BuildStatusButton.unity-button:focus:checked { + background-image: resource("Builtin Skins/LightSkin/Images/btn on focus.png"); +} + +CollabHistoryDropDown { + border-color: #a2a2a2; +} + +CollabHistoryDropDownItem { + border-color: #a2a2a2; +} + +#RevisionLine.obtainedDateLine { + background-color: #018d98; +} + +.obtainedRevision #RevisionLine { + background-color: #018d98; +} + +#RevisionIndex { + color: #018d98; +} + +#RevisionIndicator { + border-color: #018d98; +} + +.currentRevision #RevisionIndicator { + background-color: #018d98; +} + +.currentRevision #HistoryDetail { + border-color: #018d98; +} + +#StatusView > #StatusButton { + background-color: #018d98; + border-color: #018d98; +} diff --git a/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Unity.CollabProxy.Editor.asmdef b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Unity.CollabProxy.Editor.asmdef new file mode 100644 index 00000000..66511e1d --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Editor/Unity.CollabProxy.Editor.asmdef @@ -0,0 +1,7 @@ +{ + "name": "Unity.CollabProxy.Editor", + "includePlatforms": [ + "Editor" + ], + "excludePlatforms": [] +} diff --git a/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/LICENSE.md b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/LICENSE.md new file mode 100644 index 00000000..31bde4e4 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/LICENSE.md @@ -0,0 +1,31 @@ +**Unity Companion Package License v1.0 ("_License_")** + +Copyright © 2017 Unity Technologies ApS ("**_Unity_**") + +Unity hereby grants to you a worldwide, non-exclusive, no-charge, and royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, sublicense, and distribute the software that is made available with this License ("**_Software_**"), subject to the following terms and conditions: + +1. *Unity Companion Use Only*. Exercise of the license granted herein is limited to exercise for the creation, use, and/or distribution of applications, software, or other content pursuant to a valid Unity development engine software license ("**_Engine License_**"). That means while use of the Software is not limited to use in the software licensed under the Engine License, the Software may not be used for any purpose other than the creation, use, and/or distribution of Engine License-dependent applications, software, or other content. No other exercise of the license granted herein is permitted. + +1. *No Modification of Engine License*. Neither this License nor any exercise of the license granted herein modifies the Engine License in any way. + +1. *Ownership & Grant Back to You*. + + 3.1. You own your content. In this License, "derivative works" means derivatives of the Software itself--works derived only from the Software by you under this License (for example, modifying the code of the Software itself to improve its efficacy); “derivative works” of the Software do not include, for example, games, apps, or content that you create using the Software. You keep all right, title, and interest to your own content. + + 3.2. Unity owns its content. While you keep all right, title, and interest to your own content per the above, as between Unity and you, Unity will own all right, title, and interest to all intellectual property rights (including patent, trademark, and copyright) in the Software and derivative works of the Software, and you hereby assign and agree to assign all such rights in those derivative works to Unity. + + 3.3. You have a license to those derivative works. Subject to this License, Unity grants to you the same worldwide, non-exclusive, no-charge, and royalty-free copyright license to derivative works of the Software you create as is granted to you for the Software under this License. + +1. *Trademarks*. You are not granted any right or license under this License to use any trademarks, service marks, trade names, products names, or branding of Unity or its affiliates ("**_Trademarks_**"). Descriptive uses of Trademarks are permitted; see, for example, Unity’s Branding Usage Guidelines at [https://unity3d.com/public-relations/brand](https://unity3d.com/public-relations/brand). + +1. *Notices & Third-Party Rights*. This License, including the copyright notice above, must be provided in all substantial portions of the Software and derivative works thereof (or, if that is impracticable, in any other location where such notices are customarily placed). Further, if the Software is accompanied by a Unity "third-party notices" or similar file, you acknowledge and agree that software identified in that file is governed by those separate license terms. + +1. *DISCLAIMER, LIMITATION OF LIABILITY*. THE SOFTWARE AND ANY DERIVATIVE WORKS THEREOF IS PROVIDED ON AN "AS IS" BASIS, AND IS PROVIDED WITHOUT WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND/OR NONINFRINGEMENT. IN NO EVENT SHALL ANY COPYRIGHT HOLDER OR AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES (WHETHER DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL, INCLUDING PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, LOSS OF USE, DATA, OR PROFITS, AND BUSINESS INTERRUPTION), OR OTHER LIABILITY WHATSOEVER, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE, ARISING FROM OR OUT OF, OR IN CONNECTION WITH, THE SOFTWARE OR ANY DERIVATIVE WORKS THEREOF OR THE USE OF OR OTHER DEALINGS IN SAME, EVEN WHERE ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +1. *USE IS ACCEPTANCE and License Versions*. Your receipt and use of the Software constitutes your acceptance of this License and its terms and conditions. Software released by Unity under this License may be modified or updated and the License with it; upon any such modification or update, you will comply with the terms of the updated License for any use of any of the Software under the updated License. + +1. *Use in Compliance with Law and Termination*. Your exercise of the license granted herein will at all times be in compliance with applicable law and will not infringe any proprietary rights (including intellectual property rights); this License will terminate immediately on any breach by you of this License. + +1. *Severability*. If any provision of this License is held to be unenforceable or invalid, that provision will be enforced to the maximum extent possible and the other provisions will remain in full force and effect. + +1. *Governing Law and Venue*. This License is governed by and construed in accordance with the laws of Denmark, except for its conflict of laws rules; the United Nations Convention on Contracts for the International Sale of Goods will not apply. If you reside (or your principal place of business is) within the United States, you and Unity agree to submit to the personal and exclusive jurisdiction of and venue in the state and federal courts located in San Francisco County, California concerning any dispute arising out of this License ("**_Dispute_**"). If you reside (or your principal place of business is) outside the United States, you and Unity agree to submit to the personal and exclusive jurisdiction of and venue in the courts located in Copenhagen, Denmark concerning any Dispute. diff --git a/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/README.md b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/README.md new file mode 100644 index 00000000..5cfbd88a --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/README.md @@ -0,0 +1,16 @@ +# Collab Proxy UPM Package +This is the packaged version of Collab, currently limited to containing the History and Toolbar windows, along with supporting classes. + +## Development +Check this repository out in your {$PROJECT}/Packages/ folder, under the name com.unity.collab-proxy. The classes will be built by Unity. + +## Testing +In order to run the tests, you will need to add this project to the testables key in your manifest.json - once you have done this, the tests will be picked up by the Unity Test Runner window. + +## Building +You may build this project using msbuild. The commands to do so can be seen under .gitlab-ci.yml. + +## Deploying +Gitlab will automatically build your project when you deploy. You can download the resulting artifact, which will be a dll, and place it in your Editor/bin/ folder. Open the package in Unity to generate the meta files, and then you will be able to publish. + +We're currently looking into a way to avoid this manual process. diff --git a/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Tests/Editor/HistoryTests.cs b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Tests/Editor/HistoryTests.cs new file mode 100644 index 00000000..ba79a204 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Tests/Editor/HistoryTests.cs @@ -0,0 +1,583 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +using UnityEditor.Collaboration; +using UnityEngine.TestTools; +using NUnit.Framework; + +namespace UnityEditor.Collaboration.Tests +{ + [TestFixture] + internal class HistoryTests + { + private TestHistoryWindow _window; + private TestRevisionsService _service; + private CollabHistoryPresenter _presenter; + + [SetUp] + public void SetUp() + { + _window = new TestHistoryWindow(); + _service = new TestRevisionsService(); + _presenter = new CollabHistoryPresenter(_window, new CollabHistoryItemFactory(), _service); + } + + [TearDown] + public void TearDown() + { + } + + [Test] + public void CollabHistoryPresenter_OnUpdatePage__PropagatesRevisionResult() + { + _service.result = new RevisionsResult() + { + Revisions = new List() + { + new Revision(authorName: "authorName", comment: "comment", revisionID: "revisionID"), + } + }; + + _presenter.OnUpdatePage(0); + var item = _window.items.First(); + + Assert.AreEqual("revisionID", item.id); + Assert.AreEqual("authorName", item.authorName); + Assert.AreEqual("comment", item.comment); + } + + [Test] + public void CollabHistoryPresenter_OnUpdatePage__RevisionNumberingIsInOrder() + { + _service.result = new RevisionsResult() + { + RevisionsInRepo = 4, + Revisions = new List() + { + new Revision(revisionID: "0"), + new Revision(revisionID: "1"), + new Revision(revisionID: "2"), + new Revision(revisionID: "3"), + } + }; + + _presenter.OnUpdatePage(0); + var items = _window.items.ToArray(); + + Assert.AreEqual(4, items[0].index); + Assert.AreEqual(3, items[1].index); + Assert.AreEqual(2, items[2].index); + Assert.AreEqual(1, items[3].index); + } + + [Test] + public void CollabHistoryPresenter_OnUpdatePage__RevisionNumberingChangesForMorePages() + { + _service.result = new RevisionsResult() + { + RevisionsInRepo = 12, + Revisions = new List() + { + new Revision(revisionID: "0"), + new Revision(revisionID: "1"), + new Revision(revisionID: "2"), + new Revision(revisionID: "3"), + new Revision(revisionID: "4"), + } + }; + + _presenter.OnUpdatePage(1); + var items = _window.items.ToArray(); + + Assert.AreEqual(12, items[0].index); + Assert.AreEqual(11, items[1].index); + Assert.AreEqual(10, items[2].index); + Assert.AreEqual(9, items[3].index); + Assert.AreEqual(8, items[4].index); + } + + [Test] + public void CollabHistoryPresenter_OnUpdatePage__ObtainedIsCalculated() + { + _service.result = new RevisionsResult() + { + Revisions = new List() + { + new Revision(isObtained: false), + new Revision(isObtained: true), + } + }; + + _presenter.OnUpdatePage(0); + var items = _window.items.ToArray(); + + Assert.IsFalse(items[0].obtained); + Assert.IsTrue(items[1].obtained); + } + + [Test] + public void CollabHistoryPresenter_OnUpdatePage__CurrentIsCalculated() + { + _service.result = new RevisionsResult() + { + Revisions = new List() + { + new Revision(revisionID: "1"), + new Revision(revisionID: "2"), + new Revision(revisionID: "3"), + } + }; + _service.tipRevision = "2"; + + _presenter.OnUpdatePage(0); + var items = _window.items.ToArray(); + + Assert.AreEqual(false, items[0].current); + Assert.AreEqual(true, items[1].current); + Assert.AreEqual(false, items[2].current); + } + + [Test] + public void CollabHistoryPresenter_OnUpdatePage__InProgressIsCalculated() + { + _service.result = new RevisionsResult() + { + Revisions = new List() + { + new Revision(revisionID: "1"), + new Revision(revisionID: "2"), + new Revision(revisionID: "3"), + } + }; + _window.inProgressRevision = "2"; + + _presenter.OnUpdatePage(0); + var items = _window.items.ToArray(); + + Assert.IsFalse(items[0].inProgress); + Assert.IsTrue(items[1].inProgress); + Assert.IsFalse(items[2].inProgress); + } + + [Test] + public void CollabHistoryPresenter_OnUpdatePage__EnabledIsCalculated() + { + _service.result = new RevisionsResult() + { + Revisions = new List() + { + new Revision(revisionID: "0"), + } + }; + _window.revisionActionsEnabled = true; + + _presenter.OnUpdatePage(0); + var item = _window.items.First(); + + Assert.AreEqual(true, item.enabled); + } + + [Test] + public void CollabHistoryPresenter_OnUpdatePage__DisabledIsCalculated() + { + _service.result = new RevisionsResult() + { + Revisions = new List() + { + new Revision(revisionID: "0"), + } + }; + _window.revisionActionsEnabled = false; + + _presenter.OnUpdatePage(0); + var item = _window.items.First(); + + Assert.AreEqual(false, item.enabled); + } + + [Test] + public void CollabHistoryPresenter_OnUpdatePage__BuildStateHasNoneWhenNotTip() + { + _service.result = new RevisionsResult() + { + Revisions = new List() + { + new Revision(revisionID: "1"), + } + }; + _service.tipRevision = "0"; + _presenter.BuildServiceEnabled = false; + + _presenter.OnUpdatePage(0); + var item = _window.items.First(); + + Assert.AreEqual(BuildState.None, item.buildState); + } + + [Test] + public void CollabHistoryPresenter_OnUpdatePage__BuildStateTipHasNoneWhenEnabled() + { + _service.result = new RevisionsResult() + { + Revisions = new List() + { + new Revision(revisionID: "0"), + } + }; + _service.tipRevision = "0"; + _presenter.BuildServiceEnabled = true; + + _presenter.OnUpdatePage(0); + var item = _window.items.First(); + + Assert.AreEqual(BuildState.None, item.buildState); + } + + [Test] + public void CollabHistoryPresenter_OnUpdatePage__BuildStateHasConfigureWhenTip() + { + _service.result = new RevisionsResult() + { + Revisions = new List() + { + new Revision(revisionID: "0"), + } + }; + _service.tipRevision = "0"; + _presenter.BuildServiceEnabled = false; + + _presenter.OnUpdatePage(0); + var item = _window.items.First(); + + Assert.AreEqual(BuildState.Configure, item.buildState); + } + + [Test] + public void CollabHistoryPresenter_OnUpdatePage__BuildStateHasConfigureWhenZeroBuildStatus() + { + _service.result = new RevisionsResult() + { + Revisions = new List() + { + new Revision(revisionID: "0"), + } + }; + _service.tipRevision = "0"; + _presenter.BuildServiceEnabled = false; + + _presenter.OnUpdatePage(0); + var item = _window.items.First(); + + Assert.AreEqual(BuildState.Configure, item.buildState); + } + + [Test] + public void CollabHistoryPresenter_OnUpdatePage__BuildStateHasNoneWhenZeroBuildStatuses() + { + _service.result = new RevisionsResult() + { + Revisions = new List() + { + new Revision(revisionID: "0"), + } + }; + _service.tipRevision = "0"; + _presenter.BuildServiceEnabled = true; + + _presenter.OnUpdatePage(0); + var item = _window.items.First(); + + Assert.AreEqual(BuildState.None, item.buildState); + } + + [Test] + public void CollabHistoryPresenter_OnUpdatePage__BuildStateHasSuccessWhenCompleteAndSucceeded() + { + _service.result = new RevisionsResult() + { + Revisions = new List() + { + new Revision + ( + revisionID: "0", + buildStatuses: new CloudBuildStatus[1] + { + new CloudBuildStatus(complete: true, success: true), + } + ), + } + }; + _service.tipRevision = "0"; + _presenter.BuildServiceEnabled = true; + + _presenter.OnUpdatePage(0); + var item = _window.items.First(); + + Assert.AreEqual(BuildState.Success, item.buildState); + } + + [Test] + public void CollabHistoryPresenter_OnUpdatePage__BuildStateHasInProgress() + { + _service.result = new RevisionsResult() + { + Revisions = new List() + { + new Revision + ( + revisionID: "0", + buildStatuses: new CloudBuildStatus[1] + { + new CloudBuildStatus(complete: false), + } + ), + } + }; + _service.tipRevision = "0"; + _presenter.BuildServiceEnabled = true; + + _presenter.OnUpdatePage(0); + var item = _window.items.First(); + + Assert.AreEqual(BuildState.InProgress, item.buildState); + } + + [Test] + public void CollabHistoryPresenter_OnUpdatePage__BuildStateHasFailure() + { + _service.result = new RevisionsResult() + { + Revisions = new List() + { + new Revision + ( + revisionID: "0", + buildStatuses: new CloudBuildStatus[1] + { + new CloudBuildStatus(complete: true, success: false), + } + ), + } + }; + _service.tipRevision = "0"; + _presenter.BuildServiceEnabled = true; + + _presenter.OnUpdatePage(0); + var item = _window.items.First(); + + Assert.AreEqual(BuildState.Failed, item.buildState); + } + + [Test] + public void CollabHistoryPresenter_OnUpdatePage__BuildStateHasFailureWhenAnyBuildsFail() + { + _service.result = new RevisionsResult() + { + Revisions = new List() + { + new Revision + ( + revisionID: "0", + buildStatuses: new CloudBuildStatus[3] + { + new CloudBuildStatus(complete: true, success: false), + new CloudBuildStatus(complete: true, success: false), + new CloudBuildStatus(complete: true, success: true), + } + ), + } + }; + _service.tipRevision = "0"; + _presenter.BuildServiceEnabled = true; + + _presenter.OnUpdatePage(0); + var item = _window.items.First(); + + Assert.AreEqual(BuildState.Failed, item.buildState); + } + + [Test] + public void CollabHistoryPresenter_OnUpdatePage__ChangesPropagateThrough() + { + _service.result = new RevisionsResult() + { + Revisions = new List() + { + new Revision(revisionID: "0", entries: GenerateChangeActions(3)), + } + }; + + _presenter.OnUpdatePage(0); + var item = _window.items.First(); + var changes = item.changes.ToList(); + + Assert.AreEqual("Path0", changes[0].path); + Assert.AreEqual("Path1", changes[1].path); + Assert.AreEqual("Path2", changes[2].path); + } + + [Test] + public void CollabHistoryPresenter_OnUpdatePage__ChangesTotalIsCalculated() + { + _service.result = new RevisionsResult() + { + Revisions = new List() + { + new Revision(revisionID: "0", entries: GenerateChangeActions(3)), + } + }; + + _presenter.OnUpdatePage(0); + var item = _window.items.First(); + + Assert.AreEqual(3, item.changes.Count); + } + + [Test] + public void CollabHistoryPresenter_OnUpdatePage__ChangesTruncatedIsCalculated() + { + for (var i = 0; i < 20; i++) + { + _service.result = new RevisionsResult() + { + Revisions = new List() + { + new Revision(revisionID: "0", entries: GenerateChangeActions(i)), + } + }; + + _presenter.OnUpdatePage(0); + var item = _window.items.First(); + + Assert.AreEqual(i > 10, item.changesTruncated); + } + } + + [Test] + public void CollabHistoryPresenter_OnUpdatePage__OnlyKeeps10ChangeActions() + { + _service.result = new RevisionsResult() + { + Revisions = new List() + { + new Revision(authorName: "Test", author: "test", entries: GenerateChangeActions(12)), + } + }; + + _presenter.OnUpdatePage(1); + var item = _window.items.First(); + + Assert.AreEqual(10, item.changes.Count); + Assert.AreEqual(12, item.changesTotal); + Assert.AreEqual(true, item.changesTruncated); + } + + [Test] + public void CollabHistoryPresenter_OnUpdatePage__DeduplicatesMetaFiles() + { + _service.result = new RevisionsResult() + { + Revisions = new List() + { + new Revision + ( + authorName: "Test", + author: "test", + revisionID: "", + entries: new ChangeAction[2] + { + new ChangeAction(path: "Path1", action: "Action1"), + new ChangeAction(path: "Path1.meta", action: "Action1"), + } + ), + } + }; + + _presenter.OnUpdatePage(1); + var item = _window.items.First(); + + Assert.AreEqual(1, item.changes.Count); + Assert.AreEqual(1, item.changesTotal); + Assert.AreEqual("Path1", item.changes.First().path); + } + + [Test] + public void CollabHistoryPresenter_OnUpdatePage__FolderMetaFilesAreCounted() + { + _service.result = new RevisionsResult() + { + Revisions = new List() + { + new Revision + ( + authorName: "Test", + author: "test", + entries: new ChangeAction[1] + { + new ChangeAction(path: "Folder1.meta", action: "Action1"), + } + ), + } + }; + + _presenter.OnUpdatePage(1); + var item = _window.items.First(); + + Assert.AreEqual(1, item.changes.Count); + Assert.AreEqual(1, item.changesTotal); + Assert.AreEqual("Folder1", item.changes.First().path); + } + + private static ChangeAction[] GenerateChangeActions(int count) + { + var entries = new ChangeAction[count]; + for (var i = 0; i < count; i++) + entries[i] = new ChangeAction(path: "Path" + i, action: "Action" + i); + return entries; + } + } + + internal class TestRevisionsService : IRevisionsService + { + public RevisionsResult result; + public event RevisionsDelegate FetchRevisionsCallback; + + public string tipRevision { get; set; } + public string currentUser { get; set; } + + public void GetRevisions(int offset, int count) + { + if(FetchRevisionsCallback != null) + { + FetchRevisionsCallback(result); + } + } + } + + internal class TestHistoryWindow : ICollabHistoryWindow + { + public IEnumerable items; + + public bool revisionActionsEnabled { get; set; } + public int itemsPerPage { get; set; } + public string errMessage { get; set; } + public string inProgressRevision { get; set; } + public PageChangeAction OnPageChangeAction { get; set; } + public RevisionAction OnGoBackAction { get; set; } + public RevisionAction OnUpdateAction { get; set; } + public RevisionAction OnRestoreAction { get; set; } + public ShowBuildAction OnShowBuildAction { get; set; } + public Action OnShowServicesAction { get; set; } + + public void UpdateState(HistoryState state, bool force) + { + } + + public void UpdateRevisions(IEnumerable items, string tip, int totalRevisions, int currPage) + { + this.items = items; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Tests/Editor/Unity.CollabProxy.EditorTests.asmdef b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Tests/Editor/Unity.CollabProxy.EditorTests.asmdef new file mode 100644 index 00000000..3467a9ed --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/Tests/Editor/Unity.CollabProxy.EditorTests.asmdef @@ -0,0 +1,13 @@ +{ + "name": "Unity.CollabProxy.EditorTests", + "references": [ + "Unity.CollabProxy.Editor" + ], + "optionalUnityReferences": [ + "TestAssemblies" + ], + "includePlatforms": [ + "Editor" + ], + "excludePlatforms": [] +} diff --git a/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/package.json b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/package.json new file mode 100644 index 00000000..34022740 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.collab-proxy@1.2.16/package.json @@ -0,0 +1,21 @@ +{ + "name": "com.unity.collab-proxy", + "displayName": "Unity Collaborate", + "version": "1.2.16", + "unity": "2018.3", + "description": "Collaborate is a simple way for teams to save, share, and sync their Unity project", + "keywords": [ + "collab", + "collaborate", + "teams", + "team", + "cloud", + "backup" + ], + "dependencies": {}, + "repository": { + "type": "git", + "url": "https://gitlab.cds.internal.unity3d.com/upm-packages/cloud-services/collab-proxy.git", + "revision": "070e173b6a36e1d6097b1d95e09c08840c23f6ca" + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.ext.nunit@1.0.0/.gitlab-ci.yml b/KerbalVR/Library/PackageCache/com.unity.ext.nunit@1.0.0/.gitlab-ci.yml new file mode 100644 index 00000000..4c64e220 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ext.nunit@1.0.0/.gitlab-ci.yml @@ -0,0 +1,15 @@ +image: node:6.10.0 + +stages: + - push_to_packman_staging + +push_to_packman_staging: + stage: push_to_packman_staging + only: + - tags + script: + - sed -i "s/0.0.1-PLACEHOLDERVERSION/$CI_COMMIT_TAG/g" package.json + - sed -i "s/PLACEHOLDERSHA/$CI_COMMIT_SHA/g" package.json + - sed -i "s/0.0.1-PLACEHOLDERVERSION/$CI_COMMIT_TAG/g" CHANGELOG.md + - curl -u $USER_NAME:$API_KEY https://staging-packages.unity.com/auth > .npmrc + - npm publish diff --git a/KerbalVR/Library/PackageCache/com.unity.ext.nunit@1.0.0/CHANGELOG.md b/KerbalVR/Library/PackageCache/com.unity.ext.nunit@1.0.0/CHANGELOG.md new file mode 100644 index 00000000..225baeaa --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ext.nunit@1.0.0/CHANGELOG.md @@ -0,0 +1,11 @@ +# Changelog +All notable changes to this package will be documented in this file. + +The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). + +## [1.0.0] - 2019-02-21 + +### This is the first release of *Unity Package com.unity.ext.nunit*. + +- Migrated the custom version of nunit from inside of unity. diff --git a/KerbalVR/Library/PackageCache/com.unity.ext.nunit@1.0.0/LICENSE.md b/KerbalVR/Library/PackageCache/com.unity.ext.nunit@1.0.0/LICENSE.md new file mode 100644 index 00000000..ccc1f59c --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ext.nunit@1.0.0/LICENSE.md @@ -0,0 +1,19 @@ +Copyright (c) 2018 Charlie Poole, Rob Prouse + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.ext.nunit@1.0.0/README.md b/KerbalVR/Library/PackageCache/com.unity.ext.nunit@1.0.0/README.md new file mode 100644 index 00000000..2a38b9d8 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ext.nunit@1.0.0/README.md @@ -0,0 +1,6 @@ +# Custom Nunit build to work with Unity + +This version of nunit works with all platforms, il2cpp and Mono AOT. + +For Nunit Documentation: +https://github.com/nunit/docs/wiki/NUnit-Documentation diff --git a/KerbalVR/Library/PackageCache/com.unity.ext.nunit@1.0.0/net35/unity-custom/This is a custom build DONT include.txt b/KerbalVR/Library/PackageCache/com.unity.ext.nunit@1.0.0/net35/unity-custom/This is a custom build DONT include.txt new file mode 100644 index 00000000..0839eb99 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ext.nunit@1.0.0/net35/unity-custom/This is a custom build DONT include.txt @@ -0,0 +1,4 @@ +This is a custom nUnit build meant to be used by Unity editor and players. It shoul not be included or referenced from anywhere (unless you know what you're doing) + +Build from this repo +https://github.com/Unity-Technologies/nunit \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.ext.nunit@1.0.0/net35/unity-custom/nunit.framework.dll b/KerbalVR/Library/PackageCache/com.unity.ext.nunit@1.0.0/net35/unity-custom/nunit.framework.dll new file mode 100644 index 00000000..3af863c6 Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.ext.nunit@1.0.0/net35/unity-custom/nunit.framework.dll differ diff --git a/KerbalVR/Library/PackageCache/com.unity.ext.nunit@1.0.0/net35/unity-custom/nunit.framework.dll.mdb b/KerbalVR/Library/PackageCache/com.unity.ext.nunit@1.0.0/net35/unity-custom/nunit.framework.dll.mdb new file mode 100644 index 00000000..cb688df0 Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.ext.nunit@1.0.0/net35/unity-custom/nunit.framework.dll.mdb differ diff --git a/KerbalVR/Library/PackageCache/com.unity.ext.nunit@1.0.0/net35/unity-custom/nunit.framework.xml b/KerbalVR/Library/PackageCache/com.unity.ext.nunit@1.0.0/net35/unity-custom/nunit.framework.xml new file mode 100644 index 00000000..aea20992 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ext.nunit@1.0.0/net35/unity-custom/nunit.framework.xml @@ -0,0 +1,18101 @@ + + + + nunit.framework + + + + + Basic Asserts on strings. + + + + + The Equals method throws an InvalidOperationException. This is done + to make sure there is no mistake by calling this function. + + + + + + + override the default ReferenceEquals to throw an InvalidOperationException. This + implementation makes sure there is no mistake in calling this function + as part of Assert. + + + + + + + Asserts that a string is found within another string. + + The expected string + The string to be examined + The message to display in case of failure + Arguments used in formatting the message + + + + Asserts that a string is found within another string. + + The expected string + The string to be examined + + + + Asserts that a string is not found within another string. + + The expected string + The string to be examined + The message to display in case of failure + Arguments used in formatting the message + + + + Asserts that a string is found within another string. + + The expected string + The string to be examined + + + + Asserts that a string starts with another string. + + The expected string + The string to be examined + The message to display in case of failure + Arguments used in formatting the message + + + + Asserts that a string starts with another string. + + The expected string + The string to be examined + + + + Asserts that a string does not start with another string. + + The expected string + The string to be examined + The message to display in case of failure + Arguments used in formatting the message + + + + Asserts that a string does not start with another string. + + The expected string + The string to be examined + + + + Asserts that a string ends with another string. + + The expected string + The string to be examined + The message to display in case of failure + Arguments used in formatting the message + + + + Asserts that a string ends with another string. + + The expected string + The string to be examined + + + + Asserts that a string does not end with another string. + + The expected string + The string to be examined + The message to display in case of failure + Arguments used in formatting the message + + + + Asserts that a string does not end with another string. + + The expected string + The string to be examined + + + + Asserts that two strings are equal, without regard to case. + + The expected string + The actual string + The message to display in case of failure + Arguments used in formatting the message + + + + Asserts that two strings are equal, without regard to case. + + The expected string + The actual string + + + + Asserts that two strings are not equal, without regard to case. + + The expected string + The actual string + The message to display in case of failure + Arguments used in formatting the message + + + + Asserts that two strings are not equal, without regard to case. + + The expected string + The actual string + + + + Asserts that a string matches an expected regular expression pattern. + + The regex pattern to be matched + The actual string + The message to display in case of failure + Arguments used in formatting the message + + + + Asserts that a string matches an expected regular expression pattern. + + The regex pattern to be matched + The actual string + + + + Asserts that a string does not match an expected regular expression pattern. + + The regex pattern to be used + The actual string + The message to display in case of failure + Arguments used in formatting the message + + + + Asserts that a string does not match an expected regular expression pattern. + + The regex pattern to be used + The actual string + + + + Combines multiple filters so that a test must pass all + of them in order to pass this filter. + + + + + A base class for multi-part filters + + + + + Interface to be implemented by filters applied to tests. + The filter applies when running the test, after it has been + loaded, since this is the only time an ITest exists. + + + + + Interface to be implemented by filters applied to tests. + The filter applies when running the test, after it has been + loaded, since this is the only time an ITest exists. + + + + + An object implementing IXmlNodeBuilder is able to build + an XML representation of itself and any children. + + + + + Returns a TNode representing the current object. + + If true, children are included where applicable + A TNode representing the result + + + + Returns a TNode representing the current object after + adding it as a child of the supplied parent node. + + The parent node. + If true, children are included, where applicable + + + + + Determine if a particular test passes the filter criteria. Pass + may examine the parents and/or descendants of a test, depending + on the semantics of the particular filter + + The test to which the filter is applied + True if the test passes the filter, otherwise false + + + + Determine if a test matches the filter expicitly. That is, it must + be a direct match of the test itself or one of it's children. + + The test to which the filter is applied + True if the test matches the filter explicityly, otherwise false + + + + Unique Empty filter. + + + + + Determine if a particular test passes the filter criteria. The default + implementation checks the test itself, its parents and any descendants. + + Derived classes may override this method or any of the Match methods + to change the behavior of the filter. + + The test to which the filter is applied + True if the test passes the filter, otherwise false + + + + Determine if a test matches the filter expicitly. That is, it must + be a direct match of the test itself or one of it's children. + + The test to which the filter is applied + True if the test matches the filter explicityly, otherwise false + + + + Determine whether the test itself matches the filter criteria, without + examining either parents or descendants. This is overridden by each + different type of filter to perform the necessary tests. + + The test to which the filter is applied + True if the filter matches the any parent of the test + + + + Determine whether any ancestor of the test matches the filter criteria + + The test to which the filter is applied + True if the filter matches the an ancestor of the test + + + + Determine whether any descendant of the test matches the filter criteria. + + The test to be matched + True if at least one descendant matches the filter criteria + + + + Create a TestFilter instance from an xml representation. + + + + + Create a TestFilter from it's TNode representation + + + + + Adds an XML node + + True if recursive + The added XML node + + + + Adds an XML node + + Parent node + True if recursive + The added XML node + + + + Indicates whether this is the EmptyFilter + + + + + Indicates whether this is a top-level filter, + not contained in any other filter. + + + + + Nested class provides an empty filter - one that always + returns true when called. It never matches explicitly. + + + + + Constructs an empty CompositeFilter + + + + + Constructs a CompositeFilter from an array of filters + + + + + + Adds a filter to the list of filters + + The filter to be added + + + + Checks whether the CompositeFilter is matched by a test. + + The test to be matched + + + + Checks whether the CompositeFilter is matched by a test. + + The test to be matched + + + + Checks whether the CompositeFilter is explicit matched by a test. + + The test to be matched + + + + Adds an XML node + + Parent node + True if recursive + The added XML node + + + + Return a list of the composing filters. + + + + + Gets the element name + + Element name + + + + Constructs an empty AndFilter + + + + + Constructs an AndFilter from an array of filters + + + + + + Checks whether the AndFilter is matched by a test + + The test to be matched + True if all the component filters pass, otherwise false + + + + Checks whether the AndFilter is matched by a test + + The test to be matched + True if all the component filters match, otherwise false + + + + Checks whether the AndFilter is explicit matched by a test. + + The test to be matched + True if all the component filters explicit match, otherwise false + + + + Gets the element name + + Element name + + + + SubstringConstraint can test whether a string contains + the expected substring. + + + + + StringConstraint is the abstract base for constraints + that operate on strings. It supports the IgnoreCase + modifier for string operations. + + + + + The Constraint class is the base of all built-in constraints + within NUnit. It provides the operator overloads used to combine + constraints. + + + + + Interface for all constraints + + + + + The IResolveConstraint interface is implemented by all + complete and resolvable constraints and expressions. + + + + + Return the top-level constraint for this expression + + + + + + Applies the constraint to an actual value, returning a ConstraintResult. + + The value to be tested + A ConstraintResult + + + + Applies the constraint to an ActualValueDelegate that returns + the value to be tested. The default implementation simply evaluates + the delegate but derived classes may override it to provide for + delayed processing. + + An ActualValueDelegate + A ConstraintResult + + + + Test whether the constraint is satisfied by a given reference. + The default implementation simply dereferences the value but + derived classes may override it to provide for delayed processing. + + A reference to the value to be tested + A ConstraintResult + + + + The display name of this Constraint for use by ToString(). + + + + + The Description of what this constraint tests, for + use in messages and in the ConstraintResult. + + + + + Arguments provided to this Constraint, for use in + formatting the description. + + + + + The ConstraintBuilder holding this constraint + + + + + Construct a constraint with optional arguments + + Arguments to be saved + + + + Applies the constraint to an actual value, returning a ConstraintResult. + + The value to be tested + A ConstraintResult + + + + Applies the constraint to an ActualValueDelegate that returns + the value to be tested. The default implementation simply evaluates + the delegate but derived classes may override it to provide for + delayed processing. + + An ActualValueDelegate + A ConstraintResult + + + + Test whether the constraint is satisfied by a given reference. + The default implementation simply dereferences the value but + derived classes may override it to provide for delayed processing. + + A reference to the value to be tested + A ConstraintResult + + + + Retrieves the value to be tested from an ActualValueDelegate. + The default implementation simply evaluates the delegate but derived + classes may override it to provide for delayed processing. + + An ActualValueDelegate + Delegate evaluation result + + + + Default override of ToString returns the constraint DisplayName + followed by any arguments within angle brackets. + + + + + + Returns the string representation of this constraint + + + + + This operator creates a constraint that is satisfied only if both + argument constraints are satisfied. + + + + + This operator creates a constraint that is satisfied if either + of the argument constraints is satisfied. + + + + + This operator creates a constraint that is satisfied if the + argument constraint is not satisfied. + + + + + Returns a DelayedConstraint with the specified delay time. + + The delay in milliseconds. + + + + + Returns a DelayedConstraint with the specified delay time + and polling interval. + + The delay in milliseconds. + The interval at which to test the constraint. + + + + + Resolves any pending operators and returns the resolved constraint. + + + + + The display name of this Constraint for use by ToString(). + The default value is the name of the constraint with + trailing "Constraint" removed. Derived classes may set + this to another name in their constructors. + + + + + The Description of what this constraint tests, for + use in messages and in the ConstraintResult. + + + + + Arguments provided to this Constraint, for use in + formatting the description. + + + + + The ConstraintBuilder holding this constraint + + + + + Returns a ConstraintExpression by appending And + to the current constraint. + + + + + Returns a ConstraintExpression by appending And + to the current constraint. + + + + + Returns a ConstraintExpression by appending Or + to the current constraint. + + + + + The expected value + + + + + Indicates whether tests should be case-insensitive + + + + + Description of this constraint + + + + + Constructs a StringConstraint without an expected value + + + + + Constructs a StringConstraint given an expected value + + The expected value + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for success, false for failure + + + + Test whether the constraint is satisfied by a given string + + The string to be tested + True for success, false for failure + + + + The Description of what this constraint tests, for + use in messages and in the ConstraintResult. + + + + + Modify the constraint to ignore case in matching. + + + + + Initializes a new instance of the class. + + The expected. + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for success, false for failure + + + + Abstract base class used for prefixes + + + + + Construct given a base constraint + + + + + + The base constraint + + + + + Prefix used in forming the constraint description + + + + + The Description of what this constraint tests, for + use in messages and in the ConstraintResult. + + + + + AssignableToConstraint is used to test that an object + can be assigned to a given Type. + + + + + TypeConstraint is the abstract base for constraints + that take a Type as their expected value. + + + + + The expected Type used by the constraint + + + + + The type of the actual argument to which the constraint was applied + + + + + Construct a TypeConstraint for a given Type + + The expected type for the constraint + Prefix used in forming the constraint description + + + + Applies the constraint to an actual value, returning a ConstraintResult. + + The value to be tested + A ConstraintResult + + + + Apply the constraint to an actual value, returning true if it succeeds + + The actual argument + True if the constraint succeeds, otherwise false. + + + + Construct an AssignableToConstraint for the type provided + + + + + + Apply the constraint to an actual value, returning true if it succeeds + + The actual argument + True if the constraint succeeds, otherwise false. + + + + Summary description for MaxTimeAttribute. + + + + + PropertyAttribute is used to attach information to a test as a name/value pair.. + + + + + The abstract base class for all custom attributes defined by NUnit. + + + + + Default constructor + + + + + The IApplyToTest interface is implemented by self-applying + attributes that modify the state of a test in some way. + + + + + Modifies a test as defined for the specific attribute. + + The test to modify + + + + Construct a PropertyAttribute with a name and string value + + The name of the property + The property value + + + + Construct a PropertyAttribute with a name and int value + + The name of the property + The property value + + + + Construct a PropertyAttribute with a name and double value + + The name of the property + The property value + + + + Constructor for derived classes that set the + property dictionary directly. + + + + + Constructor for use by derived classes that use the + name of the type as the property name. Derived classes + must ensure that the Type of the property value is + a standard type supported by the BCL. Any custom + types will cause a serialization Exception when + in the client. + + + + + Modifies a test by adding properties to it. + + The test to modify + + + + Gets the property dictionary for this attribute + + + + + Objects implementing this interface are used to wrap + the entire test, including SetUp and TearDown. + + + + + ICommandWrapper is implemented by attributes and other + objects able to wrap a TestCommand with another command. + + + Attributes or other objects should implement one of the + derived interfaces, rather than this one, since they + indicate in which part of the command chain the wrapper + should be applied. + + + + + Wrap a command and return the result. + + The command to be wrapped + The wrapped command + + + + Construct a MaxTimeAttribute, given a time in milliseconds. + + The maximum elapsed time in milliseconds + + + + Randomizer returns a set of random _values in a repeatable + way, to allow re-running of tests if necessary. It extends + the .NET Random class, providing random values for a much + wider range of types. + + The class is used internally by the framework to generate + test case data and is also exposed for use by users through + the TestContext.Random property. + + + For consistency with the underlying Random Type, methods + returning a single value use the prefix "Next..." Those + without an argument return a non-negative value up to + the full positive range of the Type. Overloads are provided + for specifying a maximum or a range. Methods that return + arrays or strings use the prefix "Get..." to avoid + confusion with the single-value methods. + + + + + Default characters for random functions. + + Default characters are the English alphabet (uppercase & lowercase), arabic numerals, and underscore + + + + Get a Randomizer for a particular member, returning + one that has already been created if it exists. + This ensures that the same _values are generated + each time the tests are reloaded. + + + + + Get a randomizer for a particular parameter, returning + one that has already been created if it exists. + This ensures that the same values are generated + each time the tests are reloaded. + + + + + Create a new Randomizer using the next seed + available to ensure that each randomizer gives + a unique sequence of values. + + + + + + Default constructor + + + + + Construct based on seed value + + + + + + Returns a random unsigned int. + + + + + Returns a random unsigned int less than the specified maximum. + + + + + Returns a random unsigned int within a specified range. + + + + + Returns a non-negative random short. + + + + + Returns a non-negative random short less than the specified maximum. + + + + + Returns a non-negative random short within a specified range. + + + + + Returns a random unsigned short. + + + + + Returns a random unsigned short less than the specified maximum. + + + + + Returns a random unsigned short within a specified range. + + + + + Returns a random long. + + + + + Returns a random long less than the specified maximum. + + + + + Returns a non-negative random long within a specified range. + + + + + Returns a random ulong. + + + + + Returns a random ulong less than the specified maximum. + + + + + Returns a non-negative random long within a specified range. + + + + + Returns a random Byte + + + + + Returns a random Byte less than the specified maximum. + + + + + Returns a random Byte within a specified range + + + + + Returns a random SByte + + + + + Returns a random sbyte less than the specified maximum. + + + + + Returns a random sbyte within a specified range + + + + + Returns a random bool + + + + + Returns a random bool based on the probablility a true result + + + + + Returns a random double between 0.0 and the specified maximum. + + + + + Returns a random double within a specified range. + + + + + Returns a random float. + + + + + Returns a random float between 0.0 and the specified maximum. + + + + + Returns a random float within a specified range. + + + + + Returns a random enum value of the specified Type as an object. + + + + + Returns a random enum value of the specified Type. + + + + + Generate a random string based on the characters from the input string. + + desired length of output string. + string representing the set of characters from which to construct the resulting string + A random string of arbitrary length + + + + Generate a random string based on the characters from the input string. + + desired length of output string. + A random string of arbitrary length + Uses DefaultStringChars as the input character set + + + + Generate a random string based on the characters from the input string. + + A random string of the default length + Uses DefaultStringChars as the input character set + + + + Returns a random decimal. + + + + + Returns a random decimal between positive zero and the specified maximum. + + + + + Returns a random decimal within a specified range, which is not + permitted to exceed decimal.MaxVal in the current implementation. + + + A limitation of this implementation is that the range from min + to max must not exceed decimal.MaxVal. + + + + + Initial seed used to create randomizers for this run + + + + + The IFixtureBuilder interface is exposed by a class that knows how to + build a TestFixture from one or more Types. In general, it is exposed + by an attribute, but may be implemented in a helper class used by the + attribute in some cases. + + + + + Build one or more TestFixtures from type provided. At least one + non-null TestSuite must always be returned, since the method is + generally called because the user has marked the target class as + a fixture. If something prevents the fixture from being used, it + will be returned nonetheless, labelled as non-runnable. + + The type info of the fixture to be used. + A TestSuite object or one derived from TestSuite. + + + + The ITestBuilder interface is exposed by a class that knows how to + build one or more TestMethods from a MethodInfo. In general, it is exposed + by an attribute, which has additional information available to provide + the necessary test parameters to distinguish the test cases built. + + + + + Build one or more TestMethods from the provided MethodInfo. + + The method to be used as a test + The TestSuite to which the method will be added + A TestMethod object + + + + The IReflectionInfo interface is implemented by NUnit wrapper objects that perform reflection. + + + + + Returns an array of custom attributes of the specified type applied to this object + + + + + Returns a value indicating whether an attribute of the specified type is defined on this object. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Represents the result of running a test suite + + + + + The TestResult class represents the result of a test. + + + + + The ITestResult interface represents the result of a test. + + + + + Gets the ResultState of the test result, which + indicates the success or failure of the test. + + + + + Gets the name of the test result + + + + + Gets the full name of the test result + + + + + Gets the elapsed time for running the test in seconds + + + + + Gets or sets the time the test started running. + + + + + Gets or sets the time the test finished running. + + + + + Gets the message associated with a test + failure or with not running the test + + + + + Gets any stacktrace associated with an + error or failure. Not available in + the Compact Framework 1.0. + + + + + Gets the number of asserts executed + when running the test and all its children. + + + + + Gets the number of test cases that failed + when running the test and all its children. + + + + + Gets the number of test cases that passed + when running the test and all its children. + + + + + Gets the number of test cases that were skipped + when running the test and all its children. + + + + + Gets the number of test cases that were inconclusive + when running the test and all its children. + + + + + Indicates whether this result has any child results. + Accessing HasChildren should not force creation of the + Children collection in classes implementing this interface. + + + + + Gets the the collection of child results. + + + + + Gets the Test to which this result applies. + + + + + Gets any text output written to this result. + + + + + The minimum duration for tests + + + + + Error message for when child tests have errors + + + + + Error message for when child tests are ignored + + + + + Aggregate assertion count + + + + + Construct a test result given a Test + + The test to be used + + + + Returns the Xml representation of the result. + + If true, descendant results are included + An XmlNode representing the result + + + + Adds the XML representation of the result as a child of the + supplied parent node.. + + The parent node. + If true, descendant results are included + + + + + Set the result of the test + + The ResultState to use in the result + + + + Set the result of the test + + The ResultState to use in the result + A message associated with the result state + + + + Set the result of the test + + The ResultState to use in the result + A message associated with the result state + Stack trace giving the location of the command + + + + Set the test result based on the type of exception thrown + + The exception that was thrown + + + + Set the test result based on the type of exception thrown + + The exception that was thrown + THe FailureSite to use in the result + + + + RecordTearDownException appends the message and stacktrace + from an exception arising during teardown of the test + to any previously recorded information, so that any + earlier failure information is not lost. Note that + calling Assert.Ignore, Assert.Inconclusive, etc. during + teardown is treated as an error. If the current result + represents a suite, it may show a teardown error even + though all contained tests passed. + + The Exception to be recorded + + + + Adds a reason element to a node and returns it. + + The target node. + The new reason element. + + + + Adds a failure element to a node and returns it. + + The target node. + The new failure element. + + + + Gets the test with which this result is associated. + + + + + Gets the ResultState of the test result, which + indicates the success or failure of the test. + + + + + Gets the name of the test result + + + + + Gets the full name of the test result + + + + + Gets or sets the elapsed time for running the test in seconds + + + + + Gets or sets the time the test started running. + + + + + Gets or sets the time the test finished running. + + + + + Gets the message associated with a test + failure or with not running the test + + + + + Gets any stacktrace associated with an + error or failure. + + + + + Gets or sets the count of asserts executed + when running the test. + + + + + Gets the number of test cases that failed + when running the test and all its children. + + + + + Gets the number of test cases that passed + when running the test and all its children. + + + + + Gets the number of test cases that were skipped + when running the test and all its children. + + + + + Gets the number of test cases that were inconclusive + when running the test and all its children. + + + + + Indicates whether this result has any child results. + + + + + Gets the collection of child results. + + + + + Gets a TextWriter, which will write output to be included in the result. + + + + + Gets any text output written to this result. + + + + + Construct a TestSuiteResult base on a TestSuite + + The TestSuite to which the result applies + + + + Adds a child result to this result, setting this result's + ResultState to Failure if the child result failed. + + The result to be added + + + + Gets the number of test cases that failed + when running the test and all its children. + + + + + Gets the number of test cases that passed + when running the test and all its children. + + + + + Gets the number of test cases that were skipped + when running the test and all its children. + + + + + Gets the number of test cases that were inconclusive + when running the test and all its children. + + + + + Indicates whether this result has any child results. + + + + + Gets the collection of child results. + + + + + TestSuite represents a composite test, which contains other tests. + + + + + The Test abstract class represents a test within the framework. + + + + + Common interface supported by all representations + of a test. Only includes informational fields. + The Run method is specifically excluded to allow + for data-only representations of a test. + + + + + Gets the id of the test + + + + + Gets the name of the test + + + + + Gets the fully qualified name of the test + + + + + Gets the name of the class containing this test. Returns + null if the test is not associated with a class. + + + + + Gets the name of the method implementing this test. + Returns null if the test is not implemented as a method. + + + + + Gets the Type of the test fixture, if applicable, or + null if no fixture type is associated with this test. + + + + + Gets an IMethod for the method implementing this test. + Returns null if the test is not implemented as a method. + + + + + Gets the RunState of the test, indicating whether it can be run. + + + + + Count of the test cases ( 1 if this is a test case ) + + + + + Gets the properties of the test + + + + + Gets the parent test, if any. + + The parent test or null if none exists. + + + + Returns true if this is a test suite + + + + + Gets a bool indicating whether the current test + has any descendant tests. + + + + + Gets this test's child tests + + A list of child tests + + + + Gets a fixture object for running this test. + + + + + Static value to seed ids. It's started at 1000 so any + uninitialized ids will stand out. + + + + + The SetUp methods. + + + + + The teardown methods + + + + + Used to cache the declaring type for this MethodInfo + + + + + Method property backing field + + + + + Constructs a test given its name + + The name of the test + + + + Constructs a test given the path through the + test hierarchy to its parent and a name. + + The parent tests full name + The name of the test + + + + TODO: Documentation needed for constructor + + + + + + Construct a test from a MethodInfo + + + + + + Creates a TestResult for this test. + + A TestResult suitable for this type of test. + + + + Modify a newly constructed test by applying any of NUnit's common + attributes, based on a supplied ICustomAttributeProvider, which is + usually the reflection element from which the test was constructed, + but may not be in some instances. The attributes retrieved are + saved for use in subsequent operations. + + An object implementing ICustomAttributeProvider + + + + Add standard attributes and members to a test node. + + + + + + + Returns the Xml representation of the test + + If true, include child tests recursively + + + + + Returns an XmlNode representing the current result after + adding it as a child of the supplied parent node. + + The parent node. + If true, descendant results are included + + + + + Compares this test to another test for sorting purposes + + The other test + Value of -1, 0 or +1 depending on whether the current test is less than, equal to or greater than the other test + + + + Gets or sets the id of the test + + + + + + Gets or sets the name of the test + + + + + Gets or sets the fully qualified name of the test + + + + + + Gets the name of the class where this test was declared. + Returns null if the test is not associated with a class. + + + + + Gets the name of the method implementing this test. + Returns null if the test is not implemented as a method. + + + + + Gets the TypeInfo of the fixture used in running this test + or null if no fixture type is associated with it. + + + + + Gets a MethodInfo for the method implementing this test. + Returns null if the test is not implemented as a method. + + + + + Whether or not the test should be run + + + + + Gets the name used for the top-level element in the + XML representation of this test + + + + + Gets a string representing the type of test. Used as an attribute + value in the XML representation of a test and has no other + function in the framework. + + + + + Gets a count of test cases represented by + or contained under this test. + + + + + Gets the properties for this test + + + + + Returns true if this is a TestSuite + + + + + Gets a bool indicating whether the current test + has any descendant tests. + + + + + Gets the parent as a Test object. + Used by the core to set the parent. + + + + + Gets this test's child tests + + A list of child tests + + + + Gets or sets a fixture object for running this test. + + + + + Static prefix used for ids in this AppDomain. + Set by FrameworkController. + + + + + Gets or Sets the Int value representing the seed for the RandomGenerator + + + + + + Our collection of child tests + + + + + Initializes a new instance of the class. + + The name of the suite. + + + + Initializes a new instance of the class. + + Name of the parent suite. + The name of the suite. + + + + Initializes a new instance of the class. + + Type of the fixture. + + + + Initializes a new instance of the class. + + Type of the fixture. + + + + Sorts tests under this suite. + + + + + Adds a test to the suite. + + The test. + + + + Overridden to return a TestSuiteResult. + + A TestResult for this test. + + + + Returns an XmlNode representing the current result after + adding it as a child of the supplied parent node. + + The parent node. + If true, descendant results are included + + + + + Check that setup and teardown methods marked by certain attributes + meet NUnit's requirements and mark the tests not runnable otherwise. + + The attribute type to check for + + + + Gets this test's child tests + + The list of child tests + + + + Gets a count of test cases represented by + or contained under this test. + + + + + + The arguments to use in creating the fixture + + + + + Set to true to suppress sorting this suite's contents + + + + + Gets a bool indicating whether the current test + has any descendant tests. + + + + + Gets the name used for the top-level element in the + XML representation of this test + + + + + A PropertyBag represents a collection of name value pairs + that allows duplicate entries with the same key. Methods + are provided for adding a new pair as well as for setting + a key to a single value. All keys are strings but _values + may be of any type. Null _values are not permitted, since + a null entry represents the absence of the key. + + + + + A PropertyBag represents a collection of name/value pairs + that allows duplicate entries with the same key. Methods + are provided for adding a new pair as well as for setting + a key to a single value. All keys are strings but _values + may be of any type. Null _values are not permitted, since + a null entry represents the absence of the key. + + The entries in a PropertyBag are of two kinds: those that + take a single value and those that take multiple _values. + However, the PropertyBag has no knowledge of which entries + fall into each category and the distinction is entirely + up to the code using the PropertyBag. + + When working with multi-valued properties, client code + should use the Add method to add name/value pairs and + indexing to retrieve a list of all _values for a given + key. For example: + + bag.Add("Tag", "one"); + bag.Add("Tag", "two"); + Assert.That(bag["Tag"], + Is.EqualTo(new string[] { "one", "two" })); + + When working with single-valued propeties, client code + should use the Set method to set the value and Get to + retrieve the value. The GetSetting methods may also be + used to retrieve the value in a type-safe manner while + also providing default. For example: + + bag.Set("Priority", "low"); + bag.Set("Priority", "high"); // replaces value + Assert.That(bag.Get("Priority"), + Is.EqualTo("high")); + Assert.That(bag.GetSetting("Priority", "low"), + Is.EqualTo("high")); + + + + + Adds a key/value pair to the property bag + + The key + The value + + + + Sets the value for a key, removing any other + _values that are already in the property set. + + + + + + + Gets a single value for a key, using the first + one if multiple _values are present and returning + null if the value is not found. + + + + + Gets a flag indicating whether the specified key has + any entries in the property set. + + The key to be checked + True if their are _values present, otherwise false + + + + Gets or sets the list of _values for a particular key + + The key for which the _values are to be retrieved or set + + + + Gets a collection containing all the keys in the property set + + + + + Adds a key/value pair to the property set + + The key + The value + + + + Sets the value for a key, removing any other + _values that are already in the property set. + + + + + + + Gets a single value for a key, using the first + one if multiple _values are present and returning + null if the value is not found. + + + + + + + Gets a flag indicating whether the specified key has + any entries in the property set. + + The key to be checked + + True if their are _values present, otherwise false + + + + + Returns an XmlNode representating the current PropertyBag. + + Not used + An XmlNode representing the PropertyBag + + + + Returns an XmlNode representing the PropertyBag after + adding it as a child of the supplied parent node. + + The parent node. + Not used + + + + + Gets a collection containing all the keys in the property set + + + + + + Gets or sets the list of _values for a particular key + + + + + Thrown when an assertion failed. Here to preserve the inner + exception and hence its stack trace. + + + + + Initializes a new instance of the class. + + + + + Initializes a new instance of the class. + + The error message that explains + the reason for the exception + + + + Initializes a new instance of the class. + + The error message that explains + the reason for the exception + The exception that caused the + current exception + + + + Serialization Constructor + + + + + FullName filter selects tests based on their FullName + + + + + ValueMatchFilter selects tests based on some value, which + is expected to be contained in the test. + + + + + Construct a ValueMatchFilter for a single value. + + The value to be included. + + + + Match the input provided by the derived class + + The value to be matchedT + True for a match, false otherwise. + + + + Adds an XML node + + Parent node + True if recursive + The added XML node + + + + Returns the value matched by the filter - used for testing + + + + + Indicates whether the value is a regular expression + + + + + Gets the element name + + Element name + + + + Construct a FullNameFilter for a single name + + The name the filter will recognize. + + + + Match a test against a single value. + + + + + Gets the element name + + Element name + + + + NotFilter negates the operation of another filter + + + + + Construct a not filter on another filter + + The filter to be negated + + + + Determine if a particular test passes the filter criteria. The default + implementation checks the test itself, its parents and any descendants. + + Derived classes may override this method or any of the Match methods + to change the behavior of the filter. + + The test to which the filter is applied + True if the test passes the filter, otherwise false + + + + Check whether the filter matches a test + + The test to be matched + True if it matches, otherwise false + + + + Determine if a test matches the filter expicitly. That is, it must + be a direct match of the test itself or one of it's children. + + The test to which the filter is applied + True if the test matches the filter explicityly, otherwise false + + + + Adds an XML node + + Parent node + True if recursive + The added XML node + + + + Gets the base filter + + + + + SequentialStrategy creates test cases by using all of the + parameter data sources in parallel, substituting null + when any of them run out of data. + + + + + CombiningStrategy is the abstract base for classes that + know how to combine values provided for individual test + parameters to create a set of test cases. + + + + + Gets the test cases generated by the CombiningStrategy. + + The test cases. + + + + Gets the test cases generated by the CombiningStrategy. + + The test cases. + + + + NUnitTestFixtureBuilder is able to build a fixture given + a class marked with a TestFixtureAttribute or an unmarked + class containing test methods. In the first case, it is + called by the attribute and in the second directly by + NUnitSuiteBuilder. + + + + + Build a TestFixture from type provided. A non-null TestSuite + must always be returned, since the method is generally called + because the user has marked the target class as a fixture. + If something prevents the fixture from being used, it should + be returned nonetheless, labelled as non-runnable. + + An ITypeInfo for the fixture to be used. + A TestSuite object or one derived from TestSuite. + + + + Overload of BuildFrom called by tests that have arguments. + Builds a fixture using the provided type and information + in the ITestFixtureData object. + + The TypeInfo for which to construct a fixture. + An object implementing ITestFixtureData or null. + + + + + Method to add test cases to the newly constructed fixture. + + The fixture to which cases should be added + + + + Method to create a test case from a MethodInfo and add + it to the fixture being built. It first checks to see if + any global TestCaseBuilder addin wants to build the + test case. If not, it uses the internal builder + collection maintained by this fixture builder. + + The default implementation has no test case builders. + Derived classes should add builders to the collection + in their constructor. + + The method for which a test is to be created + The test suite being built. + A newly constructed Test + + + + UniqueItemsConstraint tests whether all the items in a + collection are unique. + + + + + CollectionItemsEqualConstraint is the abstract base class for all + collection constraints that apply some notion of item equality + as a part of their operation. + + + + + CollectionConstraint is the abstract base class for + constraints that operate on collections. + + + + + Construct an empty CollectionConstraint + + + + + Construct a CollectionConstraint + + + + + + Determines whether the specified enumerable is empty. + + The enumerable. + + true if the specified enumerable is empty; otherwise, false. + + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for success, false for failure + + + + Protected method to be implemented by derived classes + + + + + + + Construct an empty CollectionConstraint + + + + + Construct a CollectionConstraint + + + + + + Flag the constraint to use the supplied IComparer object. + + The IComparer object to use. + Self. + + + + Flag the constraint to use the supplied IComparer object. + + The IComparer object to use. + Self. + + + + Flag the constraint to use the supplied Comparison object. + + The IComparer object to use. + Self. + + + + Flag the constraint to use the supplied IEqualityComparer object. + + The IComparer object to use. + Self. + + + + Flag the constraint to use the supplied IEqualityComparer object. + + The IComparer object to use. + Self. + + + + Compares two collection members for equality + + + + + Return a new CollectionTally for use in making tests + + The collection to be included in the tally + + + + Flag the constraint to ignore case and return self. + + + + + Check that all items are unique. + + + + + + + The Description of what this constraint tests, for + use in messages and in the ConstraintResult. + + + + + SamePathOrUnderConstraint tests that one path is under another + + + + + PathConstraint serves as the abstract base of constraints + that operate on paths and provides several helper methods. + + + + + Construct a PathConstraint for a give expected path + + The expected path + + + + Returns the string representation of this constraint + + + + + Canonicalize the provided path + + + The path in standardized form + + + + Test whether one path in canonical form is a subpath of another path + + The first path - supposed to be the parent path + The second path - supposed to be the child path + + + + + Modifies the current instance to be case-sensitive + and returns it. + + + + + Initializes a new instance of the class. + + The expected path + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for success, false for failure + + + + The Description of what this constraint tests, for + use in messages and in the ConstraintResult. + + + + + NoItemConstraint applies another constraint to each + item in a collection, failing if any of them succeeds. + + + + + Construct a SomeItemsConstraint on top of an existing constraint + + + + + + Apply the item constraint to each item in the collection, + failing if any item fails. + + + + + + + The display name of this Constraint for use by ToString(). + The default value is the name of the constraint with + trailing "Constraint" removed. Derived classes may set + this to another name in their constructors. + + + + + EndsWithConstraint can test whether a string ends + with an expected substring. + + + + + Initializes a new instance of the class. + + The expected string + + + + Test whether the constraint is matched by the actual value. + This is a template method, which calls the IsMatch method + of the derived class. + + + + + + + ValuesAttribute is used to provide literal arguments for + an individual parameter of a test. + + + + + The abstract base class for all data-providing attributes + defined by NUnit. Used to select all data sources for a + method, class or parameter. + + + + + Default constructor + + + + + The IParameterDataSource interface is implemented by types + that can provide data for a test method parameter. + + + + + Gets an enumeration of data items for use as arguments + for a test method parameter. + + The parameter for which data is needed + An enumeration containing individual data items + + + + The collection of data to be returned. Must + be set by any derived attribute classes. + We use an object[] so that the individual + elements may have their type changed in GetData + if necessary + + + + + Constructs for use with an Enum parameter. Will pass every enum + value in to the test. + + + + + Construct with one argument + + + + + + Construct with two arguments + + + + + + + Construct with three arguments + + + + + + + + Construct with an array of arguments + + + + + + Get the collection of _values to be used as arguments + + + + + Marks a test to use a pairwise join of any argument + data provided. Arguments will be combined in such a + way that all possible pairs of arguments are used. + + + + + Marks a test to use a particular CombiningStrategy to join + any parameter data provided. Since this is the default, the + attribute is optional. + + + + + Construct a CombiningStrategyAttribute incorporating an + ICombiningStrategy and an IParamterDataProvider. + + Combining strategy to be used in combining data + An IParameterDataProvider to supply data + + + + Construct a CombiningStrategyAttribute incorporating an object + that implements ICombiningStrategy and an IParameterDataProvider. + This constructor is provided for CLS compliance. + + Combining strategy to be used in combining data + An IParameterDataProvider to supply data + + + + Construct one or more TestMethods from a given MethodInfo, + using available parameter data. + + The MethodInfo for which tests are to be constructed. + The suite to which the tests will be added. + One or more TestMethods + + + + Modify the test by adding the name of the combining strategy + to the properties. + + The test to modify + + + + Default constructor + + + + + CultureAttribute is used to mark a test fixture or an + individual method as applying to a particular Culture only. + + + + + Abstract base for Attributes that are used to include tests + in the test run based on environmental settings. + + + + + Constructor with no included items specified, for use + with named property syntax. + + + + + Constructor taking one or more included items + + Comma-delimited list of included items + + + + Name of the item that is needed in order for + a test to run. Multiple items may be given, + separated by a comma. + + + + + Name of the item to be excluded. Multiple items + may be given, separated by a comma. + + + + + The reason for including or excluding the test + + + + + Constructor with no cultures specified, for use + with named property syntax. + + + + + Constructor taking one or more cultures + + Comma-deliminted list of cultures + + + + Causes a test to be skipped if this CultureAttribute is not satisfied. + + The test to modify + + + + Tests to determine if the current culture is supported + based on the properties of this attribute. + + True, if the current culture is supported + + + + Test to determine if the a particular culture or comma- + delimited set of cultures is in use. + + Name of the culture or comma-separated list of culture ids + True if the culture is in use on the system + + + + Test to determine if one of a collection of cultures + is being used currently. + + + + + + + The current state of a work item + + + + + Ready to run or continue + + + + + Work Item is executing + + + + + Complete + + + + + A WorkItem may be an individual test case, a fixture or + a higher level grouping of tests. All WorkItems inherit + from the abstract WorkItem class, which uses the template + pattern to allow derived classes to perform work in + whatever way is needed. + + A WorkItem is created with a particular TestExecutionContext + and is responsible for re-establishing that context in the + current thread before it begins or resumes execution. + + + + + Creates a work item. + + The test for which this WorkItem is being created. + The filter to be used in selecting any child Tests. + + + + + Construct a WorkItem for a particular test. + + The test that the WorkItem will run + + + + Initialize the TestExecutionContext. This must be done + before executing the WorkItem. + + + Originally, the context was provided in the constructor + but delaying initialization of the context until the item + is about to be dispatched allows changes in the parent + context during OneTimeSetUp to be reflected in the child. + + The TestExecutionContext to use + + + + Execute the current work item, including any + child work items. + + + + + Cancel (abort or stop) a WorkItem + + true if the WorkItem should be aborted, false if it should run to completion + + + + Method that performs actually performs the work. It should + set the State to WorkItemState.Complete when done. + + + + + Method called by the derived class when all work is complete + + + + + Event triggered when the item is complete + + + + + Gets the current state of the WorkItem + + + + + The test being executed by the work item + + + + + The execution context + + + + + The unique id of the worker executing this item. + + + + + The test actions to be performed before and after this test + + + + + The test result + + + + + TODO: Documentation needed for class + + + + + TODO: Documentation needed for class + + + + + TestCommand is the abstract base class for all test commands + in the framework. A TestCommand represents a single stage in + the execution of a test, e.g.: SetUp/TearDown, checking for + Timeout, verifying the returned result from a method, etc. + + TestCommands may decorate other test commands so that the + execution of a lower-level command is nested within that + of a higher level command. All nested commands are executed + synchronously, as a single unit. Scheduling test execution + on separate threads is handled at a higher level, using the + task dispatcher. + + + + + Construct a TestCommand for a test. + + The test to be executed + + + + Runs the test in a specified context, returning a TestResult. + + The TestExecutionContext to be used for running the test. + A TestResult + + + + Gets the test associated with this command. + + + + TODO: Documentation needed for field + + + TODO: Documentation needed for method + + + + TODO: Documentation needed for constructor + + + + + + Initializes a new instance of the class. + + The inner command. + The max time allowed in milliseconds + + + + Runs the test, saving a TestResult in the supplied TestExecutionContext + + The context in which the test should run. + A TestResult + + + + The ITestListener interface is used internally to receive + notifications of significant events while a test is being + run. The events are propagated to clients by means of an + AsyncCallback. NUnit extensions may also monitor these events. + + + + + Called when a test has just started + + The test that is starting + + + + Called when a test has finished + + The result of the test + + + + Called when a test produces output for immediate display + + A TestOutput object containing the text to display + + + + The ITestAssemblyBuilder interface is implemented by a class + that is able to build a suite of tests given an assembly or + an assembly filename. + + + + + Build a suite of tests from a provided assembly + + The assembly from which tests are to be built + A dictionary of options to use in building the suite + A TestSuite containing the tests found in the assembly + + + + Build a suite of tests given the filename of an assembly + + The filename of the assembly from which tests are to be built + A dictionary of options to use in building the suite + A TestSuite containing the tests found in the assembly + + + + InternalTrace provides facilities for tracing the execution + of the NUnit framework. Tests and classes under test may make use + of Console writes, System.Diagnostics.Trace or various loggers and + NUnit itself traps and processes each of them. For that reason, a + separate internal trace is needed. + + Note: + InternalTrace uses a global lock to allow multiple threads to write + trace messages. This can easily make it a bottleneck so it must be + used sparingly. Keep the trace Level as low as possible and only + insert InternalTrace writes where they are needed. + TODO: add some buffering and a separate writer thread as an option. + TODO: figure out a way to turn on trace in specific classes only. + + + + + Initialize the internal trace facility using the name of the log + to be written to and the trace level. + + The log name + The trace level + + + + Initialize the internal trace using a provided TextWriter and level + + A TextWriter + The InternalTraceLevel + + + + Get a named Logger + + + + + + Get a logger named for a particular Type. + + + + + Gets a flag indicating whether the InternalTrace is initialized + + + + + The ITypeInfo interface is an abstraction of a .NET Type + + + + + Returns true if the Type wrapped is equal to the argument + + + + + Get the display name for this typeInfo. + + + + + Get the display name for an oject of this type, constructed with specific arguments + + + + + Returns a Type representing a generic type definition from which this Type can be constructed. + + + + + Returns a new ITypeInfo representing an instance of this generic Type using the supplied Type arguments + + + + + Returns a value indicating whether this type has a method with a specified public attribute + + + + + Returns an array of IMethodInfos for methods of this Type + that match the specified flags. + + + + + Gets the public constructor taking the specified argument Types + + + + + Returns a value indicating whether this Type has a public constructor taking the specified argument Types. + + + + + Construct an object of this Type, using the specified arguments. + + + + + Gets the underlying Type on which this ITypeInfo is based + + + + + Gets the base type of this type as an ITypeInfo + + + + + Gets the Name of the Type + + + + + Gets the FullName of the Type + + + + + Gets the assembly in which the type is declared + + + + + Gets the Namespace of the Type + + + + + Gets a value indicating whether the type is abstract. + + + + + Gets a value indicating whether the Type is a generic Type + + + + + Gets a value indicating whether the Type has generic parameters that have not been replaced by specific Types. + + + + + Gets a value indicating whether the Type is a generic Type definition + + + + + Gets a value indicating whether the type is sealed. + + + + + Gets a value indicating whether this type is a static class. + + + + + Applies the constraint to an actual value, returning a ConstraintResult. + + The value to be tested + A ConstraintResult + + + + The Description of what this constraint tests, for + use in messages and in the ConstraintResult. + + + + + Defines methods to manipulate thread-safe collections intended for producer/consumer usage. + + Specifies the type of elements in the collection. + + All implementations of this interface must enable all members of this interface + to be used concurrently from multiple threads. + + + + + Attempts to add an object to the . + + The object to add to the . + true if the object was added successfully; otherwise, false. + The was invalid for this collection. + + + + Attempts to remove and return an object from the . + + + When this method returns, if the object was removed and returned successfully, contains the removed object. If no object was available to be removed, the value is + unspecified. + + true if an object was removed and returned successfully; otherwise, false. + + + + Copies the elements contained in the to a new array. + + A new array containing the elements copied from the . + + + + Copies the elements of the to + an + , starting at a specified index. + + The one-dimensional that is the destination of + the elements copied from the . + The array must have zero-based indexing. + The zero-based index in at which copying + begins. + is a null reference (Nothing in + Visual Basic). + is less than + zero. + is equal to or greater than the + length of the + -or- The number of elements in the source is greater than the + available space from to the end of the destination . + + + + + Provide the context information of the current test. + This is an adapter for the internal ExecutionContext + class, hiding the internals from the user test. + + + + + + + + + + Construct a TestContext for an ExecutionContext + + The ExecutionContext to adapt + + + + Gets a TextWriter that will send output directly to Console.Error + + + + + Gets a TextWriter for use in displaying immediate progress messages + + + + + TestParameters object holds parameters for the test run, if any are specified + + + + Write the string representation of a boolean value to the current result + + + Write a char to the current result + + + Write a char array to the current result + + + Write the string representation of a double to the current result + + + Write the string representation of an Int32 value to the current result + + + Write the string representation of an Int64 value to the current result + + + Write the string representation of a decimal value to the current result + + + Write the string representation of an object to the current result + + + Write the string representation of a Single value to the current result + + + Write a string to the current result + + + Write the string representation of a UInt32 value to the current result + + + Write the string representation of a UInt64 value to the current result + + + Write a formatted string to the current result + + + Write a formatted string to the current result + + + Write a formatted string to the current result + + + Write a formatted string to the current result + + + Write a line terminator to the current result + + + Write the string representation of a boolean value to the current result followed by a line terminator + + + Write a char to the current result followed by a line terminator + + + Write a char array to the current result followed by a line terminator + + + Write the string representation of a double to the current result followed by a line terminator + + + Write the string representation of an Int32 value to the current result followed by a line terminator + + + Write the string representation of an Int64 value to the current result followed by a line terminator + + + Write the string representation of a decimal value to the current result followed by a line terminator + + + Write the string representation of an object to the current result followed by a line terminator + + + Write the string representation of a Single value to the current result followed by a line terminator + + + Write a string to the current result followed by a line terminator + + + Write the string representation of a UInt32 value to the current result followed by a line terminator + + + Write the string representation of a UInt64 value to the current result followed by a line terminator + + + Write a formatted string to the current result followed by a line terminator + + + Write a formatted string to the current result followed by a line terminator + + + Write a formatted string to the current result followed by a line terminator + + + Write a formatted string to the current result followed by a line terminator + + + + This method adds the a new ValueFormatterFactory to the + chain of responsibility used for fomatting values in messages. + The scope of the change is the current TestContext. + + The factory delegate + + + + This method provides a simplified way to add a ValueFormatter + delegate to the chain of responsibility, creating the factory + delegate internally. It is useful when the Type of the object + is the only criterion for selection of the formatter, since + it can be used without getting involved with a compould function. + + The type supported by this formatter + The ValueFormatter delegate + + + + Get the current test context. This is created + as needed. The user may save the context for + use within a test, but it should not be used + outside the test for which it is created. + + + + + Gets a TextWriter that will send output to the current test result. + + + + + Get a representation of the current test. + + + + + Gets a Representation of the TestResult for the current test. + + + + + Gets the unique name of the Worker that is executing this test. + + + + + Gets the directory containing the current test assembly. + + + + + Gets the directory to be used for outputting files created + by this test run. + + + + + Gets the random generator. + + + The random generator. + + + + + TestAdapter adapts a Test for consumption by + the user test code. + + + + + Construct a TestAdapter for a Test + + The Test to be adapted + + + + Gets the unique Id of a test + + + + + The name of the test, which may or may not be + the same as the method name. + + + + + The name of the method representing the test. + + + + + The FullName of the test + + + + + The ClassName of the test + + + + + The properties of the test. + + + + + ResultAdapter adapts a TestResult for consumption by + the user test code. + + + + + Construct a ResultAdapter for a TestResult + + The TestResult to be adapted + + + + Gets a ResultState representing the outcome of the test. + + + + + Gets the message associated with a test + failure or with not running the test + + + + + Gets any stacktrace associated with an + error or failure. + + + + + Gets the number of test cases that failed + when running the test and all its children. + + + + + Gets the number of test cases that passed + when running the test and all its children. + + + + + Gets the number of test cases that were skipped + when running the test and all its children. + + + + + Gets the number of test cases that were inconclusive + when running the test and all its children. + + + + + ExceptionHelper provides static methods for working with exceptions + + + + + Rethrows an exception, preserving its stack trace + + The exception to rethrow + + + + Builds up a message, using the Message field of the specified exception + as well as any InnerExceptions. + + The exception. + A combined message string. + + + + Builds up a message, using the Message field of the specified exception + as well as any InnerExceptions. + + The exception. + A combined stack trace. + + + + Gets the stack trace of the exception. + + The exception. + A string representation of the stack trace. + + + + CultureDetector is a helper class used by NUnit to determine + whether a test should be run based on the current culture. + + + + + Default constructor uses the current culture. + + + + + Construct a CultureDetector for a particular culture for testing. + + The culture to be used + + + + Test to determine if one of a collection of cultures + is being used currently. + + + + + + + Tests to determine if the current culture is supported + based on a culture attribute. + + The attribute to examine + + + + + Test to determine if the a particular culture or comma- + delimited set of cultures is in use. + + Name of the culture or comma-separated list of culture ids + True if the culture is in use on the system + + + + Return the last failure reason. Results are not + defined if called before IsSupported( Attribute ) + is called. + + + + + PairwiseStrategy creates test cases by combining the parameter + data so that all possible pairs of data items are used. + + + + The number of test cases that cover all possible pairs of test function + parameters values is significantly less than the number of test cases + that cover all possible combination of test function parameters values. + And because different studies show that most of software failures are + caused by combination of no more than two parameters, pairwise testing + can be an effective ways to test the system when it's impossible to test + all combinations of parameters. + + + The PairwiseStrategy code is based on "jenny" tool by Bob Jenkins: + http://burtleburtle.net/bob/math/jenny.html + + + + + + Gets the test cases generated by this strategy instance. + + A set of test cases. + + + + FleaRand is a pseudo-random number generator developed by Bob Jenkins: + http://burtleburtle.net/bob/rand/talksmall.html#flea + + + + + Initializes a new instance of the FleaRand class. + + The seed. + + + + FeatureInfo represents coverage of a single value of test function + parameter, represented as a pair of indices, Dimension and Feature. In + terms of unit testing, Dimension is the index of the test parameter and + Feature is the index of the supplied value in that parameter's list of + sources. + + + + + Initializes a new instance of FeatureInfo class. + + Index of a dimension. + Index of a feature. + + + + A FeatureTuple represents a combination of features, one per test + parameter, which should be covered by a test case. In the + PairwiseStrategy, we are only trying to cover pairs of features, so the + tuples actually may contain only single feature or pair of features, but + the algorithm itself works with triplets, quadruples and so on. + + + + + Initializes a new instance of FeatureTuple class for a single feature. + + Single feature. + + + + Initializes a new instance of FeatureTuple class for a pair of features. + + First feature. + Second feature. + + + + TestCase represents a single test case covering a list of features. + + + + + Initializes a new instance of TestCaseInfo class. + + A number of features in the test case. + + + + PairwiseTestCaseGenerator class implements an algorithm which generates + a set of test cases which covers all pairs of possible values of test + function. + + + + The algorithm starts with creating a set of all feature tuples which we + will try to cover (see method). This set + includes every single feature and all possible pairs of features. We + store feature tuples in the 3-D collection (where axes are "dimension", + "feature", and "all combinations which includes this feature"), and for + every two feature (e.g. "A" and "B") we generate both ("A", "B") and + ("B", "A") pairs. This data structure extremely reduces the amount of + time needed to calculate coverage for a single test case (this + calculation is the most time-consuming part of the algorithm). + + + Then the algorithm picks one tuple from the uncovered tuple, creates a + test case that covers this tuple, and then removes this tuple and all + other tuples covered by this test case from the collection of uncovered + tuples. + + + Picking a tuple to cover + + + There are no any special rules defined for picking tuples to cover. We + just pick them one by one, in the order they were generated. + + + Test generation + + + Test generation starts from creating a completely random test case which + covers, nevertheless, previously selected tuple. Then the algorithm + tries to maximize number of tuples which this test covers. + + + Test generation and maximization process repeats seven times for every + selected tuple and then the algorithm picks the best test case ("seven" + is a magic number which provides good results in acceptable time). + + Maximizing test coverage + + To maximize tests coverage, the algorithm walks thru the list of mutable + dimensions (mutable dimension is a dimension that are not included in + the previously selected tuple). Then for every dimension, the algorithm + walks thru the list of features and checks if this feature provides + better coverage than randomly selected feature, and if yes keeps this + feature. + + + This process repeats while it shows progress. If the last iteration + doesn't improve coverage, the process ends. + + + In addition, for better results, before start every iteration, the + algorithm "scrambles" dimensions - so for every iteration dimension + probes in a different order. + + + + + + Creates a set of test cases for specified dimensions. + + + An array which contains information about dimensions. Each element of + this array represents a number of features in the specific dimension. + + + A set of test cases. + + + + + Provides data from fields marked with the DatapointAttribute or the + DatapointsAttribute. + + + + + The IDataPointProvider interface is used by extensions + that provide data for a single test parameter. + + + + + Determine whether any data is available for a parameter. + + An IParameterInfo representing one + argument to a parameterized test + True if any data is available, otherwise false. + + + + Return an IEnumerable providing data for use with the + supplied parameter. + + An IParameterInfo representing one + argument to a parameterized test + An IEnumerable providing the required data + + + + Determine whether any data is available for a parameter. + + A ParameterInfo representing one + argument to a parameterized test + + True if any data is available, otherwise false. + + + + + Return an IEnumerable providing data for use with the + supplied parameter. + + A ParameterInfo representing one + argument to a parameterized test + + An IEnumerable providing the required data + + + + + CombinatorialStrategy creates test cases by using all possible + combinations of the parameter data. + + + + + Gets the test cases generated by the CombiningStrategy. + + The test cases. + + + + ThrowsNothingConstraint tests that a delegate does not + throw an exception. + + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True if no exception is thrown, otherwise false + + + + Applies the constraint to an ActualValueDelegate that returns + the value to be tested. The default implementation simply evaluates + the delegate but derived classes may override it to provide for + delayed processing. + + An ActualValueDelegate + A ConstraintResult + + + + Gets text describing a constraint + + + + + Operator that requires at least one of it's arguments to succeed + + + + + Abstract base class for all binary operators + + + + + The ConstraintOperator class is used internally by a + ConstraintBuilder to represent an operator that + modifies or combines constraints. + + Constraint operators use left and right precedence + _values to determine whether the top operator on the + stack should be reduced before pushing a new operator. + + + + + The precedence value used when the operator + is about to be pushed to the stack. + + + + + The precedence value used when the operator + is on the top of the stack. + + + + + Reduce produces a constraint from the operator and + any arguments. It takes the arguments from the constraint + stack and pushes the resulting constraint on it. + + + + + + The syntax element preceding this operator + + + + + The syntax element following this operator + + + + + The precedence value used when the operator + is about to be pushed to the stack. + + + + + The precedence value used when the operator + is on the top of the stack. + + + + + Reduce produces a constraint from the operator and + any arguments. It takes the arguments from the constraint + stack and pushes the resulting constraint on it. + + + + + + Abstract method that produces a constraint by applying + the operator to its left and right constraint arguments. + + + + + Gets the left precedence of the operator + + + + + Gets the right precedence of the operator + + + + + Construct an OrOperator + + + + + Apply the operator to produce an OrConstraint + + + + + The Numerics class contains common operations on numeric _values. + + + + + Checks the type of the object, returning true if + the object is a numeric type. + + The object to check + true if the object is a numeric type + + + + Checks the type of the object, returning true if + the object is a floating point numeric type. + + The object to check + true if the object is a floating point numeric type + + + + Checks the type of the object, returning true if + the object is a fixed point numeric type. + + The object to check + true if the object is a fixed point numeric type + + + + Test two numeric _values for equality, performing the usual numeric + conversions and using a provided or default tolerance. If the tolerance + provided is Empty, this method may set it to a default tolerance. + + The expected value + The actual value + A reference to the tolerance in effect + True if the _values are equal + + + + Compare two numeric _values, performing the usual numeric conversions. + + The expected value + The actual value + The relationship of the _values to each other + + + + FalseConstraint tests that the actual value is false + + + + + Initializes a new instance of the class. + + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for success, false for failure + + + + TestFixtureAttribute is used to mark a class that represents a TestFixture. + + + + + The ITestCaseData interface is implemented by a class + that is able to return the data required to create an + instance of a parameterized test fixture. + + + + + The ITestData interface is implemented by a class that + represents a single instance of a parameterized test. + + + + + Gets the name to be used for the test + + + + + Gets the RunState for this test case. + + + + + Gets the argument list to be provided to the test + + + + + Gets the property dictionary for the test case + + + + + Get the TypeArgs if separately set + + + + + Default constructor + + + + + Construct with a object[] representing a set of arguments. + In .NET 2.0, the arguments may later be separated into + type arguments and constructor arguments. + + + + + + Build a fixture from type provided. Normally called for a Type + on which the attribute has been placed. + + The type info of the fixture to be used. + A an IEnumerable holding one TestFixture object. + + + + Gets or sets the name of the test. + + The name of the test. + + + + Gets or sets the RunState of this test fixture. + + + + + The arguments originally provided to the attribute + + + + + Properties pertaining to this fixture + + + + + Get or set the type arguments. If not set + explicitly, any leading arguments that are + Types are taken as type arguments. + + + + + Descriptive text for this fixture + + + + + The author of this fixture + + + + + The type that this fixture is testing + + + + + Gets or sets the ignore reason. May set RunState as a side effect. + + The ignore reason. + + + + Gets or sets the reason for not running the fixture. + + The reason. + + + + Gets or sets the ignore reason. When set to a non-null + non-empty value, the test is marked as ignored. + + The ignore reason. + + + + Gets or sets a value indicating whether this is explicit. + + + true if explicit; otherwise, false. + + + + + Gets and sets the category for this fixture. + May be a comma-separated list of categories. + + + + + TestCaseAttribute is used to mark parameterized test cases + and provide them with their arguments. + + + + + The ITestCaseData interface is implemented by a class + that is able to return complete testcases for use by + a parameterized test method. + + + + + Gets the expected result of the test case + + + + + Returns true if an expected result has been set + + + + + IImplyFixture is an empty marker interface used by attributes like + TestAttribute that cause the class where they are used to be treated + as a TestFixture even without a TestFixtureAttribute. + + Marker interfaces are not usually considered a good practice, but + we use it here to avoid cluttering the attribute hierarchy with + classes that don't contain any extra implementation. + + + + + Construct a TestCaseAttribute with a list of arguments. + This constructor is not CLS-Compliant + + + + + + Construct a TestCaseAttribute with a single argument + + + + + + Construct a TestCaseAttribute with a two arguments + + + + + + + Construct a TestCaseAttribute with a three arguments + + + + + + + + Performs several special conversions allowed by NUnit in order to + permit arguments with types that cannot be used in the constructor + of an Attribute such as TestCaseAttribute or to simplify their use. + + The arguments to be converted + The ParameterInfo array for the method + + + + Construct one or more TestMethods from a given MethodInfo, + using available parameter data. + + The MethodInfo for which tests are to be constructed. + The suite to which the tests will be added. + One or more TestMethods + + + + Gets or sets the name of the test. + + The name of the test. + + + + Gets or sets the RunState of this test case. + + + + + Gets the list of arguments to a test case + + + + + Gets the properties of the test case + + + + + Gets or sets the expected result. + + The result. + + + + Returns true if the expected result has been set + + + + + Gets or sets the description. + + The description. + + + + The author of this test + + + + + The type that this test is testing + + + + + Gets or sets the reason for ignoring the test + + + + + Gets or sets a value indicating whether this is explicit. + + + true if explicit; otherwise, false. + + + + + Gets or sets the reason for not running the test. + + The reason. + + + + Gets or sets the ignore reason. When set to a non-null + non-empty value, the test is marked as ignored. + + The ignore reason. + + + + Comma-delimited list of platforms to run the test for + + + + + Comma-delimited list of platforms to not run the test for + + + + + Gets and sets the category for this test case. + May be a comma-separated list of categories. + + + + + GenericMethodHelper is able to deduce the Type arguments for + a generic method from the actual arguments provided. + + + + + Construct a GenericMethodHelper for a method + + MethodInfo for the method to examine + + + + Return the type argments for the method, deducing them + from the arguments actually provided. + + The arguments to the method + An array of type arguments. + + + + TestActionCommand runs the BeforeTest actions for a test, + then runs the test and finally runs the AfterTestActions. + + + + + Initializes a new instance of the class. + + The inner command. + + + + Runs the test, saving a TestResult in the supplied TestExecutionContext. + + The context in which the test should run. + A TestResult + + + + Provides internal logging to the NUnit framework + + + + + Interface for logging within the engine + + + + + Logs the specified message at the error level. + + The message. + + + + Logs the specified message at the error level. + + The message. + The arguments. + + + + Logs the specified message at the warning level. + + The message. + + + + Logs the specified message at the warning level. + + The message. + The arguments. + + + + Logs the specified message at the info level. + + The message. + + + + Logs the specified message at the info level. + + The message. + The arguments. + + + + Logs the specified message at the debug level. + + The message. + + + + Logs the specified message at the debug level. + + The message. + The arguments. + + + + Initializes a new instance of the class. + + The name. + The log level. + The writer where logs are sent. + + + + Logs the message at error level. + + The message. + + + + Logs the message at error level. + + The message. + The message arguments. + + + + Logs the message at warm level. + + The message. + + + + Logs the message at warning level. + + The message. + The message arguments. + + + + Logs the message at info level. + + The message. + + + + Logs the message at info level. + + The message. + The message arguments. + + + + Logs the message at debug level. + + The message. + + + + Logs the message at debug level. + + The message. + The message arguments. + + + + ClassName filter selects tests based on the class FullName + + + + + Construct a FullNameFilter for a single name + + The name the filter will recognize. + + + + Match a test against a single value. + + + + + Gets the element name + + Element name + + + + PropertyFilter is able to select or exclude tests + based on their properties. + + + + + + Construct a PropertyFilter using a property name and expected value + + A property name + The expected value of the property + + + + Check whether the filter matches a test + + The test to be matched + + + + + Adds an XML node + + Parent node + True if recursive + The added XML node + + + + Gets the element name + + Element name + + + + Env is a static class that provides some of the features of + System.Environment that are not available under all runtimes + + + + + The newline sequence in the current environment. + + + + + Path to the 'My Documents' folder + + + + + Directory used for file output if not specified on commandline. + + + + + The Assert class contains a collection of static methods that + implement the most common assertions used in NUnit. + + + The Assert class contains a collection of static methods that + implement the most common assertions used in NUnit. + + + + + Asserts that a condition is true. If the condition is false the method throws + an . + + The evaluated condition + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that a condition is true. If the condition is false the method throws + an . + + The evaluated condition + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that a condition is true. If the condition is false the method throws + an . + + The evaluated condition + + + + Asserts that a condition is true. If the condition is false the method throws + an . + + The evaluated condition + + + + Asserts that a condition is true. If the condition is false the method throws + an . + + The evaluated condition + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that a condition is true. If the condition is false the method throws + an . + + The evaluated condition + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that a condition is true. If the condition is false the method throws + an . + + The evaluated condition + + + + Asserts that a condition is true. If the condition is false the method throws + an . + + The evaluated condition + + + + Asserts that a condition is false. If the condition is true the method throws + an . + + The evaluated condition + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that a condition is false. If the condition is true the method throws + an . + + The evaluated condition + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that a condition is false. If the condition is true the method throws + an . + + The evaluated condition + + + + Asserts that a condition is false. If the condition is true the method throws + an . + + The evaluated condition + + + + Asserts that a condition is false. If the condition is true the method throws + an . + + The evaluated condition + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that a condition is false. If the condition is true the method throws + an . + + The evaluated condition + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that a condition is false. If the condition is true the method throws + an . + + The evaluated condition + + + + Asserts that a condition is false. If the condition is true the method throws + an . + + The evaluated condition + + + + Verifies that the object that is passed in is not equal to null + If the object is null then an + is thrown. + + The object that is to be tested + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the object that is passed in is not equal to null + If the object is null then an + is thrown. + + The object that is to be tested + + + + Verifies that the object that is passed in is not equal to null + If the object is null then an + is thrown. + + The object that is to be tested + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the object that is passed in is not equal to null + If the object is null then an + is thrown. + + The object that is to be tested + + + + Verifies that the object that is passed in is equal to null + If the object is not null then an + is thrown. + + The object that is to be tested + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the object that is passed in is equal to null + If the object is not null then an + is thrown. + + The object that is to be tested + + + + Verifies that the object that is passed in is equal to null + If the object is not null then an + is thrown. + + The object that is to be tested + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the object that is passed in is equal to null + If the object is not null then an + is thrown. + + The object that is to be tested + + + + Verifies that the double that is passed in is an NaN value. + If the object is not NaN then an + is thrown. + + The value that is to be tested + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the double that is passed in is an NaN value. + If the object is not NaN then an + is thrown. + + The value that is to be tested + + + + Verifies that the double that is passed in is an NaN value. + If the object is not NaN then an + is thrown. + + The value that is to be tested + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the double that is passed in is an NaN value. + If the object is not NaN then an + is thrown. + + The value that is to be tested + + + + Assert that a string is empty - that is equal to string.Empty + + The string to be tested + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Assert that a string is empty - that is equal to string.Empty + + The string to be tested + + + + Assert that an array, list or other collection is empty + + An array, list or other collection implementing ICollection + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Assert that an array, list or other collection is empty + + An array, list or other collection implementing ICollection + + + + Assert that a string is not empty - that is not equal to string.Empty + + The string to be tested + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Assert that a string is not empty - that is not equal to string.Empty + + The string to be tested + + + + Assert that an array, list or other collection is not empty + + An array, list or other collection implementing ICollection + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Assert that an array, list or other collection is not empty + + An array, list or other collection implementing ICollection + + + + Asserts that an int is zero. + + The number to be examined + + + + Asserts that an int is zero. + + The number to be examined + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that an unsigned int is zero. + + The number to be examined + + + + Asserts that an unsigned int is zero. + + The number to be examined + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that a Long is zero. + + The number to be examined + + + + Asserts that a Long is zero. + + The number to be examined + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that an unsigned Long is zero. + + The number to be examined + + + + Asserts that an unsigned Long is zero. + + The number to be examined + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that a decimal is zero. + + The number to be examined + + + + Asserts that a decimal is zero. + + The number to be examined + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that a double is zero. + + The number to be examined + + + + Asserts that a double is zero. + + The number to be examined + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that a float is zero. + + The number to be examined + + + + Asserts that a float is zero. + + The number to be examined + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that an int is not zero. + + The number to be examined + + + + Asserts that an int is not zero. + + The number to be examined + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that an unsigned int is not zero. + + The number to be examined + + + + Asserts that an unsigned int is not zero. + + The number to be examined + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that a Long is not zero. + + The number to be examined + + + + Asserts that a Long is not zero. + + The number to be examined + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that an unsigned Long is not zero. + + The number to be examined + + + + Asserts that an unsigned Long is not zero. + + The number to be examined + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that a decimal is zero. + + The number to be examined + + + + Asserts that a decimal is zero. + + The number to be examined + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that a double is zero. + + The number to be examined + + + + Asserts that a double is zero. + + The number to be examined + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that a float is zero. + + The number to be examined + + + + Asserts that a float is zero. + + The number to be examined + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that an int is negative. + + The number to be examined + + + + Asserts that an int is negative. + + The number to be examined + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that an unsigned int is negative. + + The number to be examined + + + + Asserts that an unsigned int is negative. + + The number to be examined + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that a Long is negative. + + The number to be examined + + + + Asserts that a Long is negative. + + The number to be examined + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that an unsigned Long is negative. + + The number to be examined + + + + Asserts that an unsigned Long is negative. + + The number to be examined + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that a decimal is negative. + + The number to be examined + + + + Asserts that a decimal is negative. + + The number to be examined + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that a double is negative. + + The number to be examined + + + + Asserts that a double is negative. + + The number to be examined + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that a float is negative. + + The number to be examined + + + + Asserts that a float is negative. + + The number to be examined + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that an int is negative. + + The number to be examined + + + + Asserts that an int is negative. + + The number to be examined + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that an unsigned int is negative. + + The number to be examined + + + + Asserts that an unsigned int is negative. + + The number to be examined + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that a Long is negative. + + The number to be examined + + + + Asserts that a Long is negative. + + The number to be examined + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that an unsigned Long is negative. + + The number to be examined + + + + Asserts that an unsigned Long is negative. + + The number to be examined + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that a decimal is negative. + + The number to be examined + + + + Asserts that a decimal is negative. + + The number to be examined + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that a double is negative. + + The number to be examined + + + + Asserts that a double is negative. + + The number to be examined + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that a float is negative. + + The number to be examined + + + + Asserts that a float is negative. + + The number to be examined + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that an object may be assigned a value of a given Type. + + The expected Type. + The object under examination + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that an object may be assigned a value of a given Type. + + The expected Type. + The object under examination + + + + Asserts that an object may be assigned a value of a given Type. + + The expected Type. + The object under examination + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that an object may be assigned a value of a given Type. + + The expected Type. + The object under examination + + + + Asserts that an object may not be assigned a value of a given Type. + + The expected Type. + The object under examination + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that an object may not be assigned a value of a given Type. + + The expected Type. + The object under examination + + + + Asserts that an object may not be assigned a value of a given Type. + + The expected Type. + The object under examination + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that an object may not be assigned a value of a given Type. + + The expected Type. + The object under examination + + + + Asserts that an object is an instance of a given type. + + The expected Type + The object being examined + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that an object is an instance of a given type. + + The expected Type + The object being examined + + + + Asserts that an object is an instance of a given type. + + The expected Type + The object being examined + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that an object is an instance of a given type. + + The expected Type + The object being examined + + + + Asserts that an object is not an instance of a given type. + + The expected Type + The object being examined + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that an object is not an instance of a given type. + + The expected Type + The object being examined + + + + Asserts that an object is not an instance of a given type. + + The expected Type + The object being examined + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that an object is not an instance of a given type. + + The expected Type + The object being examined + + + + Verifies that a delegate throws a particular exception when called. + + A constraint to be satisfied by the exception + A TestSnippet delegate + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Verifies that a delegate throws a particular exception when called. + + A constraint to be satisfied by the exception + A TestSnippet delegate + + + + Verifies that a delegate throws a particular exception when called. + + The exception Type expected + A TestDelegate + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Verifies that a delegate throws a particular exception when called. + + The exception Type expected + A TestDelegate + + + + Verifies that a delegate throws a particular exception when called. + + Type of the expected exception + A TestDelegate + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Verifies that a delegate throws a particular exception when called. + + Type of the expected exception + A TestDelegate + + + + Verifies that a delegate throws an exception when called + and returns it. + + A TestDelegate + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Verifies that a delegate throws an exception when called + and returns it. + + A TestDelegate + + + + Verifies that a delegate throws an exception of a certain Type + or one derived from it when called and returns it. + + The expected Exception Type + A TestDelegate + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Verifies that a delegate throws an exception of a certain Type + or one derived from it when called and returns it. + + The expected Exception Type + A TestDelegate + + + + Verifies that a delegate throws an exception of a certain Type + or one derived from it when called and returns it. + + A TestDelegate + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Verifies that a delegate throws an exception of a certain Type + or one derived from it when called and returns it. + + A TestDelegate + + + + Verifies that a delegate does not throw an exception + + A TestDelegate + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Verifies that a delegate does not throw an exception. + + A TestDelegate + + + + Asserts that a condition is true. If the condition is false the method throws + an . + + The evaluated condition + The message to display if the condition is false + Arguments to be used in formatting the message + + + + Asserts that a condition is true. If the condition is false the method throws + an . + + The evaluated condition + + + + Asserts that a condition is true. If the condition is false the method throws + an . + + The evaluated condition + A function to build the message included with the Exception + + + + Asserts that a condition is true. If the condition is false the method throws + an . + + A lambda that returns a Boolean + The message to display if the condition is false + Arguments to be used in formatting the message + + + + Asserts that a condition is true. If the condition is false the method throws + an . + + A lambda that returns a Boolean + + + + Asserts that a condition is true. If the condition is false the method throws + an . + + A lambda that returns a Boolean + A function to build the message included with the Exception + + + + Apply a constraint to an actual value, succeeding if the constraint + is satisfied and throwing an assertion exception on failure. + + The Type being compared. + An ActualValueDelegate returning the value to be tested + A Constraint expression to be applied + + + + Apply a constraint to an actual value, succeeding if the constraint + is satisfied and throwing an assertion exception on failure. + + The Type being compared. + An ActualValueDelegate returning the value to be tested + A Constraint expression to be applied + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Apply a constraint to an actual value, succeeding if the constraint + is satisfied and throwing an assertion exception on failure. + + The Type being compared. + An ActualValueDelegate returning the value to be tested + A Constraint expression to be applied + A function to build the message included with the Exception + + + + Asserts that the code represented by a delegate throws an exception + that satisfies the constraint provided. + + A TestDelegate to be executed + A ThrowsConstraint used in the test + + + + Asserts that the code represented by a delegate throws an exception + that satisfies the constraint provided. + + A TestDelegate to be executed + A ThrowsConstraint used in the test + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Asserts that the code represented by a delegate throws an exception + that satisfies the constraint provided. + + A TestDelegate to be executed + A ThrowsConstraint used in the test + A function to build the message included with the Exception + + + + Apply a constraint to an actual value, succeeding if the constraint + is satisfied and throwing an assertion exception on failure. + + The Type being compared. + The actual value to test + A Constraint to be applied + + + + Apply a constraint to an actual value, succeeding if the constraint + is satisfied and throwing an assertion exception on failure. + + The Type being compared. + The actual value to test + A Constraint expression to be applied + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Apply a constraint to an actual value, succeeding if the constraint + is satisfied and throwing an assertion exception on failure. + + The Type being compared. + The actual value to test + A Constraint expression to be applied + A function to build the message included with the Exception + + + + Apply a constraint to an actual value, succeeding if the constraint + is satisfied and throwing an assertion exception on failure. + Used as a synonym for That in rare cases where a private setter + causes a Visual Basic compilation error. + + The actual value to test + A Constraint to be applied + + + + Apply a constraint to an actual value, succeeding if the constraint + is satisfied and throwing an assertion exception on failure. + Used as a synonym for That in rare cases where a private setter + causes a Visual Basic compilation error. + + + This method is provided for use by VB developers needing to test + the value of properties with private setters. + + The actual value to test + A Constraint expression to be applied + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + We don't actually want any instances of this object, but some people + like to inherit from it to add other static methods. Hence, the + protected constructor disallows any instances of this object. + + + + + The Equals method throws an InvalidOperationException. This is done + to make sure there is no mistake by calling this function. + + + + + + + override the default ReferenceEquals to throw an InvalidOperationException. This + implementation makes sure there is no mistake in calling this function + as part of Assert. + + + + + + + Throws a with the message and arguments + that are passed in. This allows a test to be cut short, with a result + of success returned to NUnit. + + The message to initialize the with. + Arguments to be used in formatting the message + + + + Throws a with the message and arguments + that are passed in. This allows a test to be cut short, with a result + of success returned to NUnit. + + The message to initialize the with. + + + + Throws a with the message and arguments + that are passed in. This allows a test to be cut short, with a result + of success returned to NUnit. + + + + + Throws an with the message and arguments + that are passed in. This is used by the other Assert functions. + + The message to initialize the with. + Arguments to be used in formatting the message + + + + Throws an with the message that is + passed in. This is used by the other Assert functions. + + The message to initialize the with. + + + + Throws an . + This is used by the other Assert functions. + + + + + Throws an with the message and arguments + that are passed in. This causes the test to be reported as ignored. + + The message to initialize the with. + Arguments to be used in formatting the message + + + + Throws an with the message that is + passed in. This causes the test to be reported as ignored. + + The message to initialize the with. + + + + Throws an . + This causes the test to be reported as ignored. + + + + + Throws an with the message and arguments + that are passed in. This causes the test to be reported as inconclusive. + + The message to initialize the with. + Arguments to be used in formatting the message + + + + Throws an with the message that is + passed in. This causes the test to be reported as inconclusive. + + The message to initialize the with. + + + + Throws an . + This causes the test to be reported as Inconclusive. + + + + + Asserts that an object is contained in a list. + + The expected object + The list to be examined + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that an object is contained in a list. + + The expected object + The list to be examined + + + + Verifies that the first int is greater than the second + int. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first int is greater than the second + int. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + + + + Verifies that the first value is greater than the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is greater than the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + + + + Verifies that the first value is greater than the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is greater than the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + + + + Verifies that the first value is greater than the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is greater than the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + + + + Verifies that the first value is greater than the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is greater than the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + + + + Verifies that the first value is greater than the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is greater than the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + + + + Verifies that the first value is greater than the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is greater than the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + + + + Verifies that the first value is greater than the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is greater than the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + + + + Verifies that the first value is greater than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is greater than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + + + + Verifies that the first value is greater than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is greater than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + + + + Verifies that the first value is greater than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is greater than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + + + + Verifies that the first value is greater than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is greater than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + + + + Verifies that the first value is greater than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is greater than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + + + + Verifies that the first value is greater than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is greater than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + + + + Verifies that the first value is greater than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is greater than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + + + + Verifies that the first value is greater than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is greater than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + + + + Verifies that the first value is less than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is less than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + + + + Verifies that the first value is less than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is less than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + + + + Verifies that the first value is less than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is less than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + + + + Verifies that the first value is less than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is less than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + + + + Verifies that the first value is less than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is less than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + + + + Verifies that the first value is less than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is less than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + + + + Verifies that the first value is less than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is less than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + + + + Verifies that the first value is less than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is less than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + + + + Verifies that two doubles are equal considering a delta. If the + expected value is infinity then the delta value is ignored. If + they are not equal then an is + thrown. + + The expected value + The actual value + The maximum acceptable difference between the + the expected and the actual + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that two doubles are equal considering a delta. If the + expected value is infinity then the delta value is ignored. If + they are not equal then an is + thrown. + + The expected value + The actual value + The maximum acceptable difference between the + the expected and the actual + + + + Verifies that two doubles are equal considering a delta. If the + expected value is infinity then the delta value is ignored. If + they are not equal then an is + thrown. + + The expected value + The actual value + The maximum acceptable difference between the + the expected and the actual + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that two doubles are equal considering a delta. If the + expected value is infinity then the delta value is ignored. If + they are not equal then an is + thrown. + + The expected value + The actual value + The maximum acceptable difference between the + the expected and the actual + + + + Verifies that two objects are equal. Two objects are considered + equal if both are null, or if both have the same value. NUnit + has special semantics for some object types. + If they are not equal an is thrown. + + The value that is expected + The actual value + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that two objects are equal. Two objects are considered + equal if both are null, or if both have the same value. NUnit + has special semantics for some object types. + If they are not equal an is thrown. + + The value that is expected + The actual value + + + + Verifies that two objects are not equal. Two objects are considered + equal if both are null, or if both have the same value. NUnit + has special semantics for some object types. + If they are equal an is thrown. + + The value that is expected + The actual value + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that two objects are not equal. Two objects are considered + equal if both are null, or if both have the same value. NUnit + has special semantics for some object types. + If they are equal an is thrown. + + The value that is expected + The actual value + + + + Asserts that two objects refer to the same object. If they + are not the same an is thrown. + + The expected object + The actual object + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that two objects refer to the same object. If they + are not the same an is thrown. + + The expected object + The actual object + + + + Asserts that two objects do not refer to the same object. If they + are the same an is thrown. + + The expected object + The actual object + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that two objects do not refer to the same object. If they + are the same an is thrown. + + The expected object + The actual object + + + + Helper for Assert.AreEqual(double expected, double actual, ...) + allowing code generation to work consistently. + + The expected value + The actual value + The maximum acceptable difference between the + the expected and the actual + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Represents a constraint that succeeds if all the + members of a collection match a base constraint. + + + + + Abstract base for operators that indicate how to + apply a constraint to items in a collection. + + + + + PrefixOperator takes a single constraint and modifies + it's action in some way. + + + + + Reduce produces a constraint from the operator and + any arguments. It takes the arguments from the constraint + stack and pushes the resulting constraint on it. + + + + + + Returns the constraint created by applying this + prefix to another constraint. + + + + + + + Constructs a CollectionOperator + + + + + Returns a constraint that will apply the argument + to the members of a collection, succeeding if + they all succeed. + + + + + FileExistsConstraint is used to determine if a file exists + + + + + FileOrDirectoryExistsConstraint is used to determine if a file or directory exists + + + + + Initializes a new instance of the class that + will check files and directories. + + + + + Initializes a new instance of the class that + will only check files if ignoreDirectories is true. + + if set to true [ignore directories]. + + + + Applies the constraint to an actual value, returning a ConstraintResult. + + The value to be tested + A ConstraintResult + + + + If true, the constraint will only check if files exist, not directories + + + + + If true, the constraint will only check if directories exist, not files + + + + + The Description of what this constraint tests, for + use in messages and in the ConstraintResult. + + + + + Initializes a new instance of the class. + + + + + The Description of what this constraint tests, for + use in messages and in the ConstraintResult. + + + + + TestAssemblyDirectoryResolveAttribute is used to mark a test assembly as needing a + special assembly resolution hook that will explicitly search the test assembly's + directory for dependent assemblies. This works around a conflict between mixed-mode + assembly initialization and tests running in their own AppDomain in some cases. + + + + + Helper methods for inspecting a type by reflection. + + Many of these methods take ICustomAttributeProvider as an + argument to avoid duplication, even though certain attributes can + only appear on specific types of members, like MethodInfo or Type. + + In the case where a type is being examined for the presence of + an attribute, interface or named member, the Reflect methods + operate with the full name of the member being sought. This + removes the necessity of the caller having a reference to the + assembly that defines the item being sought and allows the + NUnit core to inspect assemblies that reference an older + version of the NUnit framework. + + + + + Examine a fixture type and return an array of methods having a + particular attribute. The array is order with base methods first. + + The type to examine + The attribute Type to look for + Specifies whether to search the fixture type inheritance chain + The array of methods found + + + + Examine a fixture type and return true if it has a method with + a particular attribute. + + The type to examine + The attribute Type to look for + True if found, otherwise false + + + + Invoke the default constructor on a Type + + The Type to be constructed + An instance of the Type + + + + Invoke a constructor on a Type with arguments + + The Type to be constructed + Arguments to the constructor + An instance of the Type + + + + Returns an array of types from an array of objects. + Used because the compact framework doesn't support + Type.GetTypeArray() + + An array of objects + An array of Types + + + + Invoke a parameterless method returning void on an object. + + A MethodInfo for the method to be invoked + The object on which to invoke the method + + + + Invoke a method, converting any TargetInvocationException to an NUnitException. + + A MethodInfo for the method to be invoked + The object on which to invoke the method + The argument list for the method + The return value from the invoked method + + + + + + + + + Constructor delegate, makes it possible to use a factory to create objects + + + + + InvalidTestFixtureException is thrown when an appropriate test + fixture constructor using the provided arguments cannot be found. + + + + + Initializes a new instance of the class. + + + + + Initializes a new instance of the class. + + The message. + + + + Initializes a new instance of the class. + + The message. + The inner. + + + + Serialization Constructor + + + + + Class to build ether a parameterized or a normal NUnitTestMethod. + There are four cases that the builder must deal with: + 1. The method needs no params and none are provided + 2. The method needs params and they are provided + 3. The method needs no params but they are provided in error + 4. The method needs params but they are not provided + This could have been done using two different builders, but it + turned out to be simpler to have just one. The BuildFrom method + takes a different branch depending on whether any parameters are + provided, but all four cases are dealt with in lower-level methods + + + + + The ITestCaseBuilder interface is exposed by a class that knows how to + build a test case from certain methods. + + + This interface is not the same as the ITestCaseBuilder interface in NUnit 2.x. + We have reused the name because the two products don't interoperate at all. + + + + + Examine the method and determine if it is suitable for + this builder to use in building a TestCase to be + included in the suite being populated. + + Note that returning false will cause the method to be ignored + in loading the tests. If it is desired to load the method + but label it as non-runnable, ignored, etc., then this + method must return true. + + The test method to examine + The suite being populated + True is the builder can use this method + + + + Build a TestCase from the provided MethodInfo for + inclusion in the suite being constructed. + + The method to be used as a test case + The test suite being populated, or null + A TestCase or null + + + + Determines if the method can be used to build an NUnit test + test method of some kind. The method must normally be marked + with an identifying attribute for this to be true. + + Note that this method does not check that the signature + of the method for validity. If we did that here, any + test methods with invalid signatures would be passed + over in silence in the test run. Since we want such + methods to be reported, the check for validity is made + in BuildFrom rather than here. + + An IMethodInfo for the method being used as a test method + True if the builder can create a test case from this method + + + + Build a Test from the provided MethodInfo. Depending on + whether the method takes arguments and on the availability + of test case data, this method may return a single test + or a group of tests contained in a ParameterizedMethodSuite. + + The method for which a test is to be built + A Test representing one or more method invocations + + + + Determines if the method can be used to build an NUnit test + test method of some kind. The method must normally be marked + with an identifying attribute for this to be true. + + Note that this method does not check that the signature + of the method for validity. If we did that here, any + test methods with invalid signatures would be passed + over in silence in the test run. Since we want such + methods to be reported, the check for validity is made + in BuildFrom rather than here. + + An IMethodInfo for the method being used as a test method + The test suite being built, to which the new test would be added + True if the builder can create a test case from this method + + + + Build a Test from the provided MethodInfo. Depending on + whether the method takes arguments and on the availability + of test case data, this method may return a single test + or a group of tests contained in a ParameterizedMethodSuite. + + The method for which a test is to be built + The test fixture being populated, or null + A Test representing one or more method invocations + + + + Builds a ParameterizedMethodSuite containing individual test cases. + + The method for which a test is to be built. + The list of test cases to include. + A ParameterizedMethodSuite populated with test cases + + + + Build a simple, non-parameterized TestMethod for this method. + + The MethodInfo for which a test is to be built + The test suite for which the method is being built + A TestMethod. + + + + Abstract base class for operators that are able to reduce to a + constraint whether or not another syntactic element follows. + + + + + NUnitEqualityComparer encapsulates NUnit's handling of + equality tests between objects. + + + + + If true, all string comparisons will ignore case + + + + + If true, arrays will be treated as collections, allowing + those of different dimensions to be compared + + + + + Comparison objects used in comparisons for some constraints. + + + + + List of points at which a failure occurred. + + + + + Compares two objects for equality within a tolerance. + + + + + Helper method to compare two arrays + + + + + Method to compare two DirectoryInfo objects + + first directory to compare + second directory to compare + true if equivalent, false if not + + + + Returns the default NUnitEqualityComparer + + + + + Gets and sets a flag indicating whether case should + be ignored in determining equality. + + + + + Gets and sets a flag indicating that arrays should be + compared as collections, without regard to their shape. + + + + + Gets the list of external comparers to be used to + test for equality. They are applied to members of + collections, in place of NUnit's own logic. + + + + + Gets the list of failure points for the last Match performed. + The list consists of objects to be interpreted by the caller. + This generally means that the caller may only make use of + objects it has placed on the list at a particular depthy. + + + + + Flags the comparer to include + property in comparison of two values. + + + Using this modifier does not allow to use the + modifier. + + + + + FailurePoint class represents one point of failure + in an equality test. + + + + + The location of the failure + + + + + The expected value + + + + + The actual value + + + + + Indicates whether the expected value is valid + + + + + Indicates whether the actual value is valid + + + + + NullConstraint tests that the actual value is null + + + + + Initializes a new instance of the class. + + + + + Applies the constraint to an actual value, returning a ConstraintResult. + + The value to be tested + A ConstraintResult + + + + CollectionSubsetConstraint is used to determine whether + one collection is a subset of another + + + + + Construct a CollectionSubsetConstraint + + The collection that the actual value is expected to be a subset of + + + + Test whether the actual collection is a subset of + the expected collection provided. + + + + + + + Flag the constraint to use the supplied predicate function + + The comparison function to use. + Self. + + + + The display name of this Constraint for use by ToString(). + The default value is the name of the constraint with + trailing "Constraint" removed. Derived classes may set + this to another name in their constructors. + + + + + The Description of what this constraint tests, for + use in messages and in the ConstraintResult. + + + + + AndConstraint succeeds only if both members succeed. + + + + + BinaryConstraint is the abstract base of all constraints + that combine two other constraints in some fashion. + + + + + The first constraint being combined + + + + + The second constraint being combined + + + + + Construct a BinaryConstraint from two other constraints + + The first constraint + The second constraint + + + + Create an AndConstraint from two other constraints + + The first constraint + The second constraint + + + + Apply both member constraints to an actual value, succeeding + succeeding only if both of them succeed. + + The actual value + True if the constraints both succeeded + + + + Gets text describing a constraint + + + + + Contain the result of matching a against an actual value. + + + + + Constructs a for a particular . + + The Constraint to which this result applies. + The actual value to which the Constraint was applied. + + + + Constructs a for a particular . + + The Constraint to which this result applies. + The actual value to which the Constraint was applied. + The status of the new ConstraintResult. + + + + Constructs a for a particular . + + The Constraint to which this result applies. + The actual value to which the Constraint was applied. + If true, applies a status of Success to the result, otherwise Failure. + + + + Write the failure message to the MessageWriter provided + as an argument. The default implementation simply passes + the result and the actual value to the writer, which + then displays the constraint description and the value. + + Constraints that need to provide additional details, + such as where the error occured can override this. + + The MessageWriter on which to display the message + + + + Write the actual value for a failing constraint test to a + MessageWriter. The default implementation simply writes + the raw value of actual, leaving it to the writer to + perform any formatting. + + The writer on which the actual value is displayed + + + + The actual value that was passed to the method. + + + + + Gets and sets the ResultStatus for this result. + + + + + True if actual value meets the Constraint criteria otherwise false. + + + + + Display friendly name of the constraint. + + + + + Description of the constraint may be affected by the state the constraint had + when was performed against the actual value. + + + + + Write the actual value for a failing constraint test to a + MessageWriter. The default implementation simply writes + the raw value of actual, leaving it to the writer to + perform any formatting. + + The writer on which the actual value is displayed + + + + Attribute used to identify a method that is called after + all the tests in a fixture have run. The method is + guaranteed to be called, even if an exception is thrown. + + + + + Attribute used to identify a method that is called once + after all the child tests have run. The method is + guaranteed to be called, even if an exception is thrown. + + + + + PlatformAttribute is used to mark a test fixture or an + individual method as applying to a particular platform only. + + + + + Constructor with no platforms specified, for use + with named property syntax. + + + + + Constructor taking one or more platforms + + Comma-delimited list of platforms + + + + Causes a test to be skipped if this PlatformAttribute is not satisfied. + + The test to modify + + + + Attribute used to mark a test that is to be ignored. + Ignored tests result in a warning message when the + tests are run. + + + + + Constructs the attribute giving a reason for ignoring the test + GetActionsFromAttributeProvider + The reason for ignoring the test + + + + Modifies a test by marking it as Ignored. + + The test to modify + + + + + + + + + The date in the future to stop ignoring the test as a string in UTC time. + For example for a date and time, "2014-12-25 08:10:00Z" or for just a date, + "2014-12-25". If just a date is given, the Ignore will expire at midnight UTC. + + + Once the ignore until date has passed, the test will be marked + as runnable. Tests with an ignore until date will have an IgnoreUntilDate + property set which will appear in the test results. + + The string does not contain a valid string representation of a date and time. + + + + The IApplyToContext interface is implemented by attributes + that want to make changes to the execution context before + a test is run. + + + + + Apply changes to the execution context + + The execution context + + + + A SimpleWorkItem represents a single test case and is + marked as completed immediately upon execution. This + class is also used for skipped or ignored test suites. + + + + + Construct a simple work item for a test. + + The test to be executed + The filter used to select this test + + + + Method that performs actually performs the work. + + + + + ContextSettingsCommand applies specified changes to the + TestExecutionContext prior to running a test. No special + action is needed after the test runs, since the prior + context will be restored automatically. + + + + + Initializes a new instance of the class. + + + + + + + + + + + + + + + + + + + + The RunState enum indicates whether a test can be executed. + + + + + The test is not runnable. + + + + + The test is runnable. + + + + + The test can only be run explicitly + + + + + The test has been skipped. This value may + appear on a Test when certain attributes + are used to skip the test. + + + + + The test has been ignored. May appear on + a Test, when the IgnoreAttribute is used. + + + + + Helper class with properties and methods that supply + a number of constraints used in Asserts. + + + + + Returns a new CollectionContainsConstraint checking for the + presence of a particular object in the collection. + + + + + Returns a new ContainsConstraint. This constraint + will, in turn, make use of the appropriate second-level + constraint, depending on the type of the actual argument. + This overload is only used if the item sought is a string, + since any other type implies that we are looking for a + collection member. + + + + + Returns a constraint that succeeds if the actual + value starts with the substring supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value ends with the substring supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value matches the regular expression supplied as an argument. + + + + + Returns a ConstraintExpression that negates any + following constraint. + + + + + Returns a constraint that succeeds if the value + is a file or directory and it exists. + + + + + AssemblyHelper provides static methods for working + with assemblies. + + + + + Gets the path from which an assembly was loaded. + For builds where this is not possible, returns + the name of the assembly. + + The assembly. + The path. + + + + Gets the path to the directory from which an assembly was loaded. + + The assembly. + The path. + + + + Gets the AssemblyName of an assembly. + + The assembly + An AssemblyName + + + + Loads an assembly given a string, which may be the + path to the assembly or the AssemblyName + + + + + + + Gets the assembly path from code base. + + Public for testing purposes + The code base. + + + + + FrameworkController provides a facade for use in loading, browsing + and running tests without requiring a reference to the NUnit + framework. All calls are encapsulated in constructors for + this class and its nested classes, which only require the + types of the Common Type System as arguments. + + The controller supports four actions: Load, Explore, Count and Run. + They are intended to be called by a driver, which should allow for + proper sequencing of calls. Load must be called before any of the + other actions. The driver may support other actions, such as + reload on run, by combining these calls. + + + + + A MarshalByRefObject that lives forever + + + + + Obtains a lifetime service object to control the lifetime policy for this instance. + + + + + Construct a FrameworkController using the default builder and runner. + + The AssemblyName or path to the test assembly + A prefix used for all test ids created under this controller. + A Dictionary of settings to use in loading and running the tests + + + + Construct a FrameworkController using the default builder and runner. + + The test assembly + A prefix used for all test ids created under this controller. + A Dictionary of settings to use in loading and running the tests + + + + Construct a FrameworkController, specifying the types to be used + for the runner and builder. This constructor is provided for + purposes of development. + + The full AssemblyName or the path to the test assembly + A prefix used for all test ids created under this controller. + A Dictionary of settings to use in loading and running the tests + The Type of the test runner + The Type of the test builder + + + + Construct a FrameworkController, specifying the types to be used + for the runner and builder. This constructor is provided for + purposes of development. + + The test assembly + A prefix used for all test ids created under this controller. + A Dictionary of settings to use in loading and running the tests + The Type of the test runner + The Type of the test builder + + + + Loads the tests in the assembly + + + + + + Returns info about the tests in an assembly + + A string containing the XML representation of the filter to use + The XML result of exploring the tests + + + + Runs the tests in an assembly + + A string containing the XML representation of the filter to use + The XML result of the test run + + + + Runs the tests in an assembly syncronously reporting back the test results through the callback + or through the return value + + The callback that receives the test results + A string containing the XML representation of the filter to use + The XML result of the test run + + + + Runs the tests in an assembly asyncronously reporting back the test results through the callback + + The callback that receives the test results + A string containing the XML representation of the filter to use + + + + Stops the test run + + True to force the stop, false for a cooperative stop + + + + Counts the number of test cases in the loaded TestSuite + + A string containing the XML representation of the filter to use + The number of tests + + + + Inserts environment element + + Target node + The new node + + + + Inserts settings element + + Target node + Settings dictionary + The new node + + + + Gets the ITestAssemblyBuilder used by this controller instance. + + The builder. + + + + Gets the ITestAssemblyRunner used by this controller instance. + + The runner. + + + + Gets the AssemblyName or the path for which this FrameworkController was created + + + + + Gets the Assembly for which this + + + + + Gets a dictionary of settings for the FrameworkController + + + + + A shim of the .NET interface for platforms that do not support it. + Used to indicate that a control can be the target of a callback event on the server. + + + + + Processes a callback event that targets a control. + + + + + + Returns the results of a callback event that targets a control. + + + + + + FrameworkControllerAction is the base class for all actions + performed against a FrameworkController. + + + + + LoadTestsAction loads a test into the FrameworkController + + + + + LoadTestsAction loads the tests in an assembly. + + The controller. + The callback handler. + + + + ExploreTestsAction returns info about the tests in an assembly + + + + + Initializes a new instance of the class. + + The controller for which this action is being performed. + Filter used to control which tests are included (NYI) + The callback handler. + + + + CountTestsAction counts the number of test cases in the loaded TestSuite + held by the FrameworkController. + + + + + Construct a CountsTestAction and perform the count of test cases. + + A FrameworkController holding the TestSuite whose cases are to be counted + A string containing the XML representation of the filter to use + A callback handler used to report results + + + + RunTestsAction runs the loaded TestSuite held by the FrameworkController. + + + + + Construct a RunTestsAction and run all tests in the loaded TestSuite. + + A FrameworkController holding the TestSuite to run + A string containing the XML representation of the filter to use + A callback handler used to report results + + + + RunAsyncAction initiates an asynchronous test run, returning immediately + + + + + Construct a RunAsyncAction and run all tests in the loaded TestSuite. + + A FrameworkController holding the TestSuite to run + A string containing the XML representation of the filter to use + A callback handler used to report results + + + + StopRunAction stops an ongoing run. + + + + + Construct a StopRunAction and stop any ongoing run. If no + run is in process, no error is raised. + + The FrameworkController for which a run is to be stopped. + True the stop should be forced, false for a cooperative stop. + >A callback handler used to report results + A forced stop will cause threads and processes to be killed as needed. + + + + ExceptionTypeConstraint is a special version of ExactTypeConstraint + used to provided detailed info about the exception thrown in + an error message. + + + + + ExactTypeConstraint is used to test that an object + is of the exact type provided in the constructor + + + + + Construct an ExactTypeConstraint for a given Type + + The expected Type. + + + + Apply the constraint to an actual value, returning true if it succeeds + + The actual argument + True if the constraint succeeds, otherwise false. + + + + The display name of this Constraint for use by ToString(). + The default value is the name of the constraint with + trailing "Constraint" removed. Derived classes may set + this to another name in their constructors. + + + + + Constructs an ExceptionTypeConstraint + + + + + Applies the constraint to an actual value, returning a ConstraintResult. + + The value to be tested + A ConstraintResult + + + + TestProgressReporter translates ITestListener events into + the async callbacks that are used to inform the client + software about the progress of a test run. + + + + + Initializes a new instance of the class. + + The callback handler to be used for reporting progress. + + + + Called when a test has just started + + The test that is starting + + + + Called when a test has finished. Sends a result summary to the callback. + to + + The result of the test + + + + Called when a test produces output for immediate display + + A TestOutput object containing the text to display + + + + Returns the parent test item for the targer test item if it exists + + + parent test item + + + + Makes a string safe for use as an attribute, replacing + characters characters that can't be used with their + corresponding xml representations. + + The string to be used + A new string with the _values replaced + + + + Operator used to test for the presence of a named Property + on an object and optionally apply further tests to the + value of that property. + + + + + Constructs a PropOperator for a particular named property + + + + + Reduce produces a constraint from the operator and + any arguments. It takes the arguments from the constraint + stack and pushes the resulting constraint on it. + + + + + + Gets the name of the property to which the operator applies + + + + + NaNConstraint tests that the actual value is a double or float NaN + + + + + Test that the actual value is an NaN + + + + + + + The Description of what this constraint tests, for + use in messages and in the ConstraintResult. + + + + + CollectionContainsConstraint is used to test whether a collection + contains an expected object as a member. + + + + + Construct a CollectionContainsConstraint + + + + + + Test whether the expected item is contained in the collection + + + + + + + Flag the constraint to use the supplied predicate function + + The comparison function to use. + Self. + + + + The display name of this Constraint for use by ToString(). + The default value is the name of the constraint with + trailing "Constraint" removed. Derived classes may set + this to another name in their constructors. + + + + + The Description of what this constraint tests, for + use in messages and in the ConstraintResult. + + + + + Gets the expected object + + + + + Attribute used to mark a class that contains one-time SetUp + and/or TearDown methods that apply to all the tests in a + namespace or an assembly. + + + + + Attribute used to mark a class that contains one-time SetUp + and/or TearDown methods that apply to all the tests in a + namespace or an assembly. + + + + + Attribute used to mark a class that contains one-time SetUp + and/or TearDown methods that apply to all the tests in a + namespace or an assembly. + + + + + RepeatAttribute may be applied to test case in order + to run it multiple times. + + + + + Construct a RepeatAttribute + + The number of times to run the test + + + + Wrap a command and return the result. + + The command to be wrapped + The wrapped command + + + + The test command for the RepeatAttribute + + + + + Initializes a new instance of the class. + + The inner command. + The number of repetitions + + + + Runs the test, saving a TestResult in the supplied TestExecutionContext. + + The context in which the test should run. + A TestResult + + + + A simplified implementation of .NET 4 CountdownEvent + for use in earlier versions of .NET. Only the methods + used by NUnit are implemented. + + + + + Construct a CountdownEvent + + The initial count + + + + Decrement the count by one + + + + + Block the thread until the count reaches zero + + + + + Gets the initial count established for the CountdownEvent + + + + + Gets the current count remaining for the CountdownEvent + + + + + TheoryResultCommand adjusts the result of a Theory so that + it fails if all the results were inconclusive. + + + + + Constructs a TheoryResultCommand + + The command to be wrapped by this one + + + + Overridden to call the inner command and adjust the result + in case all chlid results were inconclusive. + + + + + + + NUnitTestCaseBuilder is a utility class used by attributes + that build test cases. + + + + + Constructs an + + + + + Builds a single NUnitTestMethod, either as a child of the fixture + or as one of a set of test cases under a ParameterizedTestMethodSuite. + + The MethodInfo from which to construct the TestMethod + The suite or fixture to which the new test will be added + The ParameterSet to be used, or null + + + + + Helper method that checks the signature of a TestMethod and + any supplied parameters to determine if the test is valid. + + Currently, NUnitTestMethods are required to be public, + non-abstract methods, either static or instance, + returning void. They may take arguments but the _values must + be provided or the TestMethod is not considered runnable. + + Methods not meeting these criteria will be marked as + non-runnable and the method will return false in that case. + + The TestMethod to be checked. If it + is found to be non-runnable, it will be modified. + Parameters to be used for this test, or null + True if the method signature is valid, false if not + + The return value is no longer used internally, but is retained + for testing purposes. + + + + + The TestStatus enum indicates the result of running a test + + + + + The test was inconclusive + + + + + The test has skipped + + + + + The test succeeded + + + + + The test failed + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + TestNameGenerator is able to create test names according to + a coded pattern. + + + + + Default pattern used to generate names + + + + + Construct a TestNameGenerator + + + + + Construct a TestNameGenerator + + The pattern used by this generator. + + + + Get the display name for a TestMethod and it's arguments + + A TestMethod + The display name + + + + Get the display name for a TestMethod and it's arguments + + A TestMethod + Arguments to be used + The display name + + + + The EqualConstraintResult class is tailored for formatting + and displaying the result of an EqualConstraint. + + + + + Construct an EqualConstraintResult + + + + + Write a failure message. Overridden to provide custom + failure messages for EqualConstraint. + + The MessageWriter to write to + + + + Display the failure information for two collections that did not match. + + The MessageWriter on which to display + The expected collection. + The actual collection + The depth of this failure in a set of nested collections + + + + Displays a single line showing the types and sizes of the expected + and actual collections or arrays. If both are identical, the value is + only shown once. + + The MessageWriter on which to display + The expected collection or array + The actual collection or array + The indentation level for the message line + + + + Displays a single line showing the point in the expected and actual + arrays at which the comparison failed. If the arrays have different + structures or dimensions, both _values are shown. + + The MessageWriter on which to display + The expected array + The actual array + Index of the failure point in the underlying collections + The indentation level for the message line + + + + Display the failure information for two IEnumerables that did not match. + + The MessageWriter on which to display + The expected enumeration. + The actual enumeration + The depth of this failure in a set of nested collections + + + + Provides NUnit specific extensions to aid in Reflection + across multiple frameworks + + + This version of the class supplies GetTypeInfo() on platforms + that don't support it. + + + + + GetTypeInfo gives access to most of the Type information we take for granted + on .NET Core and Windows Runtime. Rather than #ifdef different code for different + platforms, it is easiest to just code all platforms as if they worked this way, + thus the simple passthrough. + + + + + + + Extensions for Assembly that are not available in pre-4.5 .NET releases + + + + + An easy way to get a single custom attribute from an assembly + + The attribute Type + The assembly + An attribute of Type T + + + + Type extensions that apply to all target frameworks + + + + + Determines if the given array is castable/matches the array. + + + + + + + + Determines if one type can be implicitly converted from another + + + + + + + + This class is used as a flag when we get a parameter list for a method/constructor, but + we do not know one of the types because null was passed in. + + + + + The TestCaseData class represents a set of arguments + and other parameter info to be used for a parameterized + test case. It is derived from TestCaseParameters and adds a + fluent syntax for use in initializing the test case. + + + + + The TestCaseParameters class encapsulates method arguments and + other selected parameters needed for constructing + a parameterized test case. + + + + + TestParameters is the abstract base class for all classes + that know how to provide data for constructing a test. + + + + + Default Constructor creates an empty parameter set + + + + + Construct a parameter set with a list of arguments + + + + + + Construct a non-runnable ParameterSet, specifying + the provider exception that made it invalid. + + + + + Construct a ParameterSet from an object implementing ITestData + + + + + + Applies ParameterSet _values to the test itself. + + A test. + + + + The RunState for this set of parameters. + + + + + The arguments to be used in running the test, + which must match the method signature. + + + + + A name to be used for this test case in lieu + of the standard generated name containing + the argument list. + + + + + Gets the property dictionary for this test + + + + + The original arguments provided by the user, + used for display purposes. + + + + + The expected result to be returned + + + + + Default Constructor creates an empty parameter set + + + + + Construct a non-runnable ParameterSet, specifying + the provider exception that made it invalid. + + + + + Construct a parameter set with a list of arguments + + + + + + Construct a ParameterSet from an object implementing ITestCaseData + + + + + + The expected result of the test, which + must match the method return type. + + + + + Gets a value indicating whether an expected result was specified. + + + + + Initializes a new instance of the class. + + The arguments. + + + + Initializes a new instance of the class. + + The argument. + + + + Initializes a new instance of the class. + + The first argument. + The second argument. + + + + Initializes a new instance of the class. + + The first argument. + The second argument. + The third argument. + + + + Sets the expected result for the test + + The expected result + A modified TestCaseData + + + + Sets the name of the test case + + The modified TestCaseData instance + + + + Sets the description for the test case + being constructed. + + The description. + The modified TestCaseData instance. + + + + Applies a category to the test + + + + + + + Applies a named property to the test + + + + + + + + Applies a named property to the test + + + + + + + + Applies a named property to the test + + + + + + + + Marks the test case as explicit. + + + + + Marks the test case as explicit, specifying the reason. + + + + + Ignores this TestCase, specifying the reason. + + The reason. + + + + + + + + + + + + + + + + + + + + + Gets or sets the current test + + + + + The time the current test started execution + + + + + The time the current test started in Ticks + + + + + Gets or sets the current test result + + + + + Gets a TextWriter that will send output to the current test result. + + + + + The current test object - that is the user fixture + object on which tests are being executed. + + + + + Get or set the working directory + + + + + Get or set indicator that run should stop on the first error + + + + + Gets an enum indicating whether a stop has been requested. + + + + + The current WorkItemDispatcher. Made public for + use by nunitlite.tests + + + + + The ParallelScope to be used by tests running in this context. + For builds with out the parallel feature, it has no effect. + + + + + The unique name of the worker that spawned the context. + For builds with out the parallel feature, it is null. + + + + + Gets the RandomGenerator specific to this Test + + + + + Gets or sets the test case timeout value + + + + + Gets a list of ITestActions set by upstream tests + + + + + Saves or restores the CurrentCulture + + + + + Saves or restores the CurrentUICulture + + + + + The current head of the ValueFormatter chain, copied from MsgUtils.ValueFormatter + + + + + If true, all tests must run on the same thread. No new thread may be spawned. + + + + + Helper class used to save and restore certain static or + singleton settings in the environment that affect tests + or which might be changed by the user tests. + + An internal class is used to hold settings and a stack + of these objects is pushed and popped as Save and Restore + are called. + + + + + Link to a prior saved context + + + + + Indicates that a stop has been requested + + + + + The event listener currently receiving notifications + + + + + The number of assertions for the current test + + + + + The current culture + + + + + The current UI culture + + + + + The current test result + + + + + The current Principal. + + + + + Initializes a new instance of the class. + + + + + Initializes a new instance of the class. + + An existing instance of TestExecutionContext. + + + + Get the current context or return null if none is found. + + + + + + Clear the current context. This is provided to + prevent "leakage" of the CallContext containing + the current context back to any runners. + + + + + Record any changes in the environment made by + the test code in the execution context so it + will be passed on to lower level tests. + + + + + Set up the execution environment to match a context. + Note that we may be running on the same thread where the + context was initially created or on a different thread. + + + + + Increments the assert count by one. + + + + + Increments the assert count by a specified amount. + + + + + Adds a new ValueFormatterFactory to the chain of formatters + + The new factory + + + + Obtain lifetime service object + + + + + + Gets and sets the current context. + + + + + Gets or sets the current test + + + + + The time the current test started execution + + + + + The time the current test started in Ticks + + + + + Gets or sets the current test result + + + + + Gets a TextWriter that will send output to the current test result. + + + + + The current test object - that is the user fixture + object on which tests are being executed. + + + + + Get or set the working directory + + + + + Get or set indicator that run should stop on the first error + + + + + Gets an enum indicating whether a stop has been requested. + + + + + The current test event listener + + + + + The current WorkItemDispatcher. Made public for + use by nunitlite.tests + + + + + The ParallelScope to be used by tests running in this context. + For builds with out the parallel feature, it has no effect. + + + + + The unique name of the worker that spawned the context. + For builds with out the parallel feature, it is null. + + + + + Gets the RandomGenerator specific to this Test + + + + + Gets the assert count. + + The assert count. + + + + Gets or sets the test case timeout value + + + + + Gets a list of ITestActions set by upstream tests + + + + + Saves or restores the CurrentCulture + + + + + Saves or restores the CurrentUICulture + + + + + Gets or sets the current for the Thread. + + + + + The current head of the ValueFormatter chain, copied from MsgUtils.ValueFormatter + + + + + If true, all tests must run on the same thread. No new thread may be spawned. + + + + + Thrown when a test executes inconclusively. + + + + + Abstract base for Exceptions that terminate a test and provide a ResultState. + + + + The error message that explains + the reason for the exception + + + The error message that explains + the reason for the exception + The exception that caused the + current exception + + + + Serialization Constructor + + + + + Gets the ResultState provided by this exception + + + + The error message that explains + the reason for the exception + + + The error message that explains + the reason for the exception + The exception that caused the + current exception + + + + Serialization Constructor + + + + + Gets the ResultState provided by this exception + + + + + Helper class with properties and methods that supply + a number of constraints used in Asserts. + + + + + Returns a new CollectionContainsConstraint checking for the + presence of a particular object in the collection. + + + + + Returns a new DictionaryContainsKeyConstraint checking for the + presence of a particular key in the dictionary. + + + + + Returns a new DictionaryContainsValueConstraint checking for the + presence of a particular value in the dictionary. + + + + + Returns a constraint that succeeds if the actual + value contains the substring supplied as an argument. + + + + + EqualConstraint is able to compare an actual value with the + expected value provided in its constructor. Two objects are + considered equal if both are null, or if both have the same + value. NUnit has special semantics for some object types. + + + + + NUnitEqualityComparer used to test equality. + + + + + Initializes a new instance of the class. + + The expected value. + + + + Flag the constraint to use a tolerance when determining equality. + + Tolerance value to be used + Self. + + + + Flag the constraint to use the supplied IComparer object. + + The IComparer object to use. + Self. + + + + Flag the constraint to use the supplied IComparer object. + + The IComparer object to use. + Self. + + + + Flag the constraint to use the supplied Comparison object. + + The IComparer object to use. + Self. + + + + Flag the constraint to use the supplied IEqualityComparer object. + + The IComparer object to use. + Self. + + + + Flag the constraint to use the supplied IEqualityComparer object. + + The IComparer object to use. + Self. + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for success, false for failure + + + + Gets the tolerance for this comparison. + + + The tolerance. + + + + + Gets a value indicating whether to compare case insensitive. + + + true if comparing case insensitive; otherwise, false. + + + + + Gets a value indicating whether or not to clip strings. + + + true if set to clip strings otherwise, false. + + + + + Gets the failure points. + + + The failure points. + + + + + Flag the constraint to ignore case and return self. + + + + + Flag the constraint to suppress string clipping + and return self. + + + + + Flag the constraint to compare arrays as collections + and return self. + + + + + Flags the constraint to include + property in comparison of two values. + + + Using this modifier does not allow to use the + constraint modifier. + + + + + Switches the .Within() modifier to interpret its tolerance as + a distance in representable _values (see remarks). + + Self. + + Ulp stands for "unit in the last place" and describes the minimum + amount a given value can change. For any integers, an ulp is 1 whole + digit. For floating point _values, the accuracy of which is better + for smaller numbers and worse for larger numbers, an ulp depends + on the size of the number. Using ulps for comparison of floating + point results instead of fixed tolerances is safer because it will + automatically compensate for the added inaccuracy of larger numbers. + + + + + Switches the .Within() modifier to interpret its tolerance as + a percentage that the actual _values is allowed to deviate from + the expected value. + + Self + + + + Causes the tolerance to be interpreted as a TimeSpan in days. + + Self + + + + Causes the tolerance to be interpreted as a TimeSpan in hours. + + Self + + + + Causes the tolerance to be interpreted as a TimeSpan in minutes. + + Self + + + + Causes the tolerance to be interpreted as a TimeSpan in seconds. + + Self + + + + Causes the tolerance to be interpreted as a TimeSpan in milliseconds. + + Self + + + + Causes the tolerance to be interpreted as a TimeSpan in clock ticks. + + Self + + + + The Description of what this constraint tests, for + use in messages and in the ConstraintResult. + + + + + Applies a delay to the match so that a match can be evaluated in the future. + + + + + Creates a new DelayedConstraint + + The inner constraint to decorate + The time interval after which the match is performed + If the value of is less than 0 + + + + Creates a new DelayedConstraint + + The inner constraint to decorate + The time interval after which the match is performed, in milliseconds + The time interval used for polling, in milliseconds + If the value of is less than 0 + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for if the base constraint fails, false if it succeeds + + + + Test whether the constraint is satisfied by a delegate + + The delegate whose value is to be tested + A ConstraintResult + + + + Test whether the constraint is satisfied by a given reference. + Overridden to wait for the specified delay period before + calling the base constraint with the dereferenced value. + + A reference to the value to be tested + True for success, false for failure + + + + Returns the string representation of the constraint. + + + + + Adjusts a Timestamp by a given TimeSpan + + + + + + + + Returns the difference between two Timestamps as a TimeSpan + + + + + + + + Gets text describing a constraint + + + + + CollectionOrderedConstraint is used to test whether a collection is ordered. + + + + + Construct a CollectionOrderedConstraint + + + + + Modifies the constraint to use an and returns self. + + + + + Modifies the constraint to use an and returns self. + + + + + Modifies the constraint to use a and returns self. + + + + + Modifies the constraint to test ordering by the value of + a specified property and returns self. + + + + + Test whether the collection is ordered + + + + + + + Returns the string representation of the constraint. + + + + + + The display name of this Constraint for use by ToString(). + The default value is the name of the constraint with + trailing "Constraint" removed. Derived classes may set + this to another name in their constructors. + + + + + If used performs a default ascending comparison + + + + + If used performs a reverse comparison + + + + + Then signals a break between two ordering steps + + + + + The Description of what this constraint tests, for + use in messages and in the ConstraintResult. + + + + + An OrderingStep represents one stage of the sort + + + + + Attribute used to provide descriptive text about a + test case or fixture. + + + + + Construct a description Attribute + + The text of the description + + + + InvalidTestFixtureException is thrown when an appropriate test + fixture constructor using the provided arguments cannot be found. + + + + + Initializes a new instance of the class. + + + + + Initializes a new instance of the class. + + The message. + + + + Initializes a new instance of the class. + + The message. + The inner. + + + + Serialization Constructor + + + + + A CompositeWorkItem represents a test suite and + encapsulates the execution of the suite as well + as all its child tests. + + + + + A count of how many tests in the work item have a value for the Order Property + + + + + Construct a CompositeWorkItem for executing a test suite + using a filter to select child tests. + + The TestSuite to be executed + A filter used to select child tests + + + + Method that actually performs the work. Overridden + in CompositeWorkItem to do setup, run all child + items and then do teardown. + + + + + Sorts tests under this suite. + + + + + Cancel (abort or stop) a CompositeWorkItem and all of its children + + true if the CompositeWorkItem and all of its children should be aborted, false if it should allow all currently running tests to complete + + + + List of Child WorkItems + + + + + Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other. + + + A signed integer that indicates the relative values of and , as shown in the following table.Value Meaning Less than zero is less than .Zero equals .Greater than zero is greater than . + + The first object to compare.The second object to compare. + + + + The ISimpleTestBuilder interface is exposed by a class that knows how to + build a single TestMethod from a suitable MethodInfo Types. In general, + it is exposed by an attribute, but may be implemented in a helper class + used by the attribute in some cases. + + + + + Build a TestMethod from the provided MethodInfo. + + The method to be used as a test + The TestSuite to which the method will be added + A TestMethod object + + + + The TypeWrapper class wraps a Type so it may be used in + a platform-independent manner. + + + + + Construct a TypeWrapper for a specified Type. + + + + + Returns true if the Type wrapped is T + + + + + Get the display name for this type + + + + + Get the display name for an object of this type, constructed with the specified args. + + + + + Returns a new ITypeInfo representing an instance of this generic Type using the supplied Type arguments + + + + + Returns a Type representing a generic type definition from which this Type can be constructed. + + + + + Returns an array of custom attributes of the specified type applied to this type + + + + + Returns a value indicating whether the type has an attribute of the specified type. + + + + + + + + Returns a flag indicating whether this type has a method with an attribute of the specified type. + + + + + + + Returns an array of IMethodInfos for methods of this Type + that match the specified flags. + + + + + Gets the public constructor taking the specified argument Types + + + + + Returns a value indicating whether this Type has a public constructor taking the specified argument Types. + + + + + Construct an object of this Type, using the specified arguments. + + + + + Override ToString() so that error messages in NUnit's own tests make sense + + + + + Gets the underlying Type on which this TypeWrapper is based. + + + + + Gets the base type of this type as an ITypeInfo + + + + + Gets the Name of the Type + + + + + Gets the FullName of the Type + + + + + Gets the assembly in which the type is declared + + + + + Gets the namespace of the Type + + + + + Gets a value indicating whether the type is abstract. + + + + + Gets a value indicating whether the Type is a generic Type + + + + + Gets a value indicating whether the Type has generic parameters that have not been replaced by specific Types. + + + + + Gets a value indicating whether the Type is a generic Type definition + + + + + Gets a value indicating whether the type is sealed. + + + + + Gets a value indicating whether this type represents a static class. + + + + + DictionaryContainsValueConstraint is used to test whether a dictionary + contains an expected object as a value. + + + + + Construct a DictionaryContainsValueConstraint + + + + + + Test whether the expected value is contained in the dictionary + + + + + The display name of this Constraint for use by ToString(). + The default value is the name of the constraint with + trailing "Constraint" removed. Derived classes may set + this to another name in their constructors. + + + + + The Description of what this constraint tests, for + use in messages and in the ConstraintResult. + + + + + TestCaseSourceAttribute indicates the source to be used to + provide test fixture instances for a test class. + + + + + Error message string is public so the tests can use it + + + + + Construct with the name of the method, property or field that will provide data + + The name of a static method, property or field that will provide data. + + + + Construct with a Type and name + + The Type that will provide data + The name of a static method, property or field that will provide data. + + + + Construct with a Type + + The type that will provide data + + + + Construct one or more TestFixtures from a given Type, + using available parameter data. + + The TypeInfo for which fixures are to be constructed. + One or more TestFixtures as TestSuite + + + + Returns a set of ITestFixtureData items for use as arguments + to a parameterized test fixture. + + The type for which data is needed. + + + + + The name of a the method, property or fiend to be used as a source + + + + + A Type to be used as a source + + + + + Gets or sets the category associated with every fixture created from + this attribute. May be a single category or a comma-separated list. + + + + + Attribute used to identify a method that is called once + to perform setup before any child tests are run. + + + + + Provides the Author of a test or test fixture. + + + + + Initializes a new instance of the class. + + The name of the author. + + + + Initializes a new instance of the class. + + The name of the author. + The email address of the author. + + + + The different targets a test action attribute can be applied to + + + + + Default target, which is determined by where the action attribute is attached + + + + + Target a individual test case + + + + + Target a suite of test cases + + + + + TestListener provides an implementation of ITestListener that + does nothing. It is used only through its NULL property. + + + + + Called when a test has just started + + The test that is starting + + + + Called when a test case has finished + + The result of the test + + + + Called when a test produces output for immediate display + + A TestOutput object containing the text to display + + + + Construct a new TestListener - private so it may not be used. + + + + + Get a listener that does nothing + + + + + PlatformHelper class is used by the PlatformAttribute class to + determine whether a platform is supported. + + + + + Comma-delimited list of all supported OS platform constants + + + + + Comma-delimited list of all supported Runtime platform constants + + + + + Default constructor uses the operating system and + common language runtime of the system. + + + + + Construct a PlatformHelper for a particular operating + system and common language runtime. Used in testing. + + OperatingSystem to be used + RuntimeFramework to be used + + + + Test to determine if one of a collection of platforms + is being used currently. + + + + + + + Tests to determine if the current platform is supported + based on a platform attribute. + + The attribute to examine + + + + + Tests to determine if the current platform is supported + based on a platform attribute. + + The attribute to examine + + + + + Test to determine if the a particular platform or comma- + delimited set of platforms is in use. + + Name of the platform or comma-separated list of platform ids + True if the platform is in use on the system + + + + Return the last failure reason. Results are not + defined if called before IsSupported( Attribute ) + is called. + + + + + DefaultTestAssemblyBuilder loads a single assembly and builds a TestSuite + containing test fixtures present in the assembly. + + + + + The default suite builder used by the test assembly builder. + + + + + Initializes a new instance of the class. + + + + + Build a suite of tests from a provided assembly + + The assembly from which tests are to be built + A dictionary of options to use in building the suite + + A TestSuite containing the tests found in the assembly + + + + + Build a suite of tests given the filename of an assembly + + The filename of the assembly from which tests are to be built + A dictionary of options to use in building the suite + + A TestSuite containing the tests found in the assembly + + + + + Helper class with properties and methods that supply + a number of constraints used in Asserts. + + + + + Returns a ConstraintExpression, which will apply + the following constraint to all members of a collection, + succeeding only if a specified number of them succeed. + + + + + Returns a new PropertyConstraintExpression, which will either + test for the existence of the named property on the object + being tested or apply any following constraint to that property. + + + + + Returns a new AttributeConstraint checking for the + presence of a particular attribute on an object. + + + + + Returns a new AttributeConstraint checking for the + presence of a particular attribute on an object. + + + + + Returns a new CollectionContainsConstraint checking for the + presence of a particular object in the collection. + + + + + Returns a ConstraintExpression that negates any + following constraint. + + + + + Returns a ConstraintExpression, which will apply + the following constraint to all members of a collection, + succeeding if all of them succeed. + + + + + Returns a ConstraintExpression, which will apply + the following constraint to all members of a collection, + succeeding if at least one of them succeeds. + + + + + Returns a ConstraintExpression, which will apply + the following constraint to all members of a collection, + succeeding if all of them fail. + + + + + Returns a new ConstraintExpression, which will apply the following + constraint to the Length property of the object being tested. + + + + + Returns a new ConstraintExpression, which will apply the following + constraint to the Count property of the object being tested. + + + + + Returns a new ConstraintExpression, which will apply the following + constraint to the Message property of the object being tested. + + + + + Returns a new ConstraintExpression, which will apply the following + constraint to the InnerException property of the object being tested. + + + + + EmptyConstraint tests a whether a string or collection is empty, + postponing the decision about which test is applied until the + type of the actual argument is known. + + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for success, false for failure + + + + The Description of what this constraint tests, for + use in messages and in the ConstraintResult. + + + + + ComparisonAdapter class centralizes all comparisons of + _values in NUnit, adapting to the use of any provided + , + or . + + + + + Returns a ComparisonAdapter that wraps an + + + + + Returns a ComparisonAdapter that wraps an + + + + + Returns a ComparisonAdapter that wraps a + + + + + Compares two objects + + + + + Gets the default ComparisonAdapter, which wraps an + NUnitComparer object. + + + + + Construct a ComparisonAdapter for an + + + + + Compares two objects + + + + + + + + Construct a default ComparisonAdapter + + + + + ComparerAdapter extends and + allows use of an or + to actually perform the comparison. + + + + + Construct a ComparisonAdapter for an + + + + + Compare a Type T to an object + + + + + Construct a ComparisonAdapter for a + + + + + Compare a Type T to an object + + + + + AssignableFromConstraint is used to test that an object + can be assigned from a given Type. + + + + + Construct an AssignableFromConstraint for the type provided + + + + + + Apply the constraint to an actual value, returning true if it succeeds + + The actual argument + True if the constraint succeeds, otherwise false. + + + + Marks a test to use a Sequential join of any argument + data provided. Arguments will be combined into test cases, + taking the next value of each argument until all are used. + + + + + Default constructor + + + + + RangeAttribute is used to supply a range of _values to an + individual parameter of a parameterized test. + + + + + Construct a range of ints using default step of 1 + + + + + + + Construct a range of ints specifying the step size + + + + + + + + Construct a range of unsigned ints using default step of 1 + + + + + + + Construct a range of unsigned ints specifying the step size + + + + + + + + Construct a range of longs using a default step of 1 + + + + + + + Construct a range of longs + + + + + + + + Construct a range of unsigned longs using default step of 1 + + + + + + + Construct a range of unsigned longs specifying the step size + + + + + + + + Construct a range of doubles + + + + + + + + Construct a range of floats + + + + + + + + Used to mark a field, property or method providing a set of datapoints to + be used in executing any theories within the same fixture that require an + argument of the Type provided. The data source may provide an array of + the required Type or an . + Synonymous with DatapointsAttribute. + + + + + StackFilter class is used to remove internal NUnit + entries from a stack trace so that the resulting + trace provides better information about the test. + + + + + Filters a raw stack trace and returns the result. + + The original stack trace + A filtered stack trace + + + + A utility class to create TestCommands + + + + + Gets the command to be executed before any of + the child tests are run. + + A TestCommand + + + + Gets the command to be executed after all of the + child tests are run. + + A TestCommand + + + + Creates a test command for use in running this test. + + + + + + Creates a command for skipping a test. The result returned will + depend on the test RunState. + + + + + Builds the set up tear down list. + + Type of the fixture. + Type of the set up attribute. + Type of the tear down attribute. + A list of SetUpTearDownItems + + + + The ParameterWrapper class wraps a ParameterInfo so that it may + be used in a platform-independent manner. + + + + + The IParameterInfo interface is an abstraction of a .NET parameter. + + + + + Gets a value indicating whether the parameter is optional + + + + + Gets an IMethodInfo representing the method for which this is a parameter + + + + + Gets the underlying .NET ParameterInfo + + + + + Gets the Type of the parameter + + + + + Construct a ParameterWrapper for a given method and parameter + + + + + + + Returns an array of custom attributes of the specified type applied to this method + + + + + Gets a value indicating whether one or more attributes of the specified type are defined on the parameter. + + + + + Gets a value indicating whether the parameter is optional + + + + + Gets an IMethodInfo representing the method for which this is a parameter. + + + + + Gets the underlying ParameterInfo + + + + + Gets the Type of the parameter + + + + + A trace listener that writes to a separate file per domain + and process using it. + + + + + Construct an InternalTraceWriter that writes to a file. + + Path to the file to use + + + + Construct an InternalTraceWriter that writes to a + TextWriter provided by the caller. + + + + + + Writes a character to the text string or stream. + + The character to write to the text stream. + + + + Writes a string to the text string or stream. + + The string to write. + + + + Writes a string followed by a line terminator to the text string or stream. + + The string to write. If is null, only the line terminator is written. + + + + Releases the unmanaged resources used by the and optionally releases the managed resources. + + true to release both managed and unmanaged resources; false to release only unmanaged resources. + + + + Clears all buffers for the current writer and causes any buffered data to be written to the underlying device. + + + + + Returns the character encoding in which the output is written. + + The character encoding in which the output is written. + + + + FullName filter selects tests based on their FullName + + + + + Construct a MethodNameFilter for a single name + + The name the filter will recognize. + + + + Match a test against a single value. + + + + + Gets the element name + + Element name + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Provides a platform-independent methods for getting attributes + for use by AttributeConstraint and AttributeExistsConstraint. + + + + + Gets the custom attributes from the given object. + + Portable libraries do not have an ICustomAttributeProvider, so we need to cast to each of + it's direct subtypes and try to get attributes off those instead. + The actual. + Type of the attribute. + if set to true [inherit]. + A list of the given attribute on the given object. + + + + The SpecialValue enum is used to represent TestCase arguments + that cannot be used as arguments to an Attribute. + + + + + Null represents a null value, which cannot be used as an + argument to an attriute under .NET 1.x + + + + + TypeHelper provides static methods that operate on Types. + + + + + A special value, which is used to indicate that BestCommonType() method + was unable to find a common type for the specified arguments. + + + + + Gets the display name for a Type as used by NUnit. + + The Type for which a display name is needed. + The display name for the Type + + + + Gets the display name for a Type as used by NUnit. + + The Type for which a display name is needed. + The arglist provided. + The display name for the Type + + + + Returns the best fit for a common type to be used in + matching actual arguments to a methods Type parameters. + + The first type. + The second type. + Either type1 or type2, depending on which is more general. + + + + Determines whether the specified type is numeric. + + The type to be examined. + + true if the specified type is numeric; otherwise, false. + + + + + Convert an argument list to the required parameter types. + Currently, only widening numeric conversions are performed. + + An array of args to be converted + A ParameterInfo[] whose types will be used as targets + + + + Determines whether this instance can deduce type args for a generic type from the supplied arguments. + + The type to be examined. + The arglist. + The type args to be used. + + true if this the provided args give sufficient information to determine the type args to be used; otherwise, false. + + + + + Gets the _values for an enumeration, using Enum.GetTypes + where available, otherwise through reflection. + + + + + + + Gets the ids of the _values for an enumeration, + using Enum.GetNames where available, otherwise + through reflection. + + + + + + + ThreadUtility provides a set of static methods convenient + for working with threads. + + + + + Do our best to Kill a thread + + The thread to kill + + + + Do our best to kill a thread, passing state info + + The thread to kill + Info for the ThreadAbortException handler + + + + TestFixture is a surrogate for a user test fixture class, + containing one or more tests. + + + + + Any ITest that implements this interface is at a level that the implementing + class should be disposed at the end of the test run + + + + + Initializes a new instance of the class. + + Type of the fixture. + + + + Predicate constraint wraps a Predicate in a constraint, + returning success if the predicate is true. + + + + + Construct a PredicateConstraint from a predicate + + + + + Determines whether the predicate succeeds when applied + to the actual value. + + + + + Gets text describing a constraint + + + + + NotConstraint negates the effect of some other constraint + + + + + Initializes a new instance of the class. + + The base constraint to be negated. + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for if the base constraint fails, false if it succeeds + + + + Custom value formatter function + + The value + + + + + Custom value formatter factory function + + The next formatter function + ValueFormatter + If the given formatter is unable to handle a certain format, it must call the next formatter in the chain + + + + Static methods used in creating messages + + + + + Static string used when strings are clipped + + + + + Formatting strings used for expected and actual _values + + + + + Add a formatter to the chain of responsibility. + + + + + + Formats text to represent a generalized value. + + The value + The formatted text + + + + Formats text for a collection value, + starting at a particular point, to a max length + + The collection containing elements to write. + The starting point of the elements to write + The maximum number of elements to write + + + + Returns the representation of a type as used in NUnitLite. + This is the same as Type.ToString() except for arrays, + which are displayed with their declared sizes. + + + + + + + Converts any control characters in a string + to their escaped representation. + + The string to be converted + The converted string + + + + Converts any null characters in a string + to their escaped representation. + + The string to be converted + The converted string + + + + Return the a string representation for a set of indices into an array + + Array of indices for which a string is needed + + + + Get an array of indices representing the point in a collection or + array corresponding to a single int index into the collection. + + The collection to which the indices apply + Index in the collection + Array of indices + + + + Clip a string to a given length, starting at a particular offset, returning the clipped + string with ellipses representing the removed parts + + The string to be clipped + The maximum permitted length of the result string + The point at which to start clipping + The clipped string + + + + Clip the expected and actual strings in a coordinated fashion, + so that they may be displayed together. + + + + + + + + + Shows the position two strings start to differ. Comparison + starts at the start index. + + The expected string + The actual string + The index in the strings at which comparison should start + Boolean indicating whether case should be ignored + -1 if no mismatch found, or the index where mismatch found + + + + Current head of chain of value formatters. Public for testing. + + + + + Adding this attribute to a method within a + class makes the method callable from the NUnit test runner. There is a property + called Description which is optional which you can provide a more detailed test + description. This class cannot be inherited. + + + + [TestFixture] + public class Fixture + { + [Test] + public void MethodToTest() + {} + + [Test(Description = "more detailed description")] + public void TestDescriptionMethod() + {} + } + + + + + + Construct the attribute, specifying a combining strategy and source of parameter data. + + + + + Enumeration indicating whether the tests are + running normally or being cancelled. + + + + + Running normally with no stop requested + + + + + A graceful stop has been requested + + + + + A forced stop has been requested + + + + + The TestCaseParameters class encapsulates method arguments and + other selected parameters needed for constructing + a parameterized test case. + + + + + Default Constructor creates an empty parameter set + + + + + Construct a non-runnable ParameterSet, specifying + the provider exception that made it invalid. + + + + + Construct a parameter set with a list of arguments + + + + + + Construct a ParameterSet from an object implementing ITestCaseData + + + + + + Type arguments used to create a generic fixture instance + + + + + Provides methods to support legacy string comparison methods. + + + + + Compares two strings for equality, ignoring case if requested. + + The first string. + The second string.. + if set to true, the case of the letters in the strings is ignored. + Zero if the strings are equivalent, a negative number if strA is sorted first, a positive number if + strB is sorted first + + + + Compares two strings for equality, ignoring case if requested. + + The first string. + The second string.. + if set to true, the case of the letters in the strings is ignored. + True if the strings are equivalent, false if not. + + + + OneTimeSetUpCommand runs any one-time setup methods for a suite, + constructing the user test object if necessary. + + + + + Constructs a OneTimeSetUpCommand for a suite + + The suite to which the command applies + A SetUpTearDownList for use by the command + A List of TestActionItems to be run after Setup + + + + Overridden to run the one-time setup for a suite. + + The TestExecutionContext to be used. + A TestResult + + + + The TestOutput class holds a unit of output from + a test to a specific output stream + + + + + Construct with text, ouput destination type and + the name of the test that produced the output. + + Text to be output + Name of the stream or channel to which the text should be written + FullName of test that produced the output + + + + Return string representation of the object for debugging + + + + + + Convert the TestOutput object to an XML string + + + + + Get the text + + + + + Get the output type + + + + + Get the name of the test that created the output + + + + + The IMethodInfo class is used to encapsulate information + about a method in a platform-independent manner. + + + + + Gets the parameters of the method. + + + + + + Returns the Type arguments of a generic method or the Type parameters of a generic method definition. + + + + + Replaces the type parameters of the method with the array of types provided and returns a new IMethodInfo. + + The type arguments to be used + A new IMethodInfo with the type arguments replaced + + + + Invokes the method, converting any TargetInvocationException to an NUnitException. + + The object on which to invoke the method + The argument list for the method + The return value from the invoked method + + + + Gets the Type from which this method was reflected. + + + + + Gets the MethodInfo for this method. + + + + + Gets the name of the method. + + + + + Gets a value indicating whether the method is abstract. + + + + + Gets a value indicating whether the method is public. + + + + + Gets a value indicating whether the method contains unassigned generic type parameters. + + + + + Gets a value indicating whether the method is a generic method. + + + + + Gets a value indicating whether the MethodInfo represents the definition of a generic method. + + + + + Gets the return Type of the method. + + + + + ThrowsExceptionConstraint tests that an exception has + been thrown, without any further tests. + + + + + Executes the code and returns success if an exception is thrown. + + A delegate representing the code to be tested + True if an exception is thrown, otherwise false + + + + Returns the ActualValueDelegate itself as the value to be tested. + + A delegate representing the code to be tested + The delegate itself + + + + The Description of what this constraint tests, for + use in messages and in the ConstraintResult. + + + + + LevelOfParallelismAttribute is used to set the number of worker threads + that may be allocated by the framework for running tests. + + + + + Construct a LevelOfParallelismAttribute. + + The number of worker threads to be created by the framework. + + + + RepeatAttribute may be applied to test case in order + to run it multiple times. + + + + + Construct a RepeatAttribute + + The number of times to run the test + + + + Wrap a command and return the result. + + The command to be wrapped + The wrapped command + + + + The test command for the RetryAttribute + + + + + Initializes a new instance of the class. + + The inner command. + The number of repetitions + + + + Runs the test, saving a TestResult in the supplied TestExecutionContext. + + The context in which the test should run. + A TestResult + + + + Represents the result of running a single test case. + + + + + Construct a TestCaseResult based on a TestMethod + + A TestMethod to which the result applies. + + + + Gets the number of test cases that failed + when running the test and all its children. + + + + + Gets the number of test cases that passed + when running the test and all its children. + + + + + Gets the number of test cases that were skipped + when running the test and all its children. + + + + + Gets the number of test cases that were inconclusive + when running the test and all its children. + + + + + Indicates whether this result has any child results. + + + + + Gets the collection of child results. + + + + + TestParameters class holds any named parameters supplied to the test run + + + + + Gets a flag indicating whether a parameter with the specified name exists.N + + Name of the parameter + True if it exists, otherwise false + + + + Get method is a simple alternative to the indexer + + Name of the paramter + Value of the parameter or null if not present + + + + Get the value of a parameter or a default string + + Name of the parameter + Default value of the parameter + Value of the parameter or default value if not present + + + + Get the value of a parameter or return a default + + The return Type + Name of the parameter + Default value of the parameter + Value of the parameter or default value if not present + + + + Adds a parameter to the list + + Name of the parameter + Value of the parameter + + + + Gets the number of test parameters + + + + + Gets a collection of the test parameter names + + + + + Indexer provides access to the internal dictionary + + Name of the parameter + Value of the parameter or null if not present + + + + ParameterDataSourceProvider supplies individual argument _values for + single parameters using attributes implementing IParameterDataSource. + + + + + Determine whether any data is available for a parameter. + + A ParameterInfo representing one + argument to a parameterized test + + True if any data is available, otherwise false. + + + + + Return an IEnumerable providing data for use with the + supplied parameter. + + An IParameterInfo representing one + argument to a parameterized test + + An IEnumerable providing the required data + + + + + Thrown when an assertion failed. + + + + + + + The error message that explains + the reason for the exception + The exception that caused the + current exception + + + + Serialization Constructor + + + + + Gets the ResultState provided by this exception + + + + + OrConstraint succeeds if either member succeeds + + + + + Create an OrConstraint from two other constraints + + The first constraint + The second constraint + + + + Apply the member constraints to an actual value, succeeding + succeeding as soon as one of them succeeds. + + The actual value + True if either constraint succeeded + + + + Gets text describing a constraint + + + + + Operator that tests for the presence of a particular attribute + on a type and optionally applies further tests to the attribute. + + + + + Construct an AttributeOperator for a particular Type + + The Type of attribute tested + + + + Reduce produces a constraint from the operator and + any arguments. It takes the arguments from the constraint + stack and pushes the resulting constraint on it. + + + + + MessageWriter is the abstract base for classes that write + constraint descriptions and messages in some form. The + class has separate methods for writing various components + of a message, allowing implementations to tailor the + presentation as needed. + + + + + Construct a MessageWriter given a culture + + + + + Method to write single line message with optional args, usually + written to precede the general failure message. + + The message to be written + Any arguments used in formatting the message + + + + Method to write single line message with optional args, usually + written to precede the general failure message, at a givel + indentation level. + + The indentation level of the message + The message to be written + Any arguments used in formatting the message + + + + Display Expected and Actual lines for a constraint. This + is called by MessageWriter's default implementation of + WriteMessageTo and provides the generic two-line display. + + The failing constraint result + + + + Display Expected and Actual lines for given _values. This + method may be called by constraints that need more control over + the display of actual and expected _values than is provided + by the default implementation. + + The expected value + The actual value causing the failure + + + + Display Expected and Actual lines for given _values, including + a tolerance value on the Expected line. + + The expected value + The actual value causing the failure + The tolerance within which the test was made + + + + Display the expected and actual string _values on separate lines. + If the mismatch parameter is >=0, an additional line is displayed + line containing a caret that points to the mismatch point. + + The expected string value + The actual string value + The point at which the strings don't match or -1 + If true, case is ignored in locating the point where the strings differ + If true, the strings should be clipped to fit the line + + + + Writes the text for an actual value. + + The actual value. + + + + Writes the text for a generalized value. + + The value. + + + + Writes the text for a collection value, + starting at a particular point, to a max length + + The collection containing elements to write. + The starting point of the elements to write + The maximum number of elements to write + + + + Abstract method to get the max line length + + + + + Tests whether a value is less than the value supplied to its constructor + + + + + Abstract base class for constraints that compare _values to + determine if one is greater than, equal to or less than + the other. + + + + + The value against which a comparison is to be made + + + + + If true, less than returns success + + + + + if true, equal returns success + + + + + if true, greater than returns success + + + + + ComparisonAdapter to be used in making the comparison + + + + + Initializes a new instance of the class. + + The value against which to make a comparison. + if set to true less succeeds. + if set to true equal succeeds. + if set to true greater succeeds. + String used in describing the constraint. + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for success, false for failure + + + + Modifies the constraint to use an and returns self + + The comparer used for comparison tests + A constraint modified to use the given comparer + + + + Modifies the constraint to use an and returns self + + The comparer used for comparison tests + A constraint modified to use the given comparer + + + + Modifies the constraint to use a and returns self + + The comparer used for comparison tests + A constraint modified to use the given comparer + + + + Initializes a new instance of the class. + + The expected value. + + + + EmptyStringConstraint tests whether a string is empty. + + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for success, false for failure + + + + The Description of what this constraint tests, for + use in messages and in the ConstraintResult. + + + + + EmptyDirectoryConstraint is used to test that a directory is empty + + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for success, false for failure + + + + The Description of what this constraint tests, for + use in messages and in the ConstraintResult. + + + + + ConstraintBuilder maintains the stacks that are used in + processing a ConstraintExpression. An OperatorStack + is used to hold operators that are waiting for their + operands to be reorganized. a ConstraintStack holds + input constraints as well as the results of each + operator applied. + + + + + Initializes a new instance of the class. + + + + + Appends the specified operator to the expression by first + reducing the operator stack and then pushing the new + operator on the stack. + + The operator to push. + + + + Appends the specified constraint to the expression by pushing + it on the constraint stack. + + The constraint to push. + + + + Sets the top operator right context. + + The right context. + + + + Reduces the operator stack until the topmost item + precedence is greater than or equal to the target precedence. + + The target precedence. + + + + Resolves this instance, returning a Constraint. If the Builder + is not currently in a resolvable state, an exception is thrown. + + The resolved constraint + + + + Gets a value indicating whether this instance is resolvable. + + + true if this instance is resolvable; otherwise, false. + + + + + OperatorStack is a type-safe stack for holding ConstraintOperators + + + + + Initializes a new instance of the class. + + The ConstraintBuilder using this stack. + + + + Pushes the specified operator onto the stack. + + The operator to put onto the stack. + + + + Pops the topmost operator from the stack. + + The topmost operator on the stack + + + + Gets a value indicating whether this is empty. + + true if empty; otherwise, false. + + + + Gets the topmost operator without modifying the stack. + + + + + ConstraintStack is a type-safe stack for holding Constraints + + + + + Initializes a new instance of the class. + + The ConstraintBuilder using this stack. + + + + Pushes the specified constraint. As a side effect, + the constraint's Builder field is set to the + ConstraintBuilder owning this stack. + + The constraint to put onto the stack + + + + Pops this topmost constraint from the stack. + As a side effect, the constraint's Builder + field is set to null. + + The topmost contraint on the stack + + + + Gets a value indicating whether this is empty. + + true if empty; otherwise, false. + + + + CollectionEquivalentConstraint is used to determine whether two + collections are equivalent. + + + + + Construct a CollectionEquivalentConstraint + + + + + + Test whether two collections are equivalent + + + + + + + Flag the constraint to use the supplied predicate function + + The comparison function to use. + Self. + + + + The display name of this Constraint for use by ToString(). + The default value is the name of the constraint with + trailing "Constraint" removed. Derived classes may set + this to another name in their constructors. + + + + + The Description of what this constraint tests, for + use in messages and in the ConstraintResult. + + + + + AttributeExistsConstraint tests for the presence of a + specified attribute on a Type. + + + + + Constructs an AttributeExistsConstraint for a specific attribute Type + + + + + + Tests whether the object provides the expected attribute. + + A Type, MethodInfo, or other ICustomAttributeProvider + True if the expected attribute is present, otherwise false + + + + The Description of what this constraint tests, for + use in messages and in the ConstraintResult. + + + + + Marks a test that must run on a separate thread. + + + + + Construct a RequiresThreadAttribute + + + + + Construct a RequiresThreadAttribute, specifying the apartment + + + + + ExplicitAttribute marks a test or test fixture so that it will + only be run if explicitly executed from the gui or command line + or if it is included by use of a filter. The test will not be + run simply because an enclosing suite is run. + + + + + Default constructor + + + + + Constructor with a reason + + The reason test is marked explicit + + + + Modifies a test by marking it as explicit. + + The test to modify + + + + OneTimeTearDownCommand performs any teardown actions + specified for a suite and calls Dispose on the user + test object, if any. + + + + + Construct a OneTimeTearDownCommand + + The test suite to which the command applies + A SetUpTearDownList for use by the command + A List of TestActionItems to be run before teardown. + + + + Overridden to run the teardown methods specified on the test. + + The TestExecutionContext to be used. + A TestResult + + + + Class that can build a tree of automatic namespace + suites from a group of fixtures. + + + + + NamespaceDictionary of all test suites we have created to represent + namespaces. Used to locate namespace parent suites for fixtures. + + + + + The root of the test suite being created by this builder. + + + + + Initializes a new instance of the class. + + The root suite. + + + + Adds the specified fixtures to the tree. + + The fixtures to be added. + + + + Adds the specified fixture to the tree. + + The fixture to be added. + + + + Gets the root entry in the tree created by the NamespaceTreeBuilder. + + The root suite. + + + + Built-in SuiteBuilder for all types of test classes. + + + + + The ISuiteBuilder interface is exposed by a class that knows how to + build a suite from one or more Types. + + + + + Examine the type and determine if it is suitable for + this builder to use in building a TestSuite. + + Note that returning false will cause the type to be ignored + in loading the tests. If it is desired to load the suite + but label it as non-runnable, ignored, etc., then this + method must return true. + + The type of the fixture to be used + True if the type can be used to build a TestSuite + + + + Build a TestSuite from type provided. + + The type of the fixture to be used + A TestSuite + + + + Checks to see if the provided Type is a fixture. + To be considered a fixture, it must be a non-abstract + class with one or more attributes implementing the + IFixtureBuilder interface or one or more methods + marked as tests. + + The fixture type to check + True if the fixture can be built, false if not + + + + Build a TestSuite from TypeInfo provided. + + The fixture type to build + A TestSuite built from that type + + + + We look for attributes implementing IFixtureBuilder at one level + of inheritance at a time. Attributes on base classes are not used + unless there are no fixture builder attributes at all on the derived + class. This is by design. + + The type being examined for attributes + A list of the attributes found. + + + + + + + + + + + + + + + + + + + + + + + + Provide actions to execute before and after tests. + + + + + When implemented by an attribute, this interface implemented to provide actions to execute before and after tests. + + + + + Executed before each test is run + + The test that is going to be run. + + + + Executed after each test is run + + The test that has just been run. + + + + Provides the target for the action attribute + + The target for the action attribute + + + + Executed before each test is run + + The test that is going to be run. + + + + Executed after each test is run + + The test that has just been run. + + + + Provides the target for the action attribute + + + + + Marks a test that must run in a particular threading apartment state, causing it + to run in a separate thread if necessary. + + + + + Construct an ApartmentAttribute + + The apartment state that this test must be run under. You must pass in a valid apartment state. + + + + The Iz class is a synonym for Is intended for use in VB, + which regards Is as a keyword. + + + + + Helper class with properties and methods that supply + a number of constraints used in Asserts. + + + + + Returns a constraint that tests two items for equality + + + + + Returns a constraint that tests that two references are the same object + + + + + Returns a constraint that tests whether the + actual value is greater than the supplied argument + + + + + Returns a constraint that tests whether the + actual value is greater than or equal to the supplied argument + + + + + Returns a constraint that tests whether the + actual value is greater than or equal to the supplied argument + + + + + Returns a constraint that tests whether the + actual value is less than the supplied argument + + + + + Returns a constraint that tests whether the + actual value is less than or equal to the supplied argument + + + + + Returns a constraint that tests whether the + actual value is less than or equal to the supplied argument + + + + + Returns a constraint that tests whether the actual + value is of the exact type supplied as an argument. + + + + + Returns a constraint that tests whether the actual + value is of the exact type supplied as an argument. + + + + + Returns a constraint that tests whether the actual value + is of the type supplied as an argument or a derived type. + + + + + Returns a constraint that tests whether the actual value + is of the type supplied as an argument or a derived type. + + + + + Returns a constraint that tests whether the actual value + is assignable from the type supplied as an argument. + + + + + Returns a constraint that tests whether the actual value + is assignable from the type supplied as an argument. + + + + + Returns a constraint that tests whether the actual value + is assignable to the type supplied as an argument. + + + + + Returns a constraint that tests whether the actual value + is assignable to the type supplied as an argument. + + + + + Returns a constraint that tests whether the actual value + is a collection containing the same elements as the + collection supplied as an argument. + + + + + Returns a constraint that tests whether the actual value + is a subset of the collection supplied as an argument. + + + + + Returns a constraint that tests whether the actual value + is a superset of the collection supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value contains the substring supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value starts with the substring supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value ends with the substring supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value matches the regular expression supplied as an argument. + + + + + Returns a constraint that tests whether the path provided + is the same as an expected path after canonicalization. + + + + + Returns a constraint that tests whether the path provided + is a subpath of the expected path after canonicalization. + + + + + Returns a constraint that tests whether the path provided + is the same path or under an expected path after canonicalization. + + + + + Returns a constraint that tests whether the actual value falls + inclusively within a specified range. + + from must be less than or equal to true + Inclusive beginning of the range. Must be less than or equal to to. + Inclusive end of the range. Must be greater than or equal to from. + + + + + Returns a ConstraintExpression that negates any + following constraint. + + + + + Returns a ConstraintExpression, which will apply + the following constraint to all members of a collection, + succeeding if all of them succeed. + + + + + Returns a constraint that tests for null + + + + + Returns a constraint that tests for True + + + + + Returns a constraint that tests for False + + + + + Returns a constraint that tests for a positive value + + + + + Returns a constraint that tests for a negative value + + + + + Returns a constraint that tests for equality with zero + + + + + Returns a constraint that tests for NaN + + + + + Returns a constraint that tests for empty + + + + + Returns a constraint that tests whether a collection + contains all unique items. + + + + + Returns a constraint that tests whether an object graph is serializable in binary format. + + + + + Returns a constraint that tests whether an object graph is serializable in xml format. + + + + + Returns a constraint that tests whether a collection is ordered + + + + + Objects implementing this interface are used to wrap + the TestMethodCommand itself. They apply after SetUp + has been run and before TearDown. + + + + + The CommandStage enumeration represents the defined stages + of execution for a series of TestCommands. The int _values + of the enum are used to apply decorators in the proper + order. Lower _values are applied first and are therefore + "closer" to the actual test execution. + + + No CommandStage is defined for actual invocation of the test or + for creation of the context. Execution may be imagined as + proceeding from the bottom of the list upwards, with cleanup + after the test running in the opposite order. + + + + + Use an application-defined default value. + + + + + Make adjustments needed before and after running + the raw test - that is, after any SetUp has run + and before TearDown. + + + + + Run SetUp and TearDown for the test. This stage is used + internally by NUnit and should not normally appear + in user-defined decorators. + + + + + Make adjustments needed before and after running + the entire test - including SetUp and TearDown. + + + + + ThrowsConstraint is used to test the exception thrown by + a delegate by applying a constraint to it. + + + + + Initializes a new instance of the class, + using a constraint to be applied to the exception. + + A constraint to apply to the caught exception. + + + + Executes the code of the delegate and captures any exception. + If a non-null base constraint was provided, it applies that + constraint to the exception. + + A delegate representing the code to be tested + True if an exception is thrown and the constraint succeeds, otherwise false + + + + Converts an ActualValueDelegate to a TestDelegate + before calling the primary overload. + + + + + + + Get the actual exception thrown - used by Assert.Throws. + + + + + Gets text describing a constraint + + + + + Write the actual value for a failing constraint test to a + MessageWriter. This override only handles the special message + used when an exception is expected but none is thrown. + + The writer on which the actual value is displayed + + + + Summary description for SamePathConstraint. + + + + + Initializes a new instance of the class. + + The expected path + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for success, false for failure + + + + The Description of what this constraint tests, for + use in messages and in the ConstraintResult. + + + + + Operator that requires both it's arguments to succeed + + + + + Construct an AndOperator + + + + + Apply the operator to produce an AndConstraint + + + + + Provides static methods to express the assumptions + that must be met for a test to give a meaningful + result. If an assumption is not met, the test + should produce an inconclusive result. + + + + + The Equals method throws an InvalidOperationException. This is done + to make sure there is no mistake by calling this function. + + The left object. + The right object. + Not applicable + + + + override the default ReferenceEquals to throw an InvalidOperationException. This + implementation makes sure there is no mistake in calling this function + as part of Assert. + + The left object. + The right object. + + + + Apply a constraint to an actual value, succeeding if the constraint + is satisfied and throwing an InconclusiveException on failure. + + The Type being compared. + An ActualValueDelegate returning the value to be tested + A Constraint expression to be applied + + + + Apply a constraint to an actual value, succeeding if the constraint + is satisfied and throwing an InconclusiveException on failure. + + The Type being compared. + An ActualValueDelegate returning the value to be tested + A Constraint expression to be applied + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Apply a constraint to an actual value, succeeding if the constraint + is satisfied and throwing an InconclusiveException on failure. + + The Type being compared. + An ActualValueDelegate returning the value to be tested + A Constraint expression to be applied + A function to build the message included with the Exception + + + + Asserts that a condition is true. If the condition is false the method throws + an . + + The evaluated condition + The message to display if the condition is false + Arguments to be used in formatting the message + + + + Asserts that a condition is true. If the condition is false the + method throws an . + + The evaluated condition + + + + Asserts that a condition is true. If the condition is false the method throws + an . + + The evaluated condition + A function to build the message included with the Exception + + + + Asserts that a condition is true. If the condition is false the method throws + an . + + A lambda that returns a Boolean + The message to display if the condition is false + Arguments to be used in formatting the message + + + + Asserts that a condition is true. If the condition is false the method throws + an . + + A lambda that returns a Boolean + + + + Asserts that a condition is true. If the condition is false the method throws + an . + + A lambda that returns a Boolean + A function to build the message included with the Exception + + + + Asserts that the code represented by a delegate throws an exception + that satisfies the constraint provided. + + A TestDelegate to be executed + A ThrowsConstraint used in the test + + + + Apply a constraint to an actual value, succeeding if the constraint + is satisfied and throwing an InconclusiveException on failure. + + The Type being compared. + The actual value to test + A Constraint to be applied + + + + Apply a constraint to an actual value, succeeding if the constraint + is satisfied and throwing an InconclusiveException on failure. + + The Type being compared. + The actual value to test + A Constraint expression to be applied + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Apply a constraint to an actual value, succeeding if the constraint + is satisfied and throwing an InconclusiveException on failure. + + The Type being compared. + The actual value to test + A Constraint to be applied + A function to build the message included with the Exception + + + + TODO: Documentation needed for class + + + + + Initializes a new instance of the class. + + The test being skipped. + + + + Overridden to simply set the CurrentResult to the + appropriate Skipped state. + + The execution context for the test + A TestResult + + + + The TextCapture class intercepts console output and writes it + to the current execution context, if one is present on the thread. + If no execution context is found, the output is written to a + default destination, normally the original destination of the + intercepted output. + + + + + Construct a TextCapture object + + The default destination for non-intercepted output + + + + Writes a single character + + The char to write + + + + Writes a string + + The string to write + + + + Writes a string followed by a line terminator + + The string to write + + + + Gets the Encoding in use by this TextWriter + + + + + SimpleWorkItemDispatcher handles execution of WorkItems by + directly executing them. It is provided so that a dispatcher + is always available in the context, thereby simplifying the + code needed to run child tests. + + + + + An IWorkItemDispatcher handles execution of work items. + + + + + Dispatch a single work item for execution. The first + work item dispatched is saved as the top-level + work item and used when stopping the run. + + The item to dispatch + + + + Cancel the ongoing run completely. + If no run is in process, the call has no effect. + + true if the IWorkItemDispatcher should abort all currently running WorkItems, false if it should allow all currently running WorkItems to complete + + + + Dispatch a single work item for execution. The first + work item dispatched is saved as the top-level + work item and a thread is created on which to + run it. Subsequent calls come from the top level + item or its descendants on the proper thread. + + The item to dispatch + + + + Cancel (abort or stop) the ongoing run. + If no run is in process, the call has no effect. + + true if the run should be aborted, false if it should allow its currently running test to complete + + + + Asserts on Directories + + + + + The Equals method throws an InvalidOperationException. This is done + to make sure there is no mistake by calling this function. + + + + + + + override the default ReferenceEquals to throw an InvalidOperationException. This + implementation makes sure there is no mistake in calling this function + as part of Assert. + + + + + + + Verifies that two directories are equal. Two directories are considered + equal if both are null, or if both point to the same directory. + If they are not equal an is thrown. + + A directory containing the value that is expected + A directory containing the actual value + The message to display if the directories are not equal + Arguments to be used in formatting the message + + + + Verifies that two directories are equal. Two directories are considered + equal if both are null, or if both point to the same directory. + If they are not equal an is thrown. + + A directory containing the value that is expected + A directory containing the actual value + + + + Asserts that two directories are not equal. If they are equal + an is thrown. + + A directory containing the value that is expected + A directory containing the actual value + The message to display if directories are not equal + Arguments to be used in formatting the message + + + + Asserts that two directories are not equal. If they are equal + an is thrown. + + A directory containing the value that is expected + A directory containing the actual value + + + + Asserts that the directory exists. If it does not exist + an is thrown. + + A directory containing the actual value + The message to display if directories are not equal + Arguments to be used in formatting the message + + + + Asserts that the directory exists. If it does not exist + an is thrown. + + A directory containing the actual value + + + + Asserts that the directory exists. If it does not exist + an is thrown. + + The path to a directory containing the actual value + The message to display if directories are not equal + Arguments to be used in formatting the message + + + + Asserts that the directory exists. If it does not exist + an is thrown. + + The path to a directory containing the actual value + + + + Asserts that the directory does not exist. If it does exist + an is thrown. + + A directory containing the actual value + The message to display if directories are not equal + Arguments to be used in formatting the message + + + + Asserts that the directory does not exist. If it does exist + an is thrown. + + A directory containing the actual value + + + + Asserts that the directory does not exist. If it does exist + an is thrown. + + The path to a directory containing the actual value + The message to display if directories are not equal + Arguments to be used in formatting the message + + + + Asserts that the directory does not exist. If it does exist + an is thrown. + + The path to a directory containing the actual value + + + + TestName filter selects tests based on their Name + + + + + Construct a TestNameFilter for a single name + + The name the filter will recognize. + + + + Match a test against a single value. + + + + + Gets the element name + + Element name + + + + The ParameterDataProvider class implements IParameterDataProvider + and hosts one or more individual providers. + + + + + Construct with a collection of individual providers + + + + + Determine whether any data is available for a parameter. + + An IParameterInfo representing one + argument to a parameterized test + True if any data is available, otherwise false. + + + + Return an IEnumerable providing data for use with the + supplied parameter. + + An IParameterInfo representing one + argument to a parameterized test + An IEnumerable providing the required data + + + + ExactCountConstraint applies another constraint to each + item in a collection, succeeding only if a specified + number of items succeed. + + + + + Construct an ExactCountConstraint on top of an existing constraint + + + + + + + Apply the item constraint to each item in the collection, + succeeding only if the expected number of items pass. + + + + + + + Thrown when an assertion failed. + + + + The error message that explains + the reason for the exception + + + The error message that explains + the reason for the exception + The exception that caused the + current exception + + + + Serialization Constructor + + + + + Gets the ResultState provided by this exception + + + + + XmlSerializableConstraint tests whether + an object is serializable in xml format. + + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for success, false for failure + + + + Returns the string representation of this constraint + + + + + Gets text describing a constraint + + + + Helper routines for working with floating point numbers + + + The floating point comparison code is based on this excellent article: + http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm + + + "ULP" means Unit in the Last Place and in the context of this library refers to + the distance between two adjacent floating point numbers. IEEE floating point + numbers can only represent a finite subset of natural numbers, with greater + accuracy for smaller numbers and lower accuracy for very large numbers. + + + If a comparison is allowed "2 ulps" of deviation, that means the _values are + allowed to deviate by up to 2 adjacent floating point _values, which might be + as low as 0.0000001 for small numbers or as high as 10.0 for large numbers. + + + + + Compares two floating point _values for equality + First floating point value to be compared + Second floating point value t be compared + + Maximum number of representable floating point _values that are allowed to + be between the left and the right floating point _values + + True if both numbers are equal or close to being equal + + + Floating point _values can only represent a finite subset of natural numbers. + For example, the _values 2.00000000 and 2.00000024 can be stored in a float, + but nothing inbetween them. + + + This comparison will count how many possible floating point _values are between + the left and the right number. If the number of possible _values between both + numbers is less than or equal to maxUlps, then the numbers are considered as + being equal. + + + Implementation partially follows the code outlined here: + http://www.anttirt.net/2007/08/19/proper-floating-point-comparisons/ + + + + + Compares two double precision floating point _values for equality + First double precision floating point value to be compared + Second double precision floating point value t be compared + + Maximum number of representable double precision floating point _values that are + allowed to be between the left and the right double precision floating point _values + + True if both numbers are equal or close to being equal + + + Double precision floating point _values can only represent a limited series of + natural numbers. For example, the _values 2.0000000000000000 and 2.0000000000000004 + can be stored in a double, but nothing inbetween them. + + + This comparison will count how many possible double precision floating point + _values are between the left and the right number. If the number of possible + _values between both numbers is less than or equal to maxUlps, then the numbers + are considered as being equal. + + + Implementation partially follows the code outlined here: + http://www.anttirt.net/2007/08/19/proper-floating-point-comparisons/ + + + + + + Reinterprets the memory contents of a floating point value as an integer value + + + Floating point value whose memory contents to reinterpret + + + The memory contents of the floating point value interpreted as an integer + + + + + Reinterprets the memory contents of a double precision floating point + value as an integer value + + + Double precision floating point value whose memory contents to reinterpret + + + The memory contents of the double precision floating point value + interpreted as an integer + + + + + Reinterprets the memory contents of an integer as a floating point value + + Integer value whose memory contents to reinterpret + + The memory contents of the integer value interpreted as a floating point value + + + + + Reinterprets the memory contents of an integer value as a double precision + floating point value + + Integer whose memory contents to reinterpret + + The memory contents of the integer interpreted as a double precision + floating point value + + + + Union of a floating point variable and an integer + + + The union's value as a floating point variable + + + The union's value as an integer + + + The union's value as an unsigned integer + + + Union of a double precision floating point variable and a long + + + The union's value as a double precision floating point variable + + + The union's value as a long + + + The union's value as an unsigned long + + + + EqualityAdapter class handles all equality comparisons + that use an , + or a . + + + + + Compares two objects, returning true if they are equal + + + + + Returns true if the two objects can be compared by this adapter. + The base adapter cannot handle IEnumerables except for strings. + + + + + Returns an that wraps an . + + + + + Returns an that wraps an . + + + + + Returns an EqualityAdapter that uses a predicate function for items comparison. + + + + + + + + + Returns an that wraps an . + + + + + Returns an that wraps an . + + + + + Returns an that wraps a . + + + + + that wraps an . + + + + + Returns true if the two objects can be compared by this adapter. + The base adapter cannot handle IEnumerables except for strings. + + + + + Compares two objects, returning true if they are equal + + + + + Returns true if the two objects can be compared by this adapter. + Generic adapter requires objects of the specified type. + + + + + that wraps an . + + + + + EmptyCollectionConstraint tests whether a collection is empty. + + + + + Check that the collection is empty + + + + + + + The Description of what this constraint tests, for + use in messages and in the ConstraintResult. + + + + + Helper class with properties and methods that supply + a number of constraints used in Asserts. + + + + + Returns a ConstraintExpression, which will apply + the following constraint to all members of a collection, + succeeding only if a specified number of them succeed. + + + + + Returns a new PropertyConstraintExpression, which will either + test for the existence of the named property on the object + being tested or apply any following constraint to that property. + + + + + Returns a new AttributeConstraint checking for the + presence of a particular attribute on an object. + + + + + Returns a new AttributeConstraint checking for the + presence of a particular attribute on an object. + + + + + Returns a constraint that tests two items for equality + + + + + Returns a constraint that tests that two references are the same object + + + + + Returns a constraint that tests whether the + actual value is greater than the supplied argument + + + + + Returns a constraint that tests whether the + actual value is greater than or equal to the supplied argument + + + + + Returns a constraint that tests whether the + actual value is greater than or equal to the supplied argument + + + + + Returns a constraint that tests whether the + actual value is less than the supplied argument + + + + + Returns a constraint that tests whether the + actual value is less than or equal to the supplied argument + + + + + Returns a constraint that tests whether the + actual value is less than or equal to the supplied argument + + + + + Returns a constraint that tests whether the actual + value is of the exact type supplied as an argument. + + + + + Returns a constraint that tests whether the actual + value is of the exact type supplied as an argument. + + + + + Returns a constraint that tests whether the actual value + is of the type supplied as an argument or a derived type. + + + + + Returns a constraint that tests whether the actual value + is of the type supplied as an argument or a derived type. + + + + + Returns a constraint that tests whether the actual value + is assignable from the type supplied as an argument. + + + + + Returns a constraint that tests whether the actual value + is assignable from the type supplied as an argument. + + + + + Returns a constraint that tests whether the actual value + is assignable from the type supplied as an argument. + + + + + Returns a constraint that tests whether the actual value + is assignable from the type supplied as an argument. + + + + + Returns a constraint that tests whether the actual value + is a collection containing the same elements as the + collection supplied as an argument. + + + + + Returns a constraint that tests whether the actual value + is a subset of the collection supplied as an argument. + + + + + Returns a constraint that tests whether the actual value + is a superset of the collection supplied as an argument. + + + + + Returns a new CollectionContainsConstraint checking for the + presence of a particular object in the collection. + + + + + Returns a new CollectionContainsConstraint checking for the + presence of a particular object in the collection. + + + + + Returns a new ContainsConstraint. This constraint + will, in turn, make use of the appropriate second-level + constraint, depending on the type of the actual argument. + This overload is only used if the item sought is a string, + since any other type implies that we are looking for a + collection member. + + + + + Returns a constraint that succeeds if the actual + value contains the substring supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value contains the substring supplied as an argument. + + + + + Returns a constraint that fails if the actual + value contains the substring supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value starts with the substring supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value starts with the substring supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value starts with the substring supplied as an argument. + + + + + Returns a constraint that fails if the actual + value starts with the substring supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value ends with the substring supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value ends with the substring supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value ends with the substring supplied as an argument. + + + + + Returns a constraint that fails if the actual + value ends with the substring supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value matches the regular expression supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value matches the regular expression supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value matches the regular expression supplied as an argument. + + + + + Returns a constraint that fails if the actual + value matches the pattern supplied as an argument. + + + + + Returns a constraint that tests whether the path provided + is the same as an expected path after canonicalization. + + + + + Returns a constraint that tests whether the path provided + is a subpath of the expected path after canonicalization. + + + + + Returns a constraint that tests whether the path provided + is the same path or under an expected path after canonicalization. + + + + + Returns a constraint that tests whether the actual value falls + within a specified range. + + + + + Returns a ConstraintExpression that negates any + following constraint. + + + + + Returns a ConstraintExpression that negates any + following constraint. + + + + + Returns a ConstraintExpression, which will apply + the following constraint to all members of a collection, + succeeding if all of them succeed. + + + + + Returns a ConstraintExpression, which will apply + the following constraint to all members of a collection, + succeeding if at least one of them succeeds. + + + + + Returns a ConstraintExpression, which will apply + the following constraint to all members of a collection, + succeeding if all of them fail. + + + + + Returns a new ConstraintExpression, which will apply the following + constraint to the Length property of the object being tested. + + + + + Returns a new ConstraintExpression, which will apply the following + constraint to the Count property of the object being tested. + + + + + Returns a new ConstraintExpression, which will apply the following + constraint to the Message property of the object being tested. + + + + + Returns a new ConstraintExpression, which will apply the following + constraint to the InnerException property of the object being tested. + + + + + Returns a constraint that tests for null + + + + + Returns a constraint that tests for True + + + + + Returns a constraint that tests for False + + + + + Returns a constraint that tests for a positive value + + + + + Returns a constraint that tests for a negative value + + + + + Returns a constraint that tests for equality with zero + + + + + Returns a constraint that tests for NaN + + + + + Returns a constraint that tests for empty + + + + + Returns a constraint that tests whether a collection + contains all unique items. + + + + + Returns a constraint that tests whether an object graph is serializable in binary format. + + + + + Returns a constraint that tests whether an object graph is serializable in xml format. + + + + + Returns a constraint that tests whether a collection is ordered + + + + + BinarySerializableConstraint tests whether + an object is serializable in binary format. + + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for success, false for failure + + + + Returns the string representation + + + + + The Description of what this constraint tests, for + use in messages and in the ConstraintResult. + + + + + Used on a method, marks the test with a timeout value in milliseconds. + The test will be run in a separate thread and is cancelled if the timeout + is exceeded. Used on a class or assembly, sets the default timeout + for all contained test methods. + + + + + Construct a TimeoutAttribute given a time in milliseconds + + The timeout value in milliseconds + + + + Adding this attribute to a method within a + class makes the method callable from the NUnit test runner. There is a property + called Description which is optional which you can provide a more detailed test + description. This class cannot be inherited. + + + + [TestFixture] + public class Fixture + { + [Test] + public void MethodToTest() + {} + + [Test(Description = "more detailed description")] + public void TestDescriptionMethod() + {} + } + + + + + + Modifies a test by adding a description, if not already set. + + The test to modify + + + + Construct a TestMethod from a given method. + + The method for which a test is to be constructed. + The suite to which the test will be added. + A TestMethod + + + + Descriptive text for this test + + + + + The author of this test + + + + + The type that this test is testing + + + + + Gets or sets the expected result. + + The result. + + + + Returns true if an expected result has been set + + + + + Summary description for SetUICultureAttribute. + + + + + Construct given the name of a culture + + + + + + Marks a test that must run in the STA, causing it + to run in a separate thread if necessary. + + + + + Construct a RequiresSTAAttribute + + + + + Used to mark a field, property or method providing a set of datapoints to + be used in executing any theories within the same fixture that require an + argument of the Type provided. The data source may provide an array of + the required Type or an . + Synonymous with DatapointSourceAttribute. + + + + + TestActionItem represents a single execution of an + ITestAction. It is used to track whether the BeforeTest + method has been called and suppress calling the + AfterTest method if it has not. + + + + + Construct a TestActionItem + + The ITestAction to be included + + + + Run the BeforeTest method of the action and remember that it has been run. + + The test to which the action applies + + + + Run the AfterTest action, but only if the BeforeTest + action was actually run. + + The test to which the action applies + + + + InternalTraceLevel is an enumeration controlling the + level of detailed presented in the internal log. + + + + + Use the default settings as specified by the user. + + + + + Do not display any trace messages + + + + + Display Error messages only + + + + + Display Warning level and higher messages + + + + + Display informational and higher messages + + + + + Display debug messages and higher - i.e. all messages + + + + + Display debug messages and higher - i.e. all messages + + + + + The ParallelScope enumeration permits specifying the degree to + which a test and its descendants may be run in parallel. + + + + + No Parallelism is permitted + + + + + The test itself may be run in parallel with others at the same level + + + + + Descendants of the test may be run in parallel with one another + + + + + Descendants of the test down to the level of TestFixtures may be run in parallel + + + + + ListMapper is used to transform a collection used as an actual argument + producing another collection to be used in the assertion. + + + + + Construct a ListMapper based on a collection + + The collection to be transformed + + + + Produces a collection containing all the _values of a property + + The collection of property _values + + + + + The List class is a helper class with properties and methods + that supply a number of constraints used with lists and collections. + + + + + List.Map returns a ListMapper, which can be used to map + the original collection to another collection. + + + + + + + TestAssembly is a TestSuite that represents the execution + of tests in a managed assembly. + + + + + Initializes a new instance of the class + specifying the Assembly and the path from which it was loaded. + + The assembly this test represents. + The path used to load the assembly. + + + + Initializes a new instance of the class + for a path which could not be loaded. + + The path used to load the assembly. + + + + Gets the Assembly represented by this instance. + + + + + Gets the name used for the top-level element in the + XML representation of this test + + + + + SetUpFixture extends TestSuite and supports + Setup and TearDown methods. + + + + + Initializes a new instance of the class. + + The type. + + + + TrueConstraint tests that the actual value is true + + + + + Initializes a new instance of the class. + + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for success, false for failure + + + + The Tolerance class generalizes the notion of a tolerance + within which an equality test succeeds. Normally, it is + used with numeric types, but it can be used with any + type that supports taking a difference between two + objects and comparing that difference to a value. + + + + + Constructs a linear tolerance of a specified amount + + + + + Constructs a tolerance given an amount and + + + + + Tests that the current Tolerance is linear with a + numeric value, throwing an exception if it is not. + + + + + Returns a default Tolerance object, equivalent to + specifying an exact match unless + is set, in which case, the + will be used. + + + + + Returns an empty Tolerance object, equivalent to + specifying an exact match even if + is set. + + + + + Gets the for the current Tolerance + + + + + Gets the value of the current Tolerance instance. + + + + + Returns a new tolerance, using the current amount as a percentage. + + + + + Returns a new tolerance, using the current amount in Ulps + + + + + Returns a new tolerance with a as the amount, using + the current amount as a number of days. + + + + + Returns a new tolerance with a as the amount, using + the current amount as a number of hours. + + + + + Returns a new tolerance with a as the amount, using + the current amount as a number of minutes. + + + + + Returns a new tolerance with a as the amount, using + the current amount as a number of seconds. + + + + + Returns a new tolerance with a as the amount, using + the current amount as a number of milliseconds. + + + + + Returns a new tolerance with a as the amount, using + the current amount as a number of clock ticks. + + + + + Returns true if the current tolerance has not been set or is using the . + + + + + StartsWithConstraint can test whether a string starts + with an expected substring. + + + + + Initializes a new instance of the class. + + The expected string + + + + Test whether the constraint is matched by the actual value. + This is a template method, which calls the IsMatch method + of the derived class. + + + + + + + Operator that tests that an exception is thrown and + optionally applies further tests to the exception. + + + + + Construct a ThrowsOperator + + + + + Reduce produces a constraint from the operator and + any arguments. It takes the arguments from the constraint + stack and pushes the resulting constraint on it. + + + + + ConstraintExpression represents a compound constraint in the + process of being constructed from a series of syntactic elements. + + Individual elements are appended to the expression as they are + reorganized. When a constraint is appended, it is returned as the + value of the operation so that modifiers may be applied. However, + any partially built expression is attached to the constraint for + later resolution. When an operator is appended, the partial + expression is returned. If it's a self-resolving operator, then + a ResolvableConstraintExpression is returned. + + + + + The ConstraintBuilder holding the elements recognized so far + + + + + Initializes a new instance of the class. + + + + + Initializes a new instance of the + class passing in a ConstraintBuilder, which may be pre-populated. + + The builder. + + + + Returns a string representation of the expression as it + currently stands. This should only be used for testing, + since it has the side-effect of resolving the expression. + + + + + + Appends an operator to the expression and returns the + resulting expression itself. + + + + + Appends a self-resolving operator to the expression and + returns a new ResolvableConstraintExpression. + + + + + Appends a constraint to the expression and returns that + constraint, which is associated with the current state + of the expression being built. Note that the constraint + is not reduced at this time. For example, if there + is a NotOperator on the stack we don't reduce and + return a NotConstraint. The original constraint must + be returned because it may support modifiers that + are yet to be applied. + + + + + Returns a ConstraintExpression, which will apply + the following constraint to all members of a collection, + succeeding only if a specified number of them succeed. + + + + + Returns a new PropertyConstraintExpression, which will either + test for the existence of the named property on the object + being tested or apply any following constraint to that property. + + + + + Returns a new AttributeConstraint checking for the + presence of a particular attribute on an object. + + + + + Returns a new AttributeConstraint checking for the + presence of a particular attribute on an object. + + + + + Returns the constraint provided as an argument - used to allow custom + custom constraints to easily participate in the syntax. + + + + + Returns the constraint provided as an argument - used to allow custom + custom constraints to easily participate in the syntax. + + + + + Returns a constraint that tests two items for equality + + + + + Returns a constraint that tests that two references are the same object + + + + + Returns a constraint that tests whether the + actual value is greater than the supplied argument + + + + + Returns a constraint that tests whether the + actual value is greater than or equal to the supplied argument + + + + + Returns a constraint that tests whether the + actual value is greater than or equal to the supplied argument + + + + + Returns a constraint that tests whether the + actual value is less than the supplied argument + + + + + Returns a constraint that tests whether the + actual value is less than or equal to the supplied argument + + + + + Returns a constraint that tests whether the + actual value is less than or equal to the supplied argument + + + + + Returns a constraint that tests whether the actual + value is of the exact type supplied as an argument. + + + + + Returns a constraint that tests whether the actual + value is of the exact type supplied as an argument. + + + + + Returns a constraint that tests whether the actual value + is of the type supplied as an argument or a derived type. + + + + + Returns a constraint that tests whether the actual value + is of the type supplied as an argument or a derived type. + + + + + Returns a constraint that tests whether the actual value + is assignable from the type supplied as an argument. + + + + + Returns a constraint that tests whether the actual value + is assignable from the type supplied as an argument. + + + + + Returns a constraint that tests whether the actual value + is assignable from the type supplied as an argument. + + + + + Returns a constraint that tests whether the actual value + is assignable from the type supplied as an argument. + + + + + Returns a constraint that tests whether the actual value + is a collection containing the same elements as the + collection supplied as an argument. + + + + + Returns a constraint that tests whether the actual value + is a subset of the collection supplied as an argument. + + + + + Returns a constraint that tests whether the actual value + is a superset of the collection supplied as an argument. + + + + + Returns a new CollectionContainsConstraint checking for the + presence of a particular object in the collection. + + + + + Returns a new CollectionContainsConstraint checking for the + presence of a particular object in the collection. + + + + + Returns a new ContainsConstraint. This constraint + will, in turn, make use of the appropriate second-level + constraint, depending on the type of the actual argument. + This overload is only used if the item sought is a string, + since any other type implies that we are looking for a + collection member. + + + + + Returns a new ContainsConstraint. This constraint + will, in turn, make use of the appropriate second-level + constraint, depending on the type of the actual argument. + This overload is only used if the item sought is a string, + since any other type implies that we are looking for a + collection member. + + + + + Returns a constraint that succeeds if the actual + value contains the substring supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value contains the substring supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value starts with the substring supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value starts with the substring supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value starts with the substring supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value ends with the substring supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value ends with the substring supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value ends with the substring supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value matches the regular expression supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value matches the regular expression supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value matches the regular expression supplied as an argument. + + + + + Returns a constraint that tests whether the path provided + is the same as an expected path after canonicalization. + + + + + Returns a constraint that tests whether the path provided + is the a subpath of the expected path after canonicalization. + + + + + Returns a constraint that tests whether the path provided + is the same path or under an expected path after canonicalization. + + + + + Returns a constraint that tests whether the actual value falls + within a specified range. + + + + + Returns a ConstraintExpression that negates any + following constraint. + + + + + Returns a ConstraintExpression that negates any + following constraint. + + + + + Returns a ConstraintExpression, which will apply + the following constraint to all members of a collection, + succeeding if all of them succeed. + + + + + Returns a ConstraintExpression, which will apply + the following constraint to all members of a collection, + succeeding if at least one of them succeeds. + + + + + Returns a ConstraintExpression, which will apply + the following constraint to all members of a collection, + succeeding if all of them fail. + + + + + Returns a new ConstraintExpression, which will apply the following + constraint to the Length property of the object being tested. + + + + + Returns a new ConstraintExpression, which will apply the following + constraint to the Count property of the object being tested. + + + + + Returns a new ConstraintExpression, which will apply the following + constraint to the Message property of the object being tested. + + + + + Returns a new ConstraintExpression, which will apply the following + constraint to the InnerException property of the object being tested. + + + + + With is currently a NOP - reserved for future use. + + + + + Returns a constraint that tests for null + + + + + Returns a constraint that tests for True + + + + + Returns a constraint that tests for False + + + + + Returns a constraint that tests for a positive value + + + + + Returns a constraint that tests for a negative value + + + + + Returns a constraint that tests if item is equal to zero + + + + + Returns a constraint that tests for NaN + + + + + Returns a constraint that tests for empty + + + + + Returns a constraint that tests whether a collection + contains all unique items. + + + + + Returns a constraint that tests whether an object graph is serializable in binary format. + + + + + Returns a constraint that tests whether an object graph is serializable in xml format. + + + + + Returns a constraint that tests whether a collection is ordered + + + + + Returns a constraint that succeeds if the value + is a file or directory and it exists. + + + + + Attribute used to apply a category to a test + + + + + The name of the category + + + + + Construct attribute for a given category based on + a name. The name may not contain the characters ',', + '+', '-' or '!'. However, this is not checked in the + constructor since it would cause an error to arise at + as the test was loaded without giving a clear indication + of where the problem is located. The error is handled + in NUnitFramework.cs by marking the test as not + runnable. + + The name of the category + + + + Protected constructor uses the Type name as the name + of the category. + + + + + Modifies a test by adding a category to it. + + The test to modify + + + + The name of the category + + + + + IdFilter selects tests based on their id + + + + + Construct an IdFilter for a single value + + The id the filter will recognize. + + + + Match a test against a single value. + + + + + Gets the element name + + Element name + + + + Represents a constraint that succeeds if none of the + members of a collection match a base constraint. + + + + + Returns a constraint that will apply the argument + to the members of a collection, succeeding if + none of them succeed. + + + + + Indicates which class the test or test fixture is testing + + + + + Initializes a new instance of the class. + + The type that is being tested. + + + + Initializes a new instance of the class. + + The type that is being tested. + + + + Defines the order that the test will run in + + + + + Defines the order that the test will run in + + + + + Defines the order that the test will run in + + + + + + Modifies a test as defined for the specific attribute. + + The test to modify + + + + SingleThreadedAttribute applies to a test fixture and indicates + that all the child tests must be run on the same thread as the + OneTimeSetUp and OneTimeTearDown. It sets a flag in the + TestExecutionContext and forces all tests to be run sequentially + on the current thread. Any ParallelScope setting is ignored. + + + + + Apply changes to the TestExecutionContext + + The TestExecutionContext + + + + FrameworkPackageSettings is a static class containing constant values that + are used as keys in setting up a TestPackage. These values are used in + the framework, and set in the runner. Setting values may be a string, int or bool. + + + + + Flag (bool) indicating whether tests are being debugged. + + + + + Flag (bool) indicating whether to pause execution of tests to allow + the user to attache a debugger. + + + + + The InternalTraceLevel for this run. Values are: "Default", + "Off", "Error", "Warning", "Info", "Debug", "Verbose". + Default is "Off". "Debug" and "Verbose" are synonyms. + + + + + Full path of the directory to be used for work and result files. + This path is provided to tests by the frameowrk TestContext. + + + + + Integer value in milliseconds for the default timeout value + for test cases. If not specified, there is no timeout except + as specified by attributes on the tests themselves. + + + + + A TextWriter to which the internal trace will be sent. + + + + + A list of tests to be loaded. + + + + + The number of test threads to run for the assembly. If set to + 1, a single queue is used. If set to 0, tests are executed + directly, without queuing. + + + + + The random seed to be used for this assembly. If specified + as the value reported from a prior run, the framework should + generate identical random values for tests as were used for + that run, provided that no change has been made to the test + assembly. Default is a random value itself. + + + + + If true, execution stops after the first error or failure. + + + + + If true, use of the event queue is suppressed and test events are synchronous. + + + + + The default naming pattern used in generating test names + + + + + Parameters to be passed on to the test + + + + + Represents a constraint that succeeds if the specified + count of members of a collection match a base constraint. + + + + + Construct an ExactCountOperator for a specified count + + The expected count + + + + Returns a constraint that will apply the argument + to the members of a collection, succeeding if + none of them succeed. + + + + + ParameterizedFixtureSuite serves as a container for the set of test + fixtures created from a given Type using various parameters. + + + + + Initializes a new instance of the class. + + The ITypeInfo for the type that represents the suite. + + + + Gets a string representing the type of test + + + + + + ReusableConstraint wraps a constraint expression after + resolving it so that it can be reused consistently. + + + + + Construct a ReusableConstraint from a constraint expression + + The expression to be resolved and reused + + + + Converts a constraint to a ReusableConstraint + + The constraint to be converted + A ReusableConstraint + + + + Returns a that represents this instance. + + + A that represents this instance. + + + + + Return the top-level constraint for this expression + + + + + + PropertyExistsConstraint tests that a named property + exists on the object provided through Match. + + Originally, PropertyConstraint provided this feature + in addition to making optional tests on the value + of the property. The two constraints are now separate. + + + + + Initializes a new instance of the class. + + The name of the property. + + + + Test whether the property exists for a given object + + The object to be tested + True for success, false for failure + + + + Returns the string representation of the constraint. + + + + + + The Description of what this constraint tests, for + use in messages and in the ConstraintResult. + + + + + PropertyConstraint extracts a named property and uses + its value as the actual value for a chained constraint. + + + + + Initializes a new instance of the class. + + The name. + The constraint to apply to the property. + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for success, false for failure + + + + Returns the string representation of the constraint. + + + + + + Represents a constraint that simply wraps the + constraint provided as an argument, without any + further functionality, but which modifies the + order of evaluation because of its precedence. + + + + + Constructor for the WithOperator + + + + + Returns a constraint that wraps its argument + + + + + NUnitComparer encapsulates NUnit's default behavior + in comparing two objects. + + + + + Compares two objects + + + + + + + + Returns the default NUnitComparer. + + + + + Tests whether a value is less than or equal to the value supplied to its constructor + + + + + Initializes a new instance of the class. + + The expected value. + + + + Attribute used to identify a method that is + called before any tests in a fixture are run. + + + + + Used to mark a field for use as a datapoint when executing a theory + within the same fixture that requires an argument of the field's Type. + + + + + AssertionHelper is an optional base class for user tests, + allowing the use of shorter ids for constraints and + asserts and avoiding conflict with the definition of + , from which it inherits much of its + behavior, in certain mock object frameworks. + + + + + Asserts that a condition is true. If the condition is false the method throws + an . Works Identically to + . + + The evaluated condition + The message to display if the condition is false + Arguments to be used in formatting the message + + + + Asserts that a condition is true. If the condition is false the method throws + an . Works Identically to . + + The evaluated condition + + + + Apply a constraint to an actual value, succeeding if the constraint + is satisfied and throwing an assertion exception on failure. + + A Constraint expression to be applied + An ActualValueDelegate returning the value to be tested + + + + Apply a constraint to an actual value, succeeding if the constraint + is satisfied and throwing an assertion exception on failure. + + An ActualValueDelegate returning the value to be tested + A Constraint expression to be applied + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Asserts that the code represented by a delegate throws an exception + that satisfies the constraint provided. + + A TestDelegate to be executed + A ThrowsConstraint used in the test + + + + Apply a constraint to an actual value, succeeding if the constraint + is satisfied and throwing an assertion exception on failure. + + A Constraint to be applied + The actual value to test + + + + Apply a constraint to an actual value, succeeding if the constraint + is satisfied and throwing an assertion exception on failure. + + A Constraint expression to be applied + The actual value to test + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Returns a ListMapper based on a collection. + + The original collection + + + + + TextMessageWriter writes constraint descriptions and messages + in displayable form as a text stream. It tailors the display + of individual message components to form the standard message + format of NUnit assertion failure messages. + + + + + Prefix used for the expected value line of a message + + + + + Prefix used for the actual value line of a message + + + + + Length of a message prefix + + + + + Construct a TextMessageWriter + + + + + Construct a TextMessageWriter, specifying a user message + and optional formatting arguments. + + + + + + + Method to write single line message with optional args, usually + written to precede the general failure message, at a given + indentation level. + + The indentation level of the message + The message to be written + Any arguments used in formatting the message + + + + Display Expected and Actual lines for a constraint. This + is called by MessageWriter's default implementation of + WriteMessageTo and provides the generic two-line display. + + The result of the constraint that failed + + + + Display Expected and Actual lines for given _values. This + method may be called by constraints that need more control over + the display of actual and expected _values than is provided + by the default implementation. + + The expected value + The actual value causing the failure + + + + Display Expected and Actual lines for given _values, including + a tolerance value on the expected line. + + The expected value + The actual value causing the failure + The tolerance within which the test was made + + + + Display the expected and actual string _values on separate lines. + If the mismatch parameter is >=0, an additional line is displayed + line containing a caret that points to the mismatch point. + + The expected string value + The actual string value + The point at which the strings don't match or -1 + If true, case is ignored in string comparisons + If true, clip the strings to fit the max line length + + + + Writes the text for an actual value. + + The actual value. + + + + Writes the text for a generalized value. + + The value. + + + + Writes the text for a collection value, + starting at a particular point, to a max length + + The collection containing elements to write. + The starting point of the elements to write + The maximum number of elements to write + + + + Write the generic 'Expected' line for a constraint + + The constraint that failed + + + + Write the generic 'Expected' line for a given value + + The expected value + + + + Write the generic 'Expected' line for a given value + and tolerance. + + The expected value + The tolerance within which the test was made + + + + Write the generic 'Actual' line for a constraint + + The ConstraintResult for which the actual value is to be written + + + + Write the generic 'Actual' line for a given value + + The actual value causing a failure + + + + Gets or sets the maximum line length for this writer + + + + + EventListenerTextWriter sends text output to the currently active + ITestEventListener in the form of a TestOutput object. If no event + listener is active in the contet, or if there is no context, + the output is forwarded to the supplied default writer. + + + + + Construct an EventListenerTextWriter + + The name of the stream to use for events + The default writer to use if no listener is available + + + + Write a single char + + + + + Write a string + + + + + Write a string followed by a newline + + + + + Get the Encoding for this TextWriter + + + + + CollectionSupersetConstraint is used to determine whether + one collection is a superset of another + + + + + Construct a CollectionSupersetConstraint + + The collection that the actual value is expected to be a superset of + + + + Test whether the actual collection is a superset of + the expected collection provided. + + + + + + + Flag the constraint to use the supplied predicate function + + The comparison function to use. + Self. + + + + The display name of this Constraint for use by ToString(). + The default value is the name of the constraint with + trailing "Constraint" removed. Derived classes may set + this to another name in their constructors. + + + + + The Description of what this constraint tests, for + use in messages and in the ConstraintResult. + + + + + ParameterizedMethodSuite holds a collection of individual + TestMethods with their arguments applied. + + + + + Construct from a MethodInfo + + + + + + Gets a string representing the type of test + + + + + + OSPlatform represents a particular operating system platform + + + + + Platform ID for Unix as defined by Microsoft .NET 2.0 and greater + + + + + Platform ID for Unix as defined by Mono + + + + + Platform ID for XBox as defined by .NET and Mono, but not CF + + + + + Platform ID for MacOSX as defined by .NET and Mono, but not CF + + + + + Gets the actual OS Version, not the incorrect value that might be + returned for Win 8.1 and Win 10 + + + If an application is not manifested as Windows 8.1 or Windows 10, + the version returned from Environment.OSVersion will not be 6.3 and 10.0 + respectively, but will be 6.2 and 6.3. The correct value can be found in + the registry. + + The original version + The correct OS version + + + + Construct from a platform ID and version + + + + + Construct from a platform ID, version and product type + + + + + Get the OSPlatform under which we are currently running + + + + + Get the platform ID of this instance + + + + + Get the Version of this instance + + + + + Get the Product Type of this instance + + + + + Return true if this is a windows platform + + + + + Return true if this is a Unix or Linux platform + + + + + Return true if the platform is Win32S + + + + + Return true if the platform is Win32Windows + + + + + Return true if the platform is Win32NT + + + + + Return true if the platform is Windows CE + + + + + Return true if the platform is Xbox + + + + + Return true if the platform is MacOSX + + + + + Return true if the platform is Windows 95 + + + + + Return true if the platform is Windows 98 + + + + + Return true if the platform is Windows ME + + + + + Return true if the platform is NT 3 + + + + + Return true if the platform is NT 4 + + + + + Return true if the platform is NT 5 + + + + + Return true if the platform is Windows 2000 + + + + + Return true if the platform is Windows XP + + + + + Return true if the platform is Windows 2003 Server + + + + + Return true if the platform is NT 6 + + + + + Return true if the platform is NT 6.0 + + + + + Return true if the platform is NT 6.1 + + + + + Return true if the platform is NT 6.2 + + + + + Return true if the platform is NT 6.3 + + + + + Return true if the platform is Vista + + + + + Return true if the platform is Windows 2008 Server (original or R2) + + + + + Return true if the platform is Windows 2008 Server (original) + + + + + Return true if the platform is Windows 2008 Server R2 + + + + + Return true if the platform is Windows 2012 Server (original or R2) + + + + + Return true if the platform is Windows 2012 Server (original) + + + + + Return true if the platform is Windows 2012 Server R2 + + + + + Return true if the platform is Windows 7 + + + + + Return true if the platform is Windows 8 + + + + + Return true if the platform is Windows 8.1 + + + + + Return true if the platform is Windows 10 + + + + + Return true if the platform is Windows Server. This is named Windows + Server 10 to distinguish it from previous versions of Windows Server. + + + + + Product Type Enumeration used for Windows + + + + + Product type is unknown or unspecified + + + + + Product type is Workstation + + + + + Product type is Domain Controller + + + + + Product type is Server + + + + + Combines multiple filters so that a test must pass one + of them in order to pass this filter. + + + + + Constructs an empty OrFilter + + + + + Constructs an AndFilter from an array of filters + + + + + + Checks whether the OrFilter is matched by a test + + The test to be matched + True if any of the component filters pass, otherwise false + + + + Checks whether the OrFilter is matched by a test + + The test to be matched + True if any of the component filters match, otherwise false + + + + Checks whether the OrFilter is explicit matched by a test + + The test to be matched + True if any of the component filters explicit match, otherwise false + + + + Gets the element name + + Element name + + + + InstanceOfTypeConstraint is used to test that an object + is of the same type provided or derived from it. + + + + + Construct an InstanceOfTypeConstraint for the type provided + + The expected Type + + + + Apply the constraint to an actual value, returning true if it succeeds + + The actual argument + True if the constraint succeeds, otherwise false. + + + + The display name of this Constraint for use by ToString(). + The default value is the name of the constraint with + trailing "Constraint" removed. Derived classes may set + this to another name in their constructors. + + + + + Tests whether a value is greater than the value supplied to its constructor + + + + + Initializes a new instance of the class. + + The expected value. + + + + DictionaryContainsKeyConstraint is used to test whether a dictionary + contains an expected object as a key. + + + + + Construct a DictionaryContainsKeyConstraint + + + + + + Test whether the expected key is contained in the dictionary + + + + + The display name of this Constraint for use by ToString(). + The default value is the name of the constraint with + trailing "Constraint" removed. Derived classes may set + this to another name in their constructors. + + + + + The Description of what this constraint tests, for + use in messages and in the ConstraintResult. + + + + + ContainsConstraint tests a whether a string contains a substring + or a collection contains an object. It postpones the decision of + which test to use until the type of the actual argument is known. + This allows testing whether a string is contained in a collection + or as a substring of another string using the same syntax. + + + + + Initializes a new instance of the class. + + The _expected. + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for success, false for failure + + + + The Description of what this constraint tests, for + use in messages and in the ConstraintResult. + + + + + Flag the constraint to ignore case and return self. + + + + + CollectionTally counts (tallies) the number of + occurrences of each object in one or more enumerations. + + + + + Construct a CollectionTally object from a comparer and a collection + + + + + Try to remove an object from the tally + + The object to remove + True if successful, false if the object was not found + + + + Try to remove a set of objects from the tally + + The objects to remove + True if successful, false if any object was not found + + + + The number of objects remaining in the tally + + + + + AllItemsConstraint applies another constraint to each + item in a collection, succeeding if they all succeed. + + + + + Construct an AllItemsConstraint on top of an existing constraint + + + + + + Apply the item constraint to each item in the collection, + failing if any item fails. + + + + + + + The display name of this Constraint for use by ToString(). + The default value is the name of the constraint with + trailing "Constraint" removed. Derived classes may set + this to another name in their constructors. + + + + + A set of Assert methods operating on one or more collections + + + + + The Equals method throws an InvalidOperationException. This is done + to make sure there is no mistake by calling this function. + + + + + + + override the default ReferenceEquals to throw an InvalidOperationException. This + implementation makes sure there is no mistake in calling this function + as part of Assert. + + + + + + + Asserts that all items contained in collection are of the type specified by expectedType. + + IEnumerable containing objects to be considered + System.Type that all objects in collection must be instances of + + + + Asserts that all items contained in collection are of the type specified by expectedType. + + IEnumerable containing objects to be considered + System.Type that all objects in collection must be instances of + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Asserts that all items contained in collection are not equal to null. + + IEnumerable containing objects to be considered + + + + Asserts that all items contained in collection are not equal to null. + + IEnumerable of objects to be considered + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Ensures that every object contained in collection exists within the collection + once and only once. + + IEnumerable of objects to be considered + + + + Ensures that every object contained in collection exists within the collection + once and only once. + + IEnumerable of objects to be considered + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Asserts that expected and actual are exactly equal. The collections must have the same count, + and contain the exact same objects in the same order. + + The first IEnumerable of objects to be considered + The second IEnumerable of objects to be considered + + + + Asserts that expected and actual are exactly equal. The collections must have the same count, + and contain the exact same objects in the same order. + If comparer is not null then it will be used to compare the objects. + + The first IEnumerable of objects to be considered + The second IEnumerable of objects to be considered + The IComparer to use in comparing objects from each IEnumerable + + + + Asserts that expected and actual are exactly equal. The collections must have the same count, + and contain the exact same objects in the same order. + + The first IEnumerable of objects to be considered + The second IEnumerable of objects to be considered + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Asserts that expected and actual are exactly equal. The collections must have the same count, + and contain the exact same objects in the same order. + If comparer is not null then it will be used to compare the objects. + + The first IEnumerable of objects to be considered + The second IEnumerable of objects to be considered + The IComparer to use in comparing objects from each IEnumerable + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Asserts that expected and actual are equivalent, containing the same objects but the match may be in any order. + + The first IEnumerable of objects to be considered + The second IEnumerable of objects to be considered + + + + Asserts that expected and actual are equivalent, containing the same objects but the match may be in any order. + + The first IEnumerable of objects to be considered + The second IEnumerable of objects to be considered + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Asserts that expected and actual are not exactly equal. + + The first IEnumerable of objects to be considered + The second IEnumerable of objects to be considered + + + + Asserts that expected and actual are not exactly equal. + If comparer is not null then it will be used to compare the objects. + + The first IEnumerable of objects to be considered + The second IEnumerable of objects to be considered + The IComparer to use in comparing objects from each IEnumerable + + + + Asserts that expected and actual are not exactly equal. + + The first IEnumerable of objects to be considered + The second IEnumerable of objects to be considered + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Asserts that expected and actual are not exactly equal. + If comparer is not null then it will be used to compare the objects. + + The first IEnumerable of objects to be considered + The second IEnumerable of objects to be considered + The IComparer to use in comparing objects from each IEnumerable + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Asserts that expected and actual are not equivalent. + + The first IEnumerable of objects to be considered + The second IEnumerable of objects to be considered + + + + Asserts that expected and actual are not equivalent. + + The first IEnumerable of objects to be considered + The second IEnumerable of objects to be considered + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Asserts that collection contains actual as an item. + + IEnumerable of objects to be considered + Object to be found within collection + + + + Asserts that collection contains actual as an item. + + IEnumerable of objects to be considered + Object to be found within collection + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Asserts that collection does not contain actual as an item. + + IEnumerable of objects to be considered + Object that cannot exist within collection + + + + Asserts that collection does not contain actual as an item. + + IEnumerable of objects to be considered + Object that cannot exist within collection + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Asserts that the superset does not contain the subset + + The IEnumerable subset to be considered + The IEnumerable superset to be considered + + + + Asserts that the superset does not contain the subset + + The IEnumerable subset to be considered + The IEnumerable superset to be considered + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Asserts that the superset contains the subset. + + The IEnumerable subset to be considered + The IEnumerable superset to be considered + + + + Asserts that the superset contains the subset. + + The IEnumerable subset to be considered + The IEnumerable superset to be considered + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Asserts that the subset does not contain the superset + + The IEnumerable superset to be considered + The IEnumerable subset to be considered + + + + Asserts that the subset does not contain the superset + + The IEnumerable superset to be considered + The IEnumerable subset to be considered + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Asserts that the subset contains the superset. + + The IEnumerable superset to be considered + The IEnumerable subset to be considered + + + + Asserts that the subset contains the superset. + + The IEnumerable superset to be considered + The IEnumerable subset to be considered + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Assert that an array, list or other collection is empty + + An array, list or other collection implementing IEnumerable + The message to be displayed on failure + Arguments to be used in formatting the message + + + + Assert that an array,list or other collection is empty + + An array, list or other collection implementing IEnumerable + + + + Assert that an array, list or other collection is empty + + An array, list or other collection implementing IEnumerable + The message to be displayed on failure + Arguments to be used in formatting the message + + + + Assert that an array,list or other collection is empty + + An array, list or other collection implementing IEnumerable + + + + Assert that an array, list or other collection is ordered + + An array, list or other collection implementing IEnumerable + The message to be displayed on failure + Arguments to be used in formatting the message + + + + Assert that an array, list or other collection is ordered + + An array, list or other collection implementing IEnumerable + + + + Assert that an array, list or other collection is ordered + + An array, list or other collection implementing IEnumerable + A custom comparer to perform the comparisons + The message to be displayed on failure + Arguments to be used in formatting the message + + + + Assert that an array, list or other collection is ordered + + An array, list or other collection implementing IEnumerable + A custom comparer to perform the comparisons + + + + TestCaseSourceAttribute indicates the source to be used to + provide test cases for a test method. + + + + + Construct with the name of the method, property or field that will provide data + + The name of a static method, property or field that will provide data. + + + + Construct with a Type and name + + The Type that will provide data + The name of a static method, property or field that will provide data. + A set of parameters passed to the method, works only if the Source Name is a method. + If the source name is a field or property has no effect. + + + + Construct with a Type and name + + The Type that will provide data + The name of a static method, property or field that will provide data. + + + + Construct with a Type + + The type that will provide data + + + + Construct one or more TestMethods from a given MethodInfo, + using available parameter data. + + The IMethod for which tests are to be constructed. + The suite to which the tests will be added. + One or more TestMethods + + + + Returns a set of ITestCaseDataItems for use as arguments + to a parameterized test method. + + The method for which data is needed. + + + + + A set of parameters passed to the method, works only if the Source Name is a method. + If the source name is a field or property has no effect. + + + + + The name of a the method, property or fiend to be used as a source + + + + + A Type to be used as a source + + + + + Gets or sets the category associated with every fixture created from + this attribute. May be a single category or a comma-separated list. + + + + + TestMethodCommand is the lowest level concrete command + used to run actual test cases. + + + + + Initializes a new instance of the class. + + The test. + + + + Runs the test, saving a TestResult in the execution context, as + well as returning it. If the test has an expected result, it + is asserts on that value. Since failed tests and errors throw + an exception, this command must be wrapped in an outer command, + will handle that exception and records the failure. This role + is usually played by the SetUpTearDown command. + + The execution context + + + + SetUpTearDownCommand runs any SetUp methods for a suite, + runs the test and then runs any TearDown methods. + + + + + Initializes a new instance of the class. + + The inner command. + + + + Runs the test, saving a TestResult in the supplied TestExecutionContext. + + The context in which the test should run. + A TestResult + + + + SetUpTearDownItem holds the setup and teardown methods + for a single level of the inheritance hierarchy. + + + + + Construct a SetUpTearDownNode + + A list of setup methods for this level + A list teardown methods for this level + + + + Run SetUp on this level. + + The execution context to use for running. + + + + Run TearDown for this level. + + + + + + Returns true if this level has any methods at all. + This flag is used to discard levels that do nothing. + + + + + Class used to guard against unexpected argument values + or operations by throwing an appropriate exception. + + + + + Throws an exception if an argument is null + + The value to be tested + The name of the argument + + + + Throws an exception if a string argument is null or empty + + The value to be tested + The name of the argument + + + + Throws an ArgumentOutOfRangeException if the specified condition is not met. + + The condition that must be met + The exception message to be used + The name of the argument + + + + Throws an ArgumentException if the specified condition is not met. + + The condition that must be met + The exception message to be used + The name of the argument + + + + Throws an InvalidOperationException if the specified condition is not met. + + The condition that must be met + The exception message to be used + + + + SubPathConstraint tests that the actual path is under the expected path + + + + + Initializes a new instance of the class. + + The expected path + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for success, false for failure + + + + The Description of what this constraint tests, for + use in messages and in the ConstraintResult. + + + + + ParallelizableAttribute is used to mark tests that may be run in parallel. + + + + + Construct a ParallelizableAttribute using default ParallelScope.Self. + + + + + Construct a ParallelizableAttribute with a specified scope. + + The ParallelScope associated with this attribute. + + + + Modify the context to be used for child tests + + The current TestExecutionContext + + + + Helper class with properties and methods that supply + constraints that operate on exceptions. + + + + + Creates a constraint specifying the exact type of exception expected + + + + + Creates a constraint specifying the exact type of exception expected + + + + + Creates a constraint specifying the type of exception expected + + + + + Creates a constraint specifying the type of exception expected + + + + + Creates a constraint specifying an expected exception + + + + + Creates a constraint specifying an exception with a given InnerException + + + + + Creates a constraint specifying an expected TargetInvocationException + + + + + Creates a constraint specifying an expected ArgumentException + + + + + Creates a constraint specifying an expected ArgumentNUllException + + + + + Creates a constraint specifying an expected InvalidOperationException + + + + + Creates a constraint specifying that no exception is thrown + + + + + Enumeration identifying a common language + runtime implementation. + + + + Any supported runtime framework + + + Microsoft .NET Framework + + + Microsoft .NET Compact Framework + + + Microsoft Shared Source CLI + + + Mono + + + Silverlight + + + MonoTouch + + + + RuntimeFramework represents a particular version + of a common language runtime implementation. + + + + + DefaultVersion is an empty Version, used to indicate that + NUnit should select the CLR version to use for the test. + + + + + Construct from a runtime type and version. If the version has + two parts, it is taken as a framework version. If it has three + or more, it is taken as a CLR version. In either case, the other + version is deduced based on the runtime type and provided version. + + The runtime type of the framework + The version of the framework + + + + Parses a string representing a RuntimeFramework. + The string may be just a RuntimeType name or just + a Version or a hyphenated RuntimeType-Version or + a Version prefixed by 'versionString'. + + + + + + + Overridden to return the short name of the framework + + + + + + Returns true if the current framework matches the + one supplied as an argument. Two frameworks match + if their runtime types are the same or either one + is RuntimeType.Any and all specified version components + are equal. Negative (i.e. unspecified) version + components are ignored. + + The RuntimeFramework to be matched. + True on match, otherwise false + + + + Static method to return a RuntimeFramework object + for the framework that is currently in use. + + + + + The type of this runtime framework + + + + + The framework version for this runtime framework + + + + + The CLR version for this runtime framework + + + + + Return true if any CLR version may be used in + matching this RuntimeFramework object. + + + + + Returns the Display name for this framework + + + + + CategoryFilter is able to select or exclude tests + based on their categories. + + + + + + Construct a CategoryFilter using a single category name + + A category name + + + + Check whether the filter matches a test + + The test to be matched + + + + + Gets the element name + + Element name + + + + GlobalSettings is a place for setting default values used + by the framework in performing asserts. Anything set through + this class applies to the entire test run. It should not normally + be used from within a test, since it is not thread-safe. + + + + + Default tolerance for floating point equality + + + + + Asserts on Files + + + + + The Equals method throws an InvalidOperationException. This is done + to make sure there is no mistake by calling this function. + + + + + + + override the default ReferenceEquals to throw an InvalidOperationException. This + implementation makes sure there is no mistake in calling this function + as part of Assert. + + + + + + + Verifies that two Streams are equal. Two Streams are considered + equal if both are null, or if both have the same value byte for byte. + If they are not equal an is thrown. + + The expected Stream + The actual Stream + The message to display if Streams are not equal + Arguments to be used in formatting the message + + + + Verifies that two Streams are equal. Two Streams are considered + equal if both are null, or if both have the same value byte for byte. + If they are not equal an is thrown. + + The expected Stream + The actual Stream + + + + Verifies that two files are equal. Two files are considered + equal if both are null, or if both have the same value byte for byte. + If they are not equal an is thrown. + + A file containing the value that is expected + A file containing the actual value + The message to display if Streams are not equal + Arguments to be used in formatting the message + + + + Verifies that two files are equal. Two files are considered + equal if both are null, or if both have the same value byte for byte. + If they are not equal an is thrown. + + A file containing the value that is expected + A file containing the actual value + + + + Verifies that two files are equal. Two files are considered + equal if both are null, or if both have the same value byte for byte. + If they are not equal an is thrown. + + The path to a file containing the value that is expected + The path to a file containing the actual value + The message to display if Streams are not equal + Arguments to be used in formatting the message + + + + Verifies that two files are equal. Two files are considered + equal if both are null, or if both have the same value byte for byte. + If they are not equal an is thrown. + + The path to a file containing the value that is expected + The path to a file containing the actual value + + + + Asserts that two Streams are not equal. If they are equal + an is thrown. + + The expected Stream + The actual Stream + The message to be displayed when the two Stream are the same. + Arguments to be used in formatting the message + + + + Asserts that two Streams are not equal. If they are equal + an is thrown. + + The expected Stream + The actual Stream + + + + Asserts that two files are not equal. If they are equal + an is thrown. + + A file containing the value that is expected + A file containing the actual value + The message to display if Streams are not equal + Arguments to be used in formatting the message + + + + Asserts that two files are not equal. If they are equal + an is thrown. + + A file containing the value that is expected + A file containing the actual value + + + + Asserts that two files are not equal. If they are equal + an is thrown. + + The path to a file containing the value that is expected + The path to a file containing the actual value + The message to display if Streams are not equal + Arguments to be used in formatting the message + + + + Asserts that two files are not equal. If they are equal + an is thrown. + + The path to a file containing the value that is expected + The path to a file containing the actual value + + + + Asserts that the file exists. If it does not exist + an is thrown. + + A file containing the actual value + The message to display if Streams are not equal + Arguments to be used in formatting the message + + + + Asserts that the file exists. If it does not exist + an is thrown. + + A file containing the actual value + + + + Asserts that the file exists. If it does not exist + an is thrown. + + The path to a file containing the actual value + The message to display if Streams are not equal + Arguments to be used in formatting the message + + + + Asserts that the file exists. If it does not exist + an is thrown. + + The path to a file containing the actual value + + + + Asserts that the file does not exist. If it does exist + an is thrown. + + A file containing the actual value + The message to display if Streams are not equal + Arguments to be used in formatting the message + + + + Asserts that the file does not exist. If it does exist + an is thrown. + + A file containing the actual value + + + + Asserts that the file does not exist. If it does exist + an is thrown. + + The path to a file containing the actual value + The message to display if Streams are not equal + Arguments to be used in formatting the message + + + + Asserts that the file does not exist. If it does exist + an is thrown. + + The path to a file containing the actual value + + + + Thrown when an assertion failed. + + + + + + + The error message that explains + the reason for the exception + The exception that caused the + current exception + + + + Serialization Constructor + + + + + Gets the ResultState provided by this exception + + + + + SomeItemsConstraint applies another constraint to each + item in a collection, succeeding if any of them succeeds. + + + + + Construct a SomeItemsConstraint on top of an existing constraint + + + + + + Apply the item constraint to each item in the collection, + succeeding if any item succeeds. + + + + + + + The display name of this Constraint for use by ToString(). + The default value is the name of the constraint with + trailing "Constraint" removed. Derived classes may set + this to another name in their constructors. + + + + + SameAsConstraint tests whether an object is identical to + the object passed to its constructor + + + + + Initializes a new instance of the class. + + The expected object. + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for success, false for failure + + + + The Description of what this constraint tests, for + use in messages and in the ConstraintResult. + + + + + RegexConstraint can test whether a string matches + the pattern provided. + + + + + Initializes a new instance of the class. + + The pattern. + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for success, false for failure + + + + ConstraintStatus represents the status of a ConstraintResult + returned by a Constraint being applied to an actual value. + + + + + The status has not yet been set + + + + + The constraint succeeded + + + + + The constraint failed + + + + + An error occured in applying the constraint (reserved for future use) + + + + + Attribute used to identify a method that is called + immediately after each test is run. The method is + guaranteed to be called, even if an exception is thrown. + + + + + Marks a test to use a combinatorial join of any argument + data provided. Since this is the default, the attribute is + optional. + + + + + Default constructor + + + + + The PropertyNames class provides static constants for the + standard property ids that NUnit uses on tests. + + + + + The FriendlyName of the AppDomain in which the assembly is running + + + + + The selected strategy for joining parameter data into test cases + + + + + The process ID of the executing assembly + + + + + The stack trace from any data provider that threw + an exception. + + + + + The reason a test was not run + + + + + The author of the tests + + + + + The ApartmentState required for running the test + + + + + The categories applying to a test + + + + + The Description of a test + + + + + The number of threads to be used in running tests + + + + + The maximum time in ms, above which the test is considered to have failed + + + + + The ParallelScope associated with a test + + + + + The number of times the test should be repeated + + + + + Indicates that the test should be run on a separate thread + + + + + The culture to be set for a test + + + + + The UI culture to be set for a test + + + + + The type that is under test + + + + + The timeout value for the test + + + + + The test will be ignored until the given date + + + + + The optional Order the test will run in + + + + + The MethodWrapper class wraps a MethodInfo so that it may + be used in a platform-independent manner. + + + + + Construct a MethodWrapper for a Type and a MethodInfo. + + + + + Construct a MethodInfo for a given Type and method name. + + + + + Gets the parameters of the method. + + + + + + Returns the Type arguments of a generic method or the Type parameters of a generic method definition. + + + + + Replaces the type parameters of the method with the array of types provided and returns a new IMethodInfo. + + The type arguments to be used + A new IMethodInfo with the type arguments replaced + + + + Returns an array of custom attributes of the specified type applied to this method + + + + + Gets a value indicating whether one or more attributes of the spcified type are defined on the method. + + + + + Invokes the method, converting any TargetInvocationException to an NUnitException. + + The object on which to invoke the method + The argument list for the method + The return value from the invoked method + + + + Override ToString() so that error messages in NUnit's own tests make sense + + + + + Gets the Type from which this method was reflected. + + + + + Gets the MethodInfo for this method. + + + + + Gets the name of the method. + + + + + Gets a value indicating whether the method is abstract. + + + + + Gets a value indicating whether the method is public. + + + + + Gets a value indicating whether the method contains unassigned generic type parameters. + + + + + Gets a value indicating whether the method is a generic method. + + + + + Gets a value indicating whether the MethodInfo represents the definition of a generic method. + + + + + Gets the return Type of the method. + + + + + Represents a constraint that succeeds if any of the + members of a collection match a base constraint. + + + + + Returns a constraint that will apply the argument + to the members of a collection, succeeding if + any of them succeed. + + + + + The TestMethod class represents a Test implemented as a method. + + + + + The ParameterSet used to create this test method + + + + + Initializes a new instance of the class. + + The method to be used as a test. + + + + Initializes a new instance of the class. + + The method to be used as a test. + The suite or fixture to which the new test will be added + + + + Overridden to return a TestCaseResult. + + A TestResult for this test. + + + + Returns a TNode representing the current result after + adding it as a child of the supplied parent node. + + The parent node. + If true, descendant results are included + + + + + Gets a bool indicating whether the current test + has any descendant tests. + + + + + Gets this test's child tests + + A list of child tests + + + + Gets the name used for the top-level element in the + XML representation of this test + + + + + Returns the name of the method + + + + + RangeConstraint tests whether two _values are within a + specified range. + + + + + Initializes a new instance of the class. + + from must be less than or equal to true + Inclusive beginning of the range. Must be less than or equal to to. + Inclusive end of the range. Must be greater than or equal to from. + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for success, false for failure + + + + Modifies the constraint to use an and returns self. + + + + + Modifies the constraint to use an and returns self. + + + + + Modifies the constraint to use a and returns self. + + + + + Gets text describing a constraint + + + + + Tests whether a value is greater than or equal to the value supplied to its constructor + + + + + Initializes a new instance of the class. + + The expected value. + + + + Delegate used to delay evaluation of the actual value + to be used in evaluating a constraint + + + + + AttributeConstraint tests that a specified attribute is present + on a Type or other provider and that the value of the attribute + satisfies some other constraint. + + + + + Constructs an AttributeConstraint for a specified attribute + Type and base constraint. + + + + + + + Determines whether the Type or other provider has the + expected attribute and if its value matches the + additional constraint specified. + + + + + Returns a string representation of the constraint. + + + + + ValueSourceAttribute indicates the source to be used to + provide data for one parameter of a test method. + + + + + Construct with the name of the factory - for use with languages + that don't support params arrays. + + The name of a static method, property or field that will provide data. + + + + Construct with a Type and name - for use with languages + that don't support params arrays. + + The Type that will provide data + The name of a static method, property or field that will provide data. + + + + Gets an enumeration of data items for use as arguments + for a test method parameter. + + The parameter for which data is needed + + An enumeration containing individual data items + + + + + The name of a the method, property or fiend to be used as a source + + + + + A Type to be used as a source + + + + + Summary description for SetCultureAttribute. + + + + + Construct given the name of a culture + + + + + + RandomAttribute is used to supply a set of random _values + to a single parameter of a parameterized test. + + + + + Construct a random set of values appropriate for the Type of the + parameter on which the attribute appears, specifying only the count. + + + + + + Construct a set of ints within a specified range + + + + + Construct a set of unsigned ints within a specified range + + + + + Construct a set of longs within a specified range + + + + + Construct a set of unsigned longs within a specified range + + + + + Construct a set of shorts within a specified range + + + + + Construct a set of unsigned shorts within a specified range + + + + + Construct a set of doubles within a specified range + + + + + Construct a set of floats within a specified range + + + + + Construct a set of bytes within a specified range + + + + + Construct a set of sbytes within a specified range + + + + + Get the collection of _values to be used as arguments. + + + + + Delegate used by tests that execute code and + capture any thrown exception. + + + + + TNode represents a single node in the XML representation + of a Test or TestResult. It replaces System.Xml.XmlNode and + System.Xml.Linq.XElement, providing a minimal set of methods + for operating on the XML in a platform-independent manner. + + + + + Constructs a new instance of TNode + + The name of the node + + + + Constructs a new instance of TNode with a value + + The name of the node + The text content of the node + + + + Constructs a new instance of TNode with a value + + The name of the node + The text content of the node + Flag indicating whether to use CDATA when writing the text + + + + Create a TNode from it's XML text representation + + The XML text to be parsed + A TNode + + + + Adds a new element as a child of the current node and returns it. + + The element name. + The newly created child element + + + + Adds a new element with a value as a child of the current node and returns it. + + The element name + The text content of the new element + The newly created child element + + + + Adds a new element with a value as a child of the current node and returns it. + The value will be output using a CDATA section. + + The element name + The text content of the new element + The newly created child element + + + + Adds an attribute with a specified name and value to the XmlNode. + + The name of the attribute. + The value of the attribute. + + + + Finds a single descendant of this node matching an xpath + specification. The format of the specification is + limited to what is needed by NUnit and its tests. + + + + + + + Finds all descendants of this node matching an xpath + specification. The format of the specification is + limited to what is needed by NUnit and its tests. + + + + + Writes the XML representation of the node to an XmlWriter + + + + + + Gets the name of the node + + + + + Gets the value of the node + + + + + Gets a flag indicating whether the value should be output using CDATA. + + + + + Gets the dictionary of attributes + + + + + Gets a list of child nodes + + + + + Gets the first ChildNode + + + + + Gets the XML representation of this node. + + + + + Class used to represent a list of XmlResults + + + + + Class used to represent the attributes of a node + + + + + Gets or sets the value associated with the specified key. + Overridden to return null if attribute is not found. + + The key. + Value of the attribute or null + + + + The ITestAssemblyRunner interface is implemented by classes + that are able to execute a suite of tests loaded + from an assembly. + + + + + Loads the tests found in an Assembly, returning an + indication of whether or not the load succeeded. + + File name of the assembly to load + Dictionary of options to use in loading the test + An ITest representing the loaded tests + + + + Loads the tests found in an Assembly, returning an + indication of whether or not the load succeeded. + + The assembly to load + Dictionary of options to use in loading the test + An ITest representing the loaded tests + + + + Count Test Cases using a filter + + The filter to apply + The number of test cases found + + + + Run selected tests and return a test result. The test is run synchronously, + and the listener interface is notified as it progresses. + + Interface to receive ITestListener notifications. + A test filter used to select tests to be run + + + + Run selected tests asynchronously, notifying the listener interface as it progresses. + + Interface to receive EventListener notifications. + A test filter used to select tests to be run + + + + Wait for the ongoing run to complete. + + Time to wait in milliseconds + True if the run completed, otherwise false + + + + Signal any test run that is in process to stop. Return without error if no test is running. + + If true, kill any test-running threads + + + + Gets the tree of loaded tests, or null if + no tests have been loaded. + + + + + Gets the tree of test results, if the test + run is completed, otherwise null. + + + + + Indicates whether a test has been loaded + + + + + Indicates whether a test is currently running + + + + + Indicates whether a test run is complete + + + + + Modes in which the tolerance value for a comparison can be interpreted. + + + + + The tolerance was created with a value, without specifying + how the value would be used. This is used to prevent setting + the mode more than once and is generally changed to Linear + upon execution of the test. + + + + + The tolerance is used as a numeric range within which + two compared _values are considered to be equal. + + + + + Interprets the tolerance as the percentage by which + the two compared _values my deviate from each other. + + + + + Compares two _values based in their distance in + representable numbers. + + + + + ResolvableConstraintExpression is used to represent a compound + constraint being constructed at a point where the last operator + may either terminate the expression or may have additional + qualifying constraints added to it. + + It is used, for example, for a Property element or for + an Exception element, either of which may be optionally + followed by constraints that apply to the property or + exception. + + + + + Create a new instance of ResolvableConstraintExpression + + + + + Create a new instance of ResolvableConstraintExpression, + passing in a pre-populated ConstraintBuilder. + + + + + Resolve the current expression to a Constraint + + + + + Appends an And Operator to the expression + + + + + Appends an Or operator to the expression. + + + + + Negates the test of the constraint it wraps. + + + + + Constructs a new NotOperator + + + + + Returns a NotConstraint applied to its argument. + + + + + SetUpFixtureAttribute is used to identify a SetUpFixture + + + + + Build a SetUpFixture from type provided. Normally called for a Type + on which the attribute has been placed. + + The type info of the fixture to be used. + A SetUpFixture object as a TestSuite. + + + + Marks a test that must run in the MTA, causing it + to run in a separate thread if necessary. + + On methods, you may also use MTAThreadAttribute + to serve the same purpose. + + + + + Construct a RequiresMTAAttribute + + + + + The ResultState class represents the outcome of running a test. + It contains two pieces of information. The Status of the test + is an enum indicating whether the test passed, failed, was + skipped or was inconclusive. The Label provides a more + detailed breakdown for use by client runners. + + + + + Initializes a new instance of the class. + + The TestStatus. + + + + Initializes a new instance of the class. + + The TestStatus. + The label. + + + + Initializes a new instance of the class. + + The TestStatus. + The stage at which the result was produced + + + + Initializes a new instance of the class. + + The TestStatus. + The label. + The stage at which the result was produced + + + + The result is inconclusive + + + + + The test has been skipped. + + + + + The test has been ignored. + + + + + The test was skipped because it is explicit + + + + + The test succeeded + + + + + The test failed + + + + + The test encountered an unexpected exception + + + + + The test was cancelled by the user + + + + + The test was not runnable. + + + + + A suite failed because one or more child tests failed or had errors + + + + + A suite failed in its OneTimeSetUp + + + + + A suite had an unexpected exception in its OneTimeSetUp + + + + + A suite had an unexpected exception in its OneTimeDown + + + + + Get a new ResultState, which is the same as the current + one but with the FailureSite set to the specified value. + + The FailureSite to use + A new ResultState + + + + Determines whether the specified , is equal to this instance. + + The to compare with this instance. + + true if the specified is equal to this instance; otherwise, false. + + + + + Returns a hash code for this instance. + + + A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. + + + + + Returns a that represents this instance. + + + A that represents this instance. + + + + + Gets the TestStatus for the test. + + The status. + + + + Gets the label under which this test result is + categorized, if any. + + + + + Gets the stage of test execution in which + the failure or other result took place. + + + + + The FailureSite enum indicates the stage of a test + in which an error or failure occurred. + + + + + Failure in the test itself + + + + + Failure in the SetUp method + + + + + Failure in the TearDown method + + + + + Failure of a parent test + + + + + Failure of a child test + + + + + The TestFixtureData class represents a set of arguments + and other parameter info to be used for a parameterized + fixture. It is derived from TestFixtureParameters and adds a + fluent syntax for use in initializing the fixture. + + + + + Initializes a new instance of the class. + + The arguments. + + + + Initializes a new instance of the class. + + The argument. + + + + Initializes a new instance of the class. + + The first argument. + The second argument. + + + + Initializes a new instance of the class. + + The first argument. + The second argument. + The third argument. + + + + Marks the test fixture as explicit. + + + + + Marks the test fixture as explicit, specifying the reason. + + + + + Ignores this TestFixture, specifying the reason. + + The reason. + + + + + Represents a thread-safe first-in, first-out collection of objects. + + Specifies the type of elements in the queue. + + All public and protected members of are thread-safe and may be used + concurrently from multiple threads. + + + + + Initializes a new instance of the class. + + + + + Initializes a new instance of the + class that contains elements copied from the specified collection + + The collection whose elements are copied to the new . + The argument is + null. + + + + Adds an object to the end of the . + + The object to add to the end of the . The value can be a null reference + (Nothing in Visual Basic) for reference types. + + + + + Attempts to add an object to the . + + The object to add to the . The value can be a null + reference (Nothing in Visual Basic) for reference types. + + true if the object was added successfully; otherwise, false. + For , this operation will always add the object to the + end of the + and return true. + + + + Attempts to remove and return the object at the beginning of the . + + + When this method returns, if the operation was successful, contains the + object removed. If no object was available to be removed, the value is unspecified. + + true if an element was removed and returned from the beginning of the + successfully; otherwise, false. + + + + Attempts to return an object from the beginning of the + without removing it. + + When this method returns, contains an object from + the beginning of the or an + unspecified value if the operation failed. + true if and object was returned successfully; otherwise, false. + + + + Returns an enumerator that iterates through a collection. + + An that can be used to iterate through the collection. + + + + Returns an enumerator that iterates through the . + + An enumerator for the contents of the . + + The enumeration represents a moment-in-time snapshot of the contents + of the queue. It does not reflect any updates to the collection after + was called. The enumerator is safe to use + concurrently with reads from and writes to the queue. + + + + + Copies the elements of the to an , starting at a particular + index. + + The one-dimensional Array that is the + destination of the elements copied from the + . The Array must have zero-based indexing. + The zero-based index in at which copying + begins. + is a null reference (Nothing in + Visual Basic). + is less than + zero. + + is multidimensional. -or- + does not have zero-based indexing. -or- + is equal to or greater than the length of the + -or- The number of elements in the source is + greater than the available space from to the end of the destination + . -or- The type of the source cannot be cast automatically to the type of the + destination . + + + + + Copies the elements to an existing one-dimensional Array, starting at the specified array index. + + The one-dimensional Array that is the + destination of the elements copied from the + . The Array must have zero-based + indexing. + The zero-based index in at which copying + begins. + is a null reference (Nothing in + Visual Basic). + is less than + zero. + is equal to or greater than the + length of the + -or- The number of elements in the source is greater than the + available space from to the end of the destination . + + + + + Copies the elements stored in the to a new array. + + A new array containing a snapshot of elements copied from the . + + + + Attempts to remove and return an object from the . + + + When this method returns, if the operation was successful, contains the + object removed. If no object was available to be removed, the value is unspecified. + + true if an element was removed and returned successfully; otherwise, false. + For , this operation will attempt to remove the object + from the beginning of the . + + + + + Gets a value indicating whether access to the is + synchronized with the SyncRoot. + + true if access to the is synchronized + with the SyncRoot; otherwise, false. For , this property always + returns false. + + + + Gets an object that can be used to synchronize access to the . This property is not supported. + + The SyncRoot property is not supported. + + + + Gets the number of elements contained in the . + + The number of elements contained in the . + + For determining whether the collection contains any items, use of the + property is recommended rather than retrieving the number of items from the + property and comparing it to 0. + + + + + Gets a value that indicates whether the is empty. + + true if the is empty; otherwise, false. + + For determining whether the collection contains any items, use of this property is recommended + rather than retrieving the number of items from the property and comparing it + to 0. However, as this collection is intended to be accessed concurrently, it may be the case + that another thread will modify the collection after returns, thus invalidating + the result. + + + + + Implementation of ITestAssemblyRunner + + + + + Initializes a new instance of the class. + + The builder. + + + + Loads the tests found in an Assembly + + File name of the assembly to load + Dictionary of option settings for loading the assembly + True if the load was successful + + + + Loads the tests found in an Assembly + + The assembly to load + Dictionary of option settings for loading the assembly + True if the load was successful + + + + Count Test Cases using a filter + + The filter to apply + The number of test cases found + + + + Run selected tests and return a test result. The test is run synchronously, + and the listener interface is notified as it progresses. + + Interface to receive EventListener notifications. + A test filter used to select tests to be run + + + + + Run selected tests asynchronously, notifying the listener interface as it progresses. + + Interface to receive EventListener notifications. + A test filter used to select tests to be run + + RunAsync is a template method, calling various abstract and + virtual methods to be overridden by derived classes. + + + + + Wait for the ongoing run to complete. + + Time to wait in milliseconds + True if the run completed, otherwise false + + + + Signal any test run that is in process to stop. Return without error if no test is running. + + If true, kill any tests that are currently running + + + + Initiate the test run. + + + + + Create the initial TestExecutionContext used to run tests + + The ITestListener specified in the RunAsync call + + + + Handle the the Completed event for the top level work item + + + + + The tree of tests that was loaded by the builder + + + + + The test result, if a run has completed + + + + + Indicates whether a test is loaded + + + + + Indicates whether a test is running + + + + + Indicates whether a test run is complete + + + + + Our settings, specified when loading the assembly + + + + + The top level WorkItem created for the assembly as a whole + + + + + The TestExecutionContext for the top level WorkItem + + + + diff --git a/KerbalVR/Library/PackageCache/com.unity.ext.nunit@1.0.0/package.json b/KerbalVR/Library/PackageCache/com.unity.ext.nunit@1.0.0/package.json new file mode 100644 index 00000000..c0bc305f --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ext.nunit@1.0.0/package.json @@ -0,0 +1,16 @@ +{ + "displayName": "Custom NUnit", + "name": "com.unity.ext.nunit", + "version": "1.0.0", + "unity": "2019.1", + "description": "Custom version of the nunit package build to work with Unity. Used by the Unity Test Framework.", + "keywords": ["nunit", "unittest", "test"], + "category": "Libraries", + "repository": { + "type": "git", + "url": "git@gitlab.cds.internal.unity3d.com/upm-packages/core/com.unity.ext.nunit.git", + "revision": "c8f5044ffe6adb909f9836160b0bdaa30f2d1ec9" + }, + "dependencies": { + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/.editorconfig b/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/.editorconfig new file mode 100644 index 00000000..aca19790 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/.editorconfig @@ -0,0 +1,6 @@ +root = true + +[*] +indent_style = space +indent_size = 2 +end_of_line = lf \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/CHANGELOG.md b/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/CHANGELOG.md new file mode 100644 index 00000000..0e14adce --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/CHANGELOG.md @@ -0,0 +1,43 @@ +# Code Editor Package for Rider + +## [1.1.0] - 2019-07-02 + +new setting to manage list of extensions to be opened with Rider +avoid breaking everything on any unhandled exception in RiderScriptEditor cctor +hide Rider settings, when different Editor is selected +dynamically load only newer rider plugins +path detection (work on unix symlinks) +speed up for project generation +lots of bug fixing + +## [1.0.8] - 2019-05-20 + +Fix NullReferenceException when External editor was pointing to non-existing Rider everything was broken by null-ref. + +## [1.0.7] - 2019-05-16 + +Initial migration steps from rider plugin to package. +Fix OSX check and opening of files. + +## [1.0.6] - 2019-04-30 + +Ensure asset database is refreshed when generating csproj and solution files. + +## [1.0.5] - 2019-04-27 + +Add support for generating all csproj files. + +## [1.0.4] - 2019-04-18 + +Fix relative package paths. +Fix opening editor on mac. + +## [1.0.3] - 2019-04-12 + +Fixing null reference issue for callbacks to Asset pipeline. + +## [1.0.2] - 2019-01-01 + +### This is the first release of *Unity Package rider_editor*. + +Using the newly created api to integrate Rider with Unity. diff --git a/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/CONTRIBUTING.md b/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/CONTRIBUTING.md new file mode 100644 index 00000000..576d0963 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/CONTRIBUTING.md @@ -0,0 +1,6 @@ +# Contributing + +## All contributions are subject to the [Unity Contribution Agreement(UCA)](https://unity3d.com/legal/licenses/Unity_Contribution_Agreement) +By making a pull request, you are confirming agreement to the terms and conditions of the UCA, including that your Contributions are your original creation and that you have complete right and authority to make your Contributions. + +## Once you have a change ready following these ground rules. Simply make a pull request \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/LICENSE.md b/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/LICENSE.md new file mode 100644 index 00000000..eb18dfb7 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/LICENSE.md @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Unity Technologies + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/Rider/Editor/Discovery.cs b/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/Rider/Editor/Discovery.cs new file mode 100644 index 00000000..4886aa7c --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/Rider/Editor/Discovery.cs @@ -0,0 +1,418 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using JetBrains.Annotations; +using Microsoft.Win32; +using Unity.CodeEditor; +using UnityEngine; + +namespace Packages.Rider.Editor +{ + public interface IDiscovery + { + CodeEditor.Installation[] PathCallback(); + } + + public class Discovery : IDiscovery + { + public CodeEditor.Installation[] PathCallback() + { + return RiderPathLocator.GetAllRiderPaths() + .Select(riderInfo => new CodeEditor.Installation + { + Path = riderInfo.Path, + Name = riderInfo.Presentation + }) + .OrderBy(a=>a.Name) + .ToArray(); + } + } + + /// + /// This code is a modified version of the JetBrains resharper-unity plugin listed here: + /// https://github.com/JetBrains/resharper-unity/blob/master/unity/JetBrains.Rider.Unity.Editor/EditorPlugin/RiderPathLocator.cs + /// + public static class RiderPathLocator + { +#if !(UNITY_4_7 || UNITY_5_5) + [UsedImplicitly] // Used in com.unity.ide.rider + public static RiderInfo[] GetAllRiderPaths() + { + try + { + switch (SystemInfo.operatingSystemFamily) + { + case OperatingSystemFamily.Windows: + { + return CollectRiderInfosWindows(); + } + + case OperatingSystemFamily.MacOSX: + { + return CollectRiderInfosMac(); + } + + case OperatingSystemFamily.Linux: + { + return CollectAllRiderPathsLinux(); + } + } + } + catch (Exception e) + { + Debug.LogException(e); + } + + return new RiderInfo[0]; + } +#endif + +#if RIDER_EDITOR_PLUGIN // can't be used in com.unity.ide.rider + internal static RiderInfo[] GetAllFoundInfos(OperatingSystemFamilyRider operatingSystemFamily) + { + try + { + switch (operatingSystemFamily) + { + case OperatingSystemFamilyRider.Windows: + { + return CollectRiderInfosWindows(); + } + case OperatingSystemFamilyRider.MacOSX: + { + return CollectRiderInfosMac(); + } + case OperatingSystemFamilyRider.Linux: + { + return CollectAllRiderPathsLinux(); + } + } + } + catch (Exception e) + { + Debug.LogException(e); + } + + return new RiderInfo[0]; + } + + internal static string[] GetAllFoundPaths(OperatingSystemFamilyRider operatingSystemFamily) + { + return GetAllFoundInfos(operatingSystemFamily).Select(a=>a.Path).ToArray(); + } +#endif + + private static RiderInfo[] CollectAllRiderPathsLinux() + { + var home = Environment.GetEnvironmentVariable("HOME"); + if (string.IsNullOrEmpty(home)) + return new RiderInfo[0]; + + //$Home/.local/share/JetBrains/Toolbox/apps/Rider/ch-0/173.3994.1125/bin/rider.sh + //$Home/.local/share/JetBrains/Toolbox/apps/Rider/ch-0/.channel.settings.json + var toolboxRiderRootPath = Path.Combine(home, @".local/share/JetBrains/Toolbox/apps/Rider"); + var paths = CollectPathsFromToolbox(toolboxRiderRootPath, "bin", "rider.sh", false) + .Select(a => new RiderInfo(a, true)).ToList(); + + //$Home/.local/share/applications/jetbrains-rider.desktop + var shortcut = new FileInfo(Path.Combine(home, @".local/share/applications/jetbrains-rider.desktop")); + + if (shortcut.Exists) + { + var lines = File.ReadAllLines(shortcut.FullName); + foreach (var line in lines) + { + if (!line.StartsWith("Exec=\"")) + continue; + var path = line.Split('"').Where((item, index) => index == 1).SingleOrDefault(); + if (string.IsNullOrEmpty(path)) + continue; + + if (paths.Any(a => a.Path == path)) // avoid adding similar build as from toolbox + continue; + paths.Add(new RiderInfo(path, false)); + } + } + + // snap install + var snapInstallPath = "/snap/rider/current/bin/rider.sh"; + if (new FileInfo(snapInstallPath).Exists) + paths.Add(new RiderInfo(snapInstallPath, false)); + + return paths.ToArray(); + } + + private static RiderInfo[] CollectRiderInfosMac() + { + // "/Applications/*Rider*.app" + var folder = new DirectoryInfo("/Applications"); + if (!folder.Exists) + return new RiderInfo[0]; + + var results = folder.GetDirectories("*Rider*.app") + .Select(a => new RiderInfo(a.FullName, false)) + .ToList(); + + // /Users/user/Library/Application Support/JetBrains/Toolbox/apps/Rider/ch-1/181.3870.267/Rider EAP.app + var home = Environment.GetEnvironmentVariable("HOME"); + if (!string.IsNullOrEmpty(home)) + { + var toolboxRiderRootPath = Path.Combine(home, @"Library/Application Support/JetBrains/Toolbox/apps/Rider"); + var paths = CollectPathsFromToolbox(toolboxRiderRootPath, "", "Rider*.app", true) + .Select(a => new RiderInfo(a, true)); + results.AddRange(paths); + } + + return results.ToArray(); + } + + internal static string GetBuildNumber(string path) + { + var file = new FileInfo(Path.Combine(path, GetRelativePathToBuildTxt())); + if (!file.Exists) + return string.Empty; + var text = File.ReadAllText(file.FullName); + if (text.Length > 3) + return text.Substring(3); + return string.Empty; + } + + private static RiderInfo[] CollectRiderInfosWindows() + { + var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + var toolboxRiderRootPath = Path.Combine(localAppData, @"JetBrains\Toolbox\apps\Rider"); + var installPathsToolbox = CollectPathsFromToolbox(toolboxRiderRootPath, "bin", "rider64.exe", false).ToList(); + var installInfosToolbox = installPathsToolbox + .Select(a => new RiderInfo(a, true)).ToList(); + + var installPaths = new List(); + const string registryKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"; + CollectPathsFromRegistry(registryKey, installPaths); + const string wowRegistryKey = @"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall"; + CollectPathsFromRegistry(wowRegistryKey, installPaths); + + var installInfos = installPaths + .Select(a => new RiderInfo(a, false)).ToList(); + installInfos.AddRange(installInfosToolbox); + + return installInfos.ToArray(); + } + + private static string GetRelativePathToBuildTxt() + { + switch (SystemInfo.operatingSystemFamily) + { + case OperatingSystemFamily.Windows: + case OperatingSystemFamily.Linux: + return "../../build.txt"; + case OperatingSystemFamily.MacOSX: + return "Contents/Resources/build.txt"; + } + throw new Exception("Unknown OS"); + } + + private static void CollectPathsFromRegistry(string registryKey, List installPaths) + { + using (var key = Registry.LocalMachine.OpenSubKey(registryKey)) + { + if (key == null) return; + foreach (var subkeyName in key.GetSubKeyNames().Where(a => a.Contains("Rider"))) + { + using (var subkey = key.OpenSubKey(subkeyName)) + { + var folderObject = subkey?.GetValue("InstallLocation"); + if (folderObject == null) continue; + var folder = folderObject.ToString(); + var possiblePath = Path.Combine(folder, @"bin\rider64.exe"); + if (File.Exists(possiblePath)) + installPaths.Add(possiblePath); + } + } + } + } + + private static string[] CollectPathsFromToolbox(string toolboxRiderRootPath, string dirName, string searchPattern, + bool isMac) + { + if (!Directory.Exists(toolboxRiderRootPath)) + return new string[0]; + + var channelDirs = Directory.GetDirectories(toolboxRiderRootPath); + var paths = channelDirs.SelectMany(channelDir => + { + try + { + // use history.json - last entry stands for the active build https://jetbrains.slack.com/archives/C07KNP99D/p1547807024066500?thread_ts=1547731708.057700&cid=C07KNP99D + var historyFile = Path.Combine(channelDir, ".history.json"); + if (File.Exists(historyFile)) + { + var json = File.ReadAllText(historyFile); + var build = ToolboxHistory.GetLatestBuildFromJson(json); + if (build != null) + { + var buildDir = Path.Combine(channelDir, build); + var executablePaths = GetExecutablePaths(dirName, searchPattern, isMac, buildDir); + if (executablePaths.Any()) + return executablePaths; + } + } + + var channelFile = Path.Combine(channelDir, ".channel.settings.json"); + if (File.Exists(channelFile)) + { + var json = File.ReadAllText(channelFile).Replace("active-application", "active_application"); + var build = ToolboxInstallData.GetLatestBuildFromJson(json); + if (build != null) + { + var buildDir = Path.Combine(channelDir, build); + var executablePaths = GetExecutablePaths(dirName, searchPattern, isMac, buildDir); + if (executablePaths.Any()) + return executablePaths; + } + } + + // changes in toolbox json files format may brake the logic above, so return all found Rider installations + return Directory.GetDirectories(channelDir) + .SelectMany(buildDir => GetExecutablePaths(dirName, searchPattern, isMac, buildDir)); + } + catch (Exception e) + { + // do not write to Debug.Log, just log it. + Logger.Warn($"Failed to get RiderPath from {channelDir}", e); + } + + return new string[0]; + }) + .Where(c => !string.IsNullOrEmpty(c)) + .ToArray(); + return paths; + } + + private static string[] GetExecutablePaths(string dirName, string searchPattern, bool isMac, string buildDir) + { + var folder = new DirectoryInfo(Path.Combine(buildDir, dirName)); + if (!folder.Exists) + return new string[0]; + + if (!isMac) + return new[] {Path.Combine(folder.FullName, searchPattern)}.Where(File.Exists).ToArray(); + return folder.GetDirectories(searchPattern).Select(f => f.FullName) + .Where(Directory.Exists).ToArray(); + } + + // Disable the "field is never assigned" compiler warning. We never assign it, but Unity does. + // Note that Unity disable this warning in the generated C# projects +#pragma warning disable 0649 + + [Serializable] + class ToolboxHistory + { + public List history; + + [CanBeNull] + public static string GetLatestBuildFromJson(string json) + { + try + { +#if UNITY_4_7 || UNITY_5_5 + return JsonConvert.DeserializeObject(json).history.LastOrDefault()?.item.build; +#else + return JsonUtility.FromJson(json).history.LastOrDefault()?.item.build; +#endif + } + catch (Exception) + { + Logger.Warn($"Failed to get latest build from json {json}"); + } + + return null; + } + } + + [Serializable] + class ItemNode + { + public BuildNode item; + } + + [Serializable] + class BuildNode + { + public string build; + } + + // ReSharper disable once ClassNeverInstantiated.Global + [Serializable] + class ToolboxInstallData + { + // ReSharper disable once InconsistentNaming + public ActiveApplication active_application; + + [CanBeNull] + public static string GetLatestBuildFromJson(string json) + { + try + { +#if UNITY_4_7 || UNITY_5_5 + var toolbox = JsonConvert.DeserializeObject(json); +#else + var toolbox = JsonUtility.FromJson(json); +#endif + var builds = toolbox.active_application.builds; + if (builds != null && builds.Any()) + return builds.First(); + } + catch (Exception) + { + Logger.Warn($"Failed to get latest build from json {json}"); + } + + return null; + } + } + + [Serializable] + class ActiveApplication + { + // ReSharper disable once InconsistentNaming + public List builds; + } + +#pragma warning restore 0649 + + public struct RiderInfo + { + public string Presentation; + public string BuildVersion; + public string Path; + + public RiderInfo(string path, bool isToolbox) + { + BuildVersion = GetBuildNumber(path); + Path = new FileInfo(path).FullName; // normalize separators + var presentation = "Rider " + BuildVersion; + if (isToolbox) + presentation += " (JetBrains Toolbox)"; + + Presentation = presentation; + } + } + + private static class Logger + { + internal static void Warn(string message, Exception e = null) + { +#if RIDER_EDITOR_PLUGIN // can't be used in com.unity.ide.rider + Log.GetLog(typeof(RiderPathLocator).Name).Warn(message); + if (e != null) + Log.GetLog(typeof(RiderPathLocator).Name).Warn(e); +#else + Debug.LogError(message); + if (e != null) + Debug.LogException(e); +#endif + } + } + } +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/Rider/Editor/EditorPluginInterop.cs b/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/Rider/Editor/EditorPluginInterop.cs new file mode 100644 index 00000000..1c09b83d --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/Rider/Editor/EditorPluginInterop.cs @@ -0,0 +1,123 @@ +using System; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using UnityEngine; + +namespace Packages.Rider.Editor +{ + public static class EditorPluginInterop + { + private static string ourEntryPointTypeName = "JetBrains.Rider.Unity.Editor.PluginEntryPoint"; + + private static void DisableSyncSolutionOnceCallBack() + { + // RiderScriptableSingleton.Instance.CsprojProcessedOnce = true; + // Otherwise EditorPlugin regenerates all on every AppDomain reload + var assembly = GetEditorPluginAssembly(); + if (assembly == null) return; + var type = assembly.GetType("JetBrains.Rider.Unity.Editor.Utils.RiderScriptableSingleton"); + if (type == null) return; + var baseType = type.BaseType; + if (baseType == null) return; + var instance = baseType.GetProperty("Instance"); + if (instance == null) return; + var instanceVal = instance.GetValue(null); + var member = type.GetProperty("CsprojProcessedOnce"); + if (member==null) return; + member.SetValue(instanceVal, true); + } + + public static string LogPath + { + get + { + try + { + var assembly = GetEditorPluginAssembly(); + if (assembly == null) return null; + var type = assembly.GetType(ourEntryPointTypeName); + if (type == null) return null; + var field = type.GetField("LogPath", BindingFlags.NonPublic | BindingFlags.Static); + if (field == null) return null; + return field.GetValue(null) as string; + } + catch (Exception) + { + Debug.Log("Unable to do OpenFile to Rider from dll, fallback to com.unity.ide.rider implementation."); + } + + return null; + } + } + + public static bool OpenFileDllImplementation(string path, int line, int column) + { + var openResult = false; + // reflection for fast OpenFileLineCol, when Rider is started and protocol connection is established + try + { + var assembly = GetEditorPluginAssembly(); + if (assembly == null) return false; + var type = assembly.GetType(ourEntryPointTypeName); + if (type == null) return false; + var field = type.GetField("OpenAssetHandler", BindingFlags.NonPublic | BindingFlags.Static); + if (field == null) return false; + var handlerInstance = field.GetValue(null); + var method = handlerInstance.GetType() + .GetMethod("OnOpenedAsset", new[] {typeof(string), typeof(int), typeof(int)}); + if (method == null) return false; + var assetFilePath = path; + if (!string.IsNullOrEmpty(path)) + assetFilePath = Path.GetFullPath(path); + + openResult = (bool) method.Invoke(handlerInstance, new object[] {assetFilePath, line, column}); + } + catch (Exception e) + { + Debug.Log("Unable to do OpenFile to Rider from dll, fallback to com.unity.ide.rider implementation."); + Debug.LogException(e); + } + + return openResult; + } + + public static Assembly GetEditorPluginAssembly() + { + var assemblies = AppDomain.CurrentDomain.GetAssemblies(); + var assembly = assemblies.FirstOrDefault(a => a.GetName().Name.Equals("JetBrains.Rider.Unity.Editor.Plugin.Full.Repacked")); + return assembly; + } + + public static bool EditorPluginIsLoadedFromAssets() + { + var currentDir = Directory.GetCurrentDirectory(); + var assembly = GetEditorPluginAssembly(); + if (assembly == null) + return false; + var location = assembly.Location; + return location.StartsWith(currentDir, StringComparison.InvariantCultureIgnoreCase); + } + + + internal static void InitEntryPoint() + { + try + { + DisableSyncSolutionOnceCallBack(); // is require for Rider prior to 2019.2 + + var type = GetEditorPluginAssembly().GetType("JetBrains.Rider.Unity.Editor.AfterUnity56.EntryPoint"); + if (type == null) + type = GetEditorPluginAssembly().GetType("JetBrains.Rider.Unity.Editor.UnitTesting.EntryPoint"); // oldRider + RuntimeHelpers.RunClassConstructor(type.TypeHandle); + } + catch (TypeInitializationException ex) + { + Debug.LogException(ex); + if (ex.InnerException != null) + Debug.LogException(ex.InnerException); + } + } + } +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/Rider/Editor/LoggingLevel.cs b/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/Rider/Editor/LoggingLevel.cs new file mode 100644 index 00000000..19ef8ab1 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/Rider/Editor/LoggingLevel.cs @@ -0,0 +1,22 @@ +namespace Packages.Rider.Editor +{ + public enum LoggingLevel + { + /// + /// Do not use it in logging. Only in config to disable logging. + /// + OFF, + /// For errors that lead to application failure + FATAL, + /// For errors that must be shown in Exception Browser + ERROR, + /// Suspicious situations but not errors + WARN, + /// Regular level for important events + INFO, + /// Additional info for debbuging + VERBOSE, + /// Methods & callstacks tracing, more than verbose + TRACE, + } +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/Rider/Editor/PluginSettings.cs b/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/Rider/Editor/PluginSettings.cs new file mode 100644 index 00000000..0f159798 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/Rider/Editor/PluginSettings.cs @@ -0,0 +1,153 @@ +using System.Reflection; +using Unity.CodeEditor; +using UnityEditor; +using UnityEngine; + +namespace Packages.Rider.Editor +{ + public class PluginSettings + { + public static LoggingLevel SelectedLoggingLevel + { + get => (LoggingLevel) EditorPrefs.GetInt("Rider_SelectedLoggingLevel", 0); + set + { + EditorPrefs.SetInt("Rider_SelectedLoggingLevel", (int) value); + } + } + + public static bool OverrideLangVersion + { + get { return EditorPrefs.GetBool("Rider_OverrideLangVersion", false); } + private set { EditorPrefs.SetBool("Rider_OverrideLangVersion", value);; } + } + + public static string LangVersion + { + get { return EditorPrefs.GetString("Rider_LangVersion", "4"); } + private set { EditorPrefs.SetString("Rider_LangVersion", value); } + } + + public static bool LogEventsCollectorEnabled + { + get { return EditorPrefs.GetBool("Rider_LogEventsCollectorEnabled", true); } + private set { EditorPrefs.SetBool("Rider_LogEventsCollectorEnabled", value); } + } + + + private static GUIStyle ourVersionInfoStyle = new GUIStyle() + { + normal = new GUIStyleState() + { + textColor = new Color(0, 0, 0, .6f), + }, + margin = new RectOffset(4, 4, 4, 4), + }; + + /// + /// Preferences menu layout + /// + /// + /// Contains all 3 toggles: Enable/Disable; Debug On/Off; Writing Launch File On/Off + /// + [SettingsProvider] + private static SettingsProvider RiderPreferencesItem() + { + if (!RiderScriptEditor.IsRiderInstallation(RiderScriptEditor.CurrentEditor)) + return null; + if (!RiderScriptEditor.ShouldLoadEditorPlugin(RiderScriptEditor.CurrentEditor)) + return null; + var provider = new SettingsProvider("Preferences/Rider", SettingsScope.User) + { + label = "Rider", + keywords = new[] { "Rider" }, + guiHandler = (searchContext) => + { + EditorGUIUtility.labelWidth = 200f; + EditorGUILayout.BeginVertical(); + + GUILayout.BeginVertical(); + LogEventsCollectorEnabled = + EditorGUILayout.Toggle(new GUIContent("Pass Console to Rider:"), LogEventsCollectorEnabled); + + GUILayout.EndVertical(); + + OverrideLangVersion = EditorGUILayout.Toggle(new GUIContent("Override LangVersion:"), OverrideLangVersion); + if (OverrideLangVersion) + { + var workaroundUrl = "https://gist.github.com/van800/875ce55eaf88d65b105d010d7b38a8d4"; + var workaroundText = "Use this workaround if overriding doesn't work."; + var helpLangVersion = @"Avoid overriding, unless there is no particular need."; + + LangVersion = + EditorGUILayout.TextField( + new GUIContent("LangVersion:", + helpLangVersion), LangVersion); + LinkButton(caption: workaroundText, url: workaroundUrl); + EditorGUILayout.HelpBox(helpLangVersion, MessageType.None); + } + + GUILayout.Label(""); + + if (!string.IsNullOrEmpty(EditorPluginInterop.LogPath)) + { + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.PrefixLabel("Log file:"); + var previous = GUI.enabled; + GUI.enabled = previous && SelectedLoggingLevel != LoggingLevel.OFF; + var button = GUILayout.Button(new GUIContent("Open log")); + if (button) + { + //UnityEditorInternal.InternalEditorUtility.OpenFileAtLineExternal(PluginEntryPoint.LogPath, 0); + // works much faster than the commented code, when Rider is already started + CodeEditor.CurrentEditor.OpenProject(EditorPluginInterop.LogPath, 0, 0); + } + + GUI.enabled = previous; + GUILayout.EndHorizontal(); + } + + var loggingMsg = + @"Sets the amount of Rider Debug output. If you are about to report an issue, please select Verbose logging level and attach Unity console output to the issue."; + SelectedLoggingLevel = + (LoggingLevel) EditorGUILayout.EnumPopup(new GUIContent("Logging Level:", loggingMsg), + SelectedLoggingLevel); + + + EditorGUILayout.HelpBox(loggingMsg, MessageType.None); + + var githubRepo = "https://github.com/JetBrains/resharper-unity"; + var caption = $"{githubRepo}"; + LinkButton(caption: caption, url: githubRepo); + + GUILayout.FlexibleSpace(); + GUILayout.BeginHorizontal(); + + GUILayout.FlexibleSpace(); + var version = Assembly.GetExecutingAssembly().GetName().Version; + GUILayout.Label("Plugin version: " + version, ourVersionInfoStyle); + + GUILayout.EndHorizontal(); + + EditorGUILayout.EndVertical(); + } + }; + return provider; + } + + private static void LinkButton(string caption, string url) + { + var style = GUI.skin.label; + style.richText = true; + + var bClicked = GUILayout.Button(caption, style); + + var rect = GUILayoutUtility.GetLastRect(); + rect.width = style.CalcSize(new GUIContent(caption)).x; + EditorGUIUtility.AddCursorRect(rect, MouseCursor.Link); + + if (bClicked) + Application.OpenURL(url); + } + } +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/Rider/Editor/ProjectGeneration.cs b/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/Rider/Editor/ProjectGeneration.cs new file mode 100644 index 00000000..7b7cd03d --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/Rider/Editor/ProjectGeneration.cs @@ -0,0 +1,938 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Security; +using System.Security.Cryptography; +using System.Text; +using System.Text.RegularExpressions; +using Packages.Rider.Editor.Util; +using UnityEditor; +using UnityEditor.Compilation; +using UnityEditor.PackageManager; +using UnityEditorInternal; +using UnityEngine; + +namespace Packages.Rider.Editor +{ + public interface IGenerator + { + bool SyncIfNeeded(IEnumerable affectedFiles, IEnumerable reimportedFiles); + void Sync(); + bool HasSolutionBeenGenerated(); + string SolutionFile(); + string ProjectDirectory { get; } + void GenerateAll(bool generateAll); + } + + public interface IAssemblyNameProvider + { + string GetAssemblyNameFromScriptPath(string path); + IEnumerable GetAllAssemblies(Func shouldFileBePartOfSolution); + IEnumerable GetAllAssetPaths(); + UnityEditor.PackageManager.PackageInfo FindForAssetPath(string assetPath); + } + + public struct TestSettings + { + public bool ShouldSync; + public Dictionary SyncPath; + } + + class AssemblyNameProvider : IAssemblyNameProvider + { + public string GetAssemblyNameFromScriptPath(string path) + { + return CompilationPipeline.GetAssemblyNameFromScriptPath(path); + } + + public IEnumerable GetAllAssemblies(Func shouldFileBePartOfSolution) + { + return CompilationPipeline.GetAssemblies() + .Where(i => 0 < i.sourceFiles.Length && i.sourceFiles.Any(shouldFileBePartOfSolution)); + } + + public IEnumerable GetAllAssetPaths() + { + return AssetDatabase.GetAllAssetPaths(); + } + + public UnityEditor.PackageManager.PackageInfo FindForAssetPath(string assetPath) + { + return UnityEditor.PackageManager.PackageInfo.FindForAssetPath(assetPath); + } + } + + + public class ProjectGeneration : IGenerator + { + enum ScriptingLanguage + { + None, + CSharp + } + + public static readonly string MSBuildNamespaceUri = "http://schemas.microsoft.com/developer/msbuild/2003"; + + const string k_WindowsNewline = "\r\n"; + + /// + /// Map source extensions to ScriptingLanguages + /// + static readonly Dictionary k_BuiltinSupportedExtensions = + new Dictionary + { + {"cs", ScriptingLanguage.CSharp}, + {"uxml", ScriptingLanguage.None}, + {"uss", ScriptingLanguage.None}, + {"shader", ScriptingLanguage.None}, + {"compute", ScriptingLanguage.None}, + {"cginc", ScriptingLanguage.None}, + {"hlsl", ScriptingLanguage.None}, + {"glslinc", ScriptingLanguage.None} + }; + + string m_SolutionProjectEntryTemplate = string.Join("\r\n", + @"Project(""{{{0}}}"") = ""{1}"", ""{2}"", ""{{{3}}}""", + @"EndProject").Replace(" ", "\t"); + + string m_SolutionProjectConfigurationTemplate = string.Join("\r\n", + @" {{{0}}}.Debug|Any CPU.ActiveCfg = Debug|Any CPU", + @" {{{0}}}.Debug|Any CPU.Build.0 = Debug|Any CPU", + @" {{{0}}}.Release|Any CPU.ActiveCfg = Release|Any CPU", + @" {{{0}}}.Release|Any CPU.Build.0 = Release|Any CPU").Replace(" ", "\t"); + + static readonly string[] k_ReimportSyncExtensions = {".dll", ".asmdef"}; + + /// + /// Map ScriptingLanguages to project extensions + /// + /*static readonly Dictionary k_ProjectExtensions = new Dictionary + { + { ScriptingLanguage.CSharp, ".csproj" }, + { ScriptingLanguage.None, ".csproj" }, + };*/ + static readonly Regex k_ScriptReferenceExpression = new Regex( + @"^Library.ScriptAssemblies.(?(?.*)\.dll$)", + RegexOptions.Compiled | RegexOptions.IgnoreCase); + + string[] m_ProjectSupportedExtensions = new string[0]; + bool m_ShouldGenerateAll; + + public string ProjectDirectory { get; } + + public void GenerateAll(bool generateAll) + { + m_ShouldGenerateAll = generateAll; + } + + public TestSettings Settings { get; set; } + readonly string m_ProjectName; + readonly IAssemblyNameProvider m_AssemblyNameProvider; + + const string k_ToolsVersion = "4.0"; + const string k_ProductVersion = "10.0.20506"; + const string k_BaseDirectory = "."; + const string k_TargetFrameworkVersion = "v4.7.1"; + const string k_TargetLanguageVersion = "latest"; + + public ProjectGeneration() : this(Directory.GetParent(Application.dataPath).FullName, new AssemblyNameProvider()) + { + } + + public ProjectGeneration(string tempDirectory) : this(tempDirectory, new AssemblyNameProvider()) + { + } + + public ProjectGeneration(string tempDirectory, IAssemblyNameProvider assemblyNameProvider) + { + Settings = new TestSettings {ShouldSync = true}; + ProjectDirectory = tempDirectory.Replace('\\', '/'); + m_ProjectName = Path.GetFileName(ProjectDirectory); + m_AssemblyNameProvider = assemblyNameProvider; + } + + /// + /// Syncs the scripting solution if any affected files are relevant. + /// + /// + /// Whether the solution was synced. + /// + /// + /// A set of files whose status has changed + /// + /// + /// A set of files that got reimported + /// + public bool SyncIfNeeded(IEnumerable affectedFiles, IEnumerable reimportedFiles) + { + SetupProjectSupportedExtensions(); + + if (HasFilesBeenModified(affectedFiles, reimportedFiles)) + { + Sync(); + return true; + } + + return false; + } + + bool HasFilesBeenModified(IEnumerable affectedFiles, IEnumerable reimportedFiles) + { + return affectedFiles.Any(ShouldFileBePartOfSolution) || reimportedFiles.Any(ShouldSyncOnReimportedAsset); + } + + static bool ShouldSyncOnReimportedAsset(string asset) + { + return k_ReimportSyncExtensions.Contains(new FileInfo(asset).Extension); + } + + public void Sync() + { + SetupProjectSupportedExtensions(); + var types = GetAssetPostprocessorTypes(); + bool externalCodeAlreadyGeneratedProjects = OnPreGeneratingCSProjectFiles(types); + + if (!externalCodeAlreadyGeneratedProjects) + { + GenerateAndWriteSolutionAndProjects(types); + } + + OnGeneratedCSProjectFiles(types); + } + + public bool HasSolutionBeenGenerated() + { + return File.Exists(SolutionFile()); + } + + void SetupProjectSupportedExtensions() + { + m_ProjectSupportedExtensions = EditorSettings.projectGenerationUserExtensions; + } + + bool ShouldFileBePartOfSolution(string file) + { + string extension = Path.GetExtension(file); + + // Exclude files coming from packages except if they are internalized. + if (!m_ShouldGenerateAll && IsInternalizedPackagePath(file)) + { + return false; + } + + // Dll's are not scripts but still need to be included.. + if (extension == ".dll") + return true; + + if (file.ToLower().EndsWith(".asmdef")) + return true; + + return IsSupportedExtension(extension); + } + + bool IsSupportedExtension(string extension) + { + extension = extension.TrimStart('.'); + if (k_BuiltinSupportedExtensions.ContainsKey(extension)) + return true; + if (m_ProjectSupportedExtensions.Contains(extension)) + return true; + return false; + } + + static ScriptingLanguage ScriptingLanguageFor(Assembly island) + { + return ScriptingLanguageFor(GetExtensionOfSourceFiles(island.sourceFiles)); + } + + static string GetExtensionOfSourceFiles(string[] files) + { + return files.Length > 0 ? GetExtensionOfSourceFile(files[0]) : "NA"; + } + + static string GetExtensionOfSourceFile(string file) + { + var ext = Path.GetExtension(file).ToLower(); + ext = ext.Substring(1); //strip dot + return ext; + } + + static ScriptingLanguage ScriptingLanguageFor(string extension) + { + return k_BuiltinSupportedExtensions.TryGetValue(extension.TrimStart('.'), out var result) + ? result + : ScriptingLanguage.None; + } + + public void GenerateAndWriteSolutionAndProjects(Type[] types) + { + // Only synchronize islands that have associated source files and ones that we actually want in the project. + // This also filters out DLLs coming from .asmdef files in packages. + var assemblies = m_AssemblyNameProvider.GetAllAssemblies(ShouldFileBePartOfSolution); + + var allAssetProjectParts = GenerateAllAssetProjectParts(); + + var monoIslands = assemblies.ToList(); + + SyncSolution(monoIslands, types); + var allProjectIslands = RelevantIslandsForMode(monoIslands).ToList(); + foreach (Assembly assembly in allProjectIslands) + { + var responseFileData = ParseResponseFileData(assembly); + SyncProject(assembly, allAssetProjectParts, responseFileData, allProjectIslands, types); + } + } + + IEnumerable ParseResponseFileData(Assembly assembly) + { + var systemReferenceDirectories = + CompilationPipeline.GetSystemAssemblyDirectories(assembly.compilerOptions.ApiCompatibilityLevel); + + Dictionary responseFilesData = assembly.compilerOptions.ResponseFiles.ToDictionary( + x => x, x => CompilationPipeline.ParseResponseFile( + Path.Combine(ProjectDirectory, x), + ProjectDirectory, + systemReferenceDirectories + )); + + Dictionary responseFilesWithErrors = responseFilesData.Where(x => x.Value.Errors.Any()) + .ToDictionary(x => x.Key, x => x.Value); + + if (responseFilesWithErrors.Any()) + { + foreach (var error in responseFilesWithErrors) + foreach (var valueError in error.Value.Errors) + { + Debug.LogError($"{error.Key} Parse Error : {valueError}"); + } + } + + return responseFilesData.Select(x => x.Value); + } + + Dictionary GenerateAllAssetProjectParts() + { + Dictionary stringBuilders = new Dictionary(); + + foreach (string asset in m_AssemblyNameProvider.GetAllAssetPaths()) + { + // Exclude files coming from packages except if they are internalized. + if (!m_ShouldGenerateAll && IsInternalizedPackagePath(asset)) + { + continue; + } + + string extension = Path.GetExtension(asset); + if (IsSupportedExtension(extension) && ScriptingLanguage.None == ScriptingLanguageFor(extension)) + { + // Find assembly the asset belongs to by adding script extension and using compilation pipeline. + var assemblyName = m_AssemblyNameProvider.GetAssemblyNameFromScriptPath(asset + ".cs"); + + if (string.IsNullOrEmpty(assemblyName)) + { + continue; + } + + assemblyName = FileSystemUtil.FileNameWithoutExtension(assemblyName); + + if (!stringBuilders.TryGetValue(assemblyName, out var projectBuilder)) + { + projectBuilder = new StringBuilder(); + stringBuilders[assemblyName] = projectBuilder; + } + + projectBuilder.Append(" ") + .Append(k_WindowsNewline); + } + } + + var result = new Dictionary(); + + foreach (var entry in stringBuilders) + result[entry.Key] = entry.Value.ToString(); + + return result; + } + + bool IsInternalizedPackagePath(string file) + { + if (string.IsNullOrWhiteSpace(file)) + { + return false; + } + + var packageInfo = m_AssemblyNameProvider.FindForAssetPath(file); + if (packageInfo == null) + { + return false; + } + + var packageSource = packageInfo.source; + return packageSource != PackageSource.Embedded && packageSource != PackageSource.Local; + } + + void SyncProject( + Assembly island, + Dictionary allAssetsProjectParts, + IEnumerable responseFilesData, + List allProjectIslands, + Type[] types) + { + SyncProjectFileIfNotChanged(ProjectFile(island), + ProjectText(island, allAssetsProjectParts, responseFilesData, allProjectIslands), types); + } + + void SyncProjectFileIfNotChanged(string path, string newContents, Type[] types) + { + if (Path.GetExtension(path) == ".csproj") + { + newContents = OnGeneratedCSProject(path, newContents, types); + } + + SyncFileIfNotChanged(path, newContents); + } + + void SyncSolutionFileIfNotChanged(string path, string newContents, Type[] types) + { + newContents = OnGeneratedSlnSolution(path, newContents, types); + + SyncFileIfNotChanged(path, newContents); + } + + static List SafeGetTypes(System.Reflection.Assembly a) + { + List ret; + + try + { + ret = a.GetTypes().ToList(); + } + catch (System.Reflection.ReflectionTypeLoadException rtl) + { + ret = rtl.Types.ToList(); + } + catch (Exception) + { + return new List(); + } + + return ret.Where(r => r != null).ToList(); + } + + static void OnGeneratedCSProjectFiles(Type[] types) + { + var args = new object[0]; + foreach (var type in types) + { + var method = type.GetMethod("OnGeneratedCSProjectFiles", + System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | + System.Reflection.BindingFlags.Static); + if (method == null) + { + continue; + } + + method.Invoke(null, args); + } + } + + public static Type[] GetAssetPostprocessorTypes() + { + return TypeCache.GetTypesDerivedFrom().ToArray(); // doesn't find types from EditorPlugin, which is fine + } + + static bool OnPreGeneratingCSProjectFiles(Type[] types) + { + bool result = false; + foreach (var type in types) + { + var args = new object[0]; + var method = type.GetMethod("OnPreGeneratingCSProjectFiles", + System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | + System.Reflection.BindingFlags.Static); + if (method == null) + { + continue; + } + + var returnValue = method.Invoke(null, args); + if (method.ReturnType == typeof(bool)) + { + result |= (bool) returnValue; + } + } + + return result; + } + + static string OnGeneratedCSProject(string path, string content, Type[] types) + { + foreach (var type in types) + { + var args = new[] {path, content}; + var method = type.GetMethod("OnGeneratedCSProject", + System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | + System.Reflection.BindingFlags.Static); + if (method == null) + { + continue; + } + + var returnValue = method.Invoke(null, args); + if (method.ReturnType == typeof(string)) + { + content = (string) returnValue; + } + } + + return content; + } + + static string OnGeneratedSlnSolution(string path, string content, Type[] types) + { + foreach (var type in types) + { + var args = new[] {path, content}; + var method = type.GetMethod("OnGeneratedSlnSolution", + System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | + System.Reflection.BindingFlags.Static); + if (method == null) + { + continue; + } + + var returnValue = method.Invoke(null, args); + if (method.ReturnType == typeof(string)) + { + content = (string) returnValue; + } + } + + return content; + } + + void SyncFileIfNotChanged(string filename, string newContents) + { + if (File.Exists(filename) && + newContents == File.ReadAllText(filename)) + { + return; + } + + if (Settings.ShouldSync) + { + File.WriteAllText(filename, newContents, Encoding.UTF8); + } + else + { + var utf8 = Encoding.UTF8; + byte[] utfBytes = utf8.GetBytes(newContents); + Settings.SyncPath[filename] = utf8.GetString(utfBytes, 0, utfBytes.Length); + } + } + + string ProjectText(Assembly assembly, + Dictionary allAssetsProjectParts, + IEnumerable responseFilesData, + List allProjectIslands) + { + var projectBuilder = new StringBuilder(ProjectHeader(assembly, responseFilesData)); + var references = new List(); + var projectReferences = new List(); + + foreach (string file in assembly.sourceFiles) + { + if (!ShouldFileBePartOfSolution(file)) + continue; + + var extension = Path.GetExtension(file).ToLower(); + var fullFile = EscapedRelativePathFor(file); + if (".dll" != extension) + { + projectBuilder.Append(" ").Append(k_WindowsNewline); + } + else + { + references.Add(fullFile); + } + } + + var assemblyName = FileSystemUtil.FileNameWithoutExtension(assembly.outputPath); + + // Append additional non-script files that should be included in project generation. + if (allAssetsProjectParts.TryGetValue(assemblyName, out var additionalAssetsForProject)) + projectBuilder.Append(additionalAssetsForProject); + + var islandRefs = references.Union(assembly.allReferences); + + foreach (string reference in islandRefs) + { + if (reference.EndsWith("/UnityEditor.dll", StringComparison.Ordinal) + || reference.EndsWith("/UnityEngine.dll", StringComparison.Ordinal) + || reference.EndsWith("\\UnityEditor.dll", StringComparison.Ordinal) + || reference.EndsWith("\\UnityEngine.dll", StringComparison.Ordinal)) + continue; + + var match = k_ScriptReferenceExpression.Match(reference); + if (match.Success) + { + // assume csharp language + // Add a reference to a project except if it's a reference to a script assembly + // that we are not generating a project for. This will be the case for assemblies + // coming from .assembly.json files in non-internalized packages. + var dllName = match.Groups["dllname"].Value; + if (allProjectIslands.Any(i => Path.GetFileName(i.outputPath) == dllName)) + { + projectReferences.Add(match); + continue; + } + } + + string fullReference = Path.IsPathRooted(reference) ? reference : Path.Combine(ProjectDirectory, reference); + + AppendReference(fullReference, projectBuilder); + } + + var responseRefs = responseFilesData.SelectMany(x => x.FullPathReferences.Select(r => r)); + foreach (var reference in responseRefs) + { + AppendReference(reference, projectBuilder); + } + + if (0 < projectReferences.Count) + { + projectBuilder.AppendLine(" "); + projectBuilder.AppendLine(" "); + foreach (Match reference in projectReferences) + { + var referencedProject = reference.Groups["project"].Value; + + projectBuilder.Append(" ").Append(k_WindowsNewline); + projectBuilder.Append(" {") + .Append(ProjectGuid(Path.Combine("Temp", reference.Groups["project"].Value + ".dll"))).Append("}") + .Append(k_WindowsNewline); + projectBuilder.Append(" ").Append(referencedProject).Append("").Append(k_WindowsNewline); + projectBuilder.AppendLine(" "); + } + } + + projectBuilder.Append(ProjectFooter()); + return projectBuilder.ToString(); + } + + static void AppendReference(string fullReference, StringBuilder projectBuilder) + { + //replace \ with / and \\ with / + var escapedFullPath = SecurityElement.Escape(fullReference); + escapedFullPath = escapedFullPath.Replace("\\\\", "/").Replace("\\", "/"); + projectBuilder.Append(" ").Append(k_WindowsNewline); + projectBuilder.Append(" ").Append(escapedFullPath).Append("").Append(k_WindowsNewline); + projectBuilder.Append(" ").Append(k_WindowsNewline); + } + + public string ProjectFile(Assembly assembly) + { + return Path.Combine(ProjectDirectory, $"{FileSystemUtil.FileNameWithoutExtension(assembly.outputPath)}.csproj"); + } + + public string SolutionFile() + { + return Path.Combine(ProjectDirectory, $"{m_ProjectName}.sln"); + } + + string ProjectHeader( + Assembly island, + IEnumerable responseFilesData + ) + { + var arguments = new object[] + { + k_ToolsVersion, k_ProductVersion, ProjectGuid(island.outputPath), + InternalEditorUtility.GetEngineAssemblyPath(), + InternalEditorUtility.GetEditorAssemblyPath(), + string.Join(";", + new[] {"DEBUG", "TRACE"}.Concat(EditorUserBuildSettings.activeScriptCompilationDefines).Concat(island.defines) + .Concat(responseFilesData.SelectMany(x => x.Defines)).Distinct().ToArray()), + MSBuildNamespaceUri, + FileSystemUtil.FileNameWithoutExtension(island.outputPath), + EditorSettings.projectGenerationRootNamespace, + k_TargetFrameworkVersion, + PluginSettings.OverrideLangVersion?PluginSettings.LangVersion:k_TargetLanguageVersion, + k_BaseDirectory, + island.compilerOptions.AllowUnsafeCode | responseFilesData.Any(x => x.Unsafe) + }; + + try + { + return string.Format(GetProjectHeaderTemplate(), arguments); + } + catch (Exception) + { + throw new NotSupportedException( + "Failed creating c# project because the c# project header did not have the correct amount of arguments, which is " + + arguments.Length); + } + } + + static string GetSolutionText() + { + return string.Join("\r\n", + @"", + @"Microsoft Visual Studio Solution File, Format Version {0}", + @"# Visual Studio {1}", + @"{2}", + @"Global", + @" GlobalSection(SolutionConfigurationPlatforms) = preSolution", + @" Debug|Any CPU = Debug|Any CPU", + @" Release|Any CPU = Release|Any CPU", + @" EndGlobalSection", + @" GlobalSection(ProjectConfigurationPlatforms) = postSolution", + @"{3}", + @" EndGlobalSection", + @" GlobalSection(SolutionProperties) = preSolution", + @" HideSolutionNode = FALSE", + @" EndGlobalSection", + @"EndGlobal", + @"").Replace(" ", "\t"); + } + + static string GetProjectFooterTemplate() + { + return string.Join("\r\n", + @" ", + @" ", + @" ", + @"", + @""); + } + + static string GetProjectHeaderTemplate() + { + var header = new[] + { + @"", + @"", + @" ", + @" {10}", + @" <_TargetFrameworkDirectories>non_empty_path_generated_by_unity.rider.package", + @" <_FullFrameworkReferenceAssemblyPaths>non_empty_path_generated_by_unity.rider.package", + @" true", + @" ", + @" ", + @" Debug", + @" AnyCPU", + @" {1}", + @" 2.0", + @" {8}", + @" {{{2}}}", + @" Library", + @" Properties", + @" {7}", + @" {9}", + @" 512", + @" {11}", + @" ", + @" ", + @" true", + @" full", + @" false", + @" Temp\bin\Debug\", + @" {5}", + @" prompt", + @" 4", + @" 0169", + @" {12}", + @" ", + @" ", + @" pdbonly", + @" true", + @" Temp\bin\Release\", + @" prompt", + @" 4", + @" 0169", + @" {12}", + @" " + }; + + var forceExplicitReferences = new[] + { + @" ", + @" true", + @" true", + @" false", + @" false", + @" false", + @" " + }; + + var itemGroupStart = new[] + { + @" " + }; + + var footer = new[] + { + @" ", + @" {3}", + @" ", + @" ", + @" {4}", + @" ", + @" ", + @" ", + @"" + }; + + var text = header.Concat(forceExplicitReferences).Concat(itemGroupStart).Concat(footer).ToArray(); + return string.Join("\r\n", text); + } + + void SyncSolution(IEnumerable islands, Type[] types) + { + SyncSolutionFileIfNotChanged(SolutionFile(), SolutionText(islands), types); + } + + string SolutionText(IEnumerable islands) + { + var fileversion = "11.00"; + var vsversion = "2010"; + + var relevantIslands = RelevantIslandsForMode(islands); + string projectEntries = GetProjectEntries(relevantIslands); + string projectConfigurations = string.Join(k_WindowsNewline, + relevantIslands.Select(i => GetProjectActiveConfigurations(ProjectGuid(i.outputPath))).ToArray()); + return string.Format(GetSolutionText(), fileversion, vsversion, projectEntries, projectConfigurations); + } + + static IEnumerable RelevantIslandsForMode(IEnumerable islands) + { + IEnumerable relevantIslands = islands.Where(i => ScriptingLanguage.CSharp == ScriptingLanguageFor(i)); + return relevantIslands; + } + + /// + /// Get a Project("{guid}") = "MyProject", "MyProject.unityproj", "{projectguid}" + /// entry for each relevant language + /// + string GetProjectEntries(IEnumerable islands) + { + var projectEntries = islands.Select(i => string.Format( + m_SolutionProjectEntryTemplate, + SolutionGuid(i), FileSystemUtil.FileNameWithoutExtension(i.outputPath), Path.GetFileName(ProjectFile(i)), + ProjectGuid(i.outputPath) + )); + + return string.Join(k_WindowsNewline, projectEntries.ToArray()); + } + + /// + /// Generate the active configuration string for a given project guid + /// + string GetProjectActiveConfigurations(string projectGuid) + { + return string.Format( + m_SolutionProjectConfigurationTemplate, + projectGuid); + } + + string EscapedRelativePathFor(string file) + { + var projectDir = ProjectDirectory.Replace('/', '\\'); + file = file.Replace('/', '\\'); + var path = SkipPathPrefix(file, projectDir); + + var packageInfo = m_AssemblyNameProvider.FindForAssetPath(path.Replace('\\', '/')); + if (packageInfo != null) + { + // We have to normalize the path, because the PackageManagerRemapper assumes + // dir seperators will be os specific. + var absolutePath = Path.GetFullPath(NormalizePath(path)).Replace('/', '\\'); + path = SkipPathPrefix(absolutePath, projectDir); + } + + return SecurityElement.Escape(path); + } + + static string SkipPathPrefix(string path, string prefix) + { + if (path.Replace("\\", "/").StartsWith($"{prefix}/")) + return path.Substring(prefix.Length + 1); + return path; + } + + static string NormalizePath(string path) + { + if (Path.DirectorySeparatorChar == '\\') + return path.Replace('/', Path.DirectorySeparatorChar); + return path.Replace('\\', Path.DirectorySeparatorChar); + } + + + string ProjectGuid(string assembly) + { + return SolutionGuidGenerator.GuidForProject(m_ProjectName + FileSystemUtil.FileNameWithoutExtension(assembly)); + } + + string SolutionGuid(Assembly island) + { + return SolutionGuidGenerator.GuidForSolution(m_ProjectName, GetExtensionOfSourceFiles(island.sourceFiles)); + } + + static string ProjectFooter() + { + return GetProjectFooterTemplate(); + } + + static string GetProjectExtension() + { + return ".csproj"; + } + } + + public static class SolutionGuidGenerator + { + public static string GuidForProject(string projectName) + { + return ComputeGuidHashFor(projectName + "salt"); + } + + public static string GuidForSolution(string projectName, string sourceFileExtension) + { + if (sourceFileExtension.ToLower() == "cs") + // GUID for a C# class library: http://www.codeproject.com/Reference/720512/List-of-Visual-Studio-Project-Type-GUIDs + return "FAE04EC0-301F-11D3-BF4B-00C04F79EFBC"; + + return ComputeGuidHashFor(projectName); + } + + static string ComputeGuidHashFor(string input) + { + var hash = MD5.Create().ComputeHash(Encoding.Default.GetBytes(input)); + return HashAsGuid(HashToString(hash)); + } + + static string HashAsGuid(string hash) + { + var guid = hash.Substring(0, 8) + "-" + hash.Substring(8, 4) + "-" + hash.Substring(12, 4) + "-" + + hash.Substring(16, 4) + "-" + hash.Substring(20, 12); + return guid.ToUpper(); + } + + static string HashToString(byte[] bs) + { + var sb = new StringBuilder(); + foreach (byte b in bs) + sb.Append(b.ToString("x2")); + return sb.ToString(); + } + } +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/Rider/Editor/RiderInitializer.cs b/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/Rider/Editor/RiderInitializer.cs new file mode 100644 index 00000000..f70b7924 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/Rider/Editor/RiderInitializer.cs @@ -0,0 +1,47 @@ +using System; +using System.IO; +using System.Linq; +using System.Reflection; +using UnityEngine; + +namespace Packages.Rider.Editor +{ + internal class RiderInitializer + { + public void Initialize(string editorPath) + { + if (EditorPluginInterop.EditorPluginIsLoadedFromAssets()) + { + Debug.LogError($"Please delete {EditorPluginInterop.GetEditorPluginAssembly().Location}. Unity 2019.2+ loads it directly from Rider installation. To disable this, open Rider's settings, search and uncheck 'Automatically install and update Rider's Unity editor plugin'."); + return; + } + + var dllName = "JetBrains.Rider.Unity.Editor.Plugin.Full.Repacked.dll"; + var relPath = "../../plugins/rider-unity/EditorPlugin"; + if (SystemInfo.operatingSystemFamily == OperatingSystemFamily.MacOSX) + relPath = "Contents/plugins/rider-unity/EditorPlugin"; + var dllFile = new FileInfo(Path.Combine(Path.Combine(editorPath, relPath), dllName)); + + if (dllFile.Exists) + { + // doesn't lock assembly on disk + var bytes = File.ReadAllBytes(dllFile.FullName); + var pdbFile = new FileInfo(Path.ChangeExtension(dllFile.FullName, ".pdb")); + if (pdbFile.Exists) + { + AppDomain.CurrentDomain.Load(bytes, File.ReadAllBytes(pdbFile.FullName)); + } + else + { + AppDomain.CurrentDomain.Load(bytes); + // AppDomain.CurrentDomain.Load(AssemblyName.GetAssemblyName(dllFile.FullName)); // use this for external source debug + } + EditorPluginInterop.InitEntryPoint(); + } + else + { + Debug.Log((object) ($"Unable to find Rider EditorPlugin {dllFile.FullName} for Unity ")); + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/Rider/Editor/RiderScriptEditor.cs b/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/Rider/Editor/RiderScriptEditor.cs new file mode 100644 index 00000000..190ed666 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/Rider/Editor/RiderScriptEditor.cs @@ -0,0 +1,344 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Linq; +using Packages.Rider.Editor.Util; +using Unity.CodeEditor; +using UnityEditor; +using UnityEngine; +using Debug = UnityEngine.Debug; + +namespace Packages.Rider.Editor +{ + [InitializeOnLoad] + public class RiderScriptEditor : IExternalCodeEditor + { + IDiscovery m_Discoverability; + IGenerator m_ProjectGeneration; + RiderInitializer m_Initiliazer = new RiderInitializer(); + + static RiderScriptEditor() + { + try + { + var projectGeneration = new ProjectGeneration(); + var editor = new RiderScriptEditor(new Discovery(), projectGeneration); + CodeEditor.Register(editor); + + var path = GetEditorRealPath(CodeEditor.CurrentEditorInstallation); + if (IsRiderInstallation(path)) + { + if (!FileSystemUtil.EditorPathExists(path)) // previously used rider was removed + { + var newEditor = editor.Installations.Last().Path; + CodeEditor.SetExternalScriptEditor(newEditor); + path = newEditor; + } + + editor.CreateSolutionIfDoesntExist(); + if (ShouldLoadEditorPlugin(path)) + { + editor.m_Initiliazer.Initialize(path); + } + + InitProjectFilesWatcher(); + } + } + catch (Exception e) + { + Debug.LogException(e); + } + } + + private static void InitProjectFilesWatcher() + { + var watcher = new FileSystemWatcher(); + watcher.Path = Directory.GetCurrentDirectory(); + watcher.NotifyFilter = NotifyFilters.LastWrite; //Watch for changes in LastWrite times + watcher.Filter = "*.*"; + + // Add event handlers. + watcher.Changed += OnChanged; + watcher.Created += OnChanged; + + watcher.EnableRaisingEvents = true; // Begin watching. + + AppDomain.CurrentDomain.DomainUnload += (EventHandler) ((_, __) => + { + watcher.Dispose(); + }); + } + + private static void OnChanged(object sender, FileSystemEventArgs e) + { + var extension = Path.GetExtension(e.FullPath); + if (extension == ".sln" || extension == ".csproj") + RiderScriptEditorData.instance.HasChanges = true; + } + + private static string GetEditorRealPath(string path) + { + if (string.IsNullOrEmpty(path)) + { + return path; + } + + if (!FileSystemUtil.EditorPathExists(path)) + return path; + + if (SystemInfo.operatingSystemFamily != OperatingSystemFamily.Windows) + { + var realPath = FileSystemUtil.GetFinalPathName(path); + + // case of snap installation + if (SystemInfo.operatingSystemFamily == OperatingSystemFamily.Linux) + { + if (new FileInfo(path).Name.ToLowerInvariant() == "rider" && + new FileInfo(realPath).Name.ToLowerInvariant() == "snap") + { + var snapInstallPath = "/snap/rider/current/bin/rider.sh"; + if (new FileInfo(snapInstallPath).Exists) + return snapInstallPath; + } + } + + // in case of symlink + return realPath; + } + + return path; + } + + const string unity_generate_all = "unity_generate_all_csproj"; + + public RiderScriptEditor(IDiscovery discovery, IGenerator projectGeneration) + { + m_Discoverability = discovery; + m_ProjectGeneration = projectGeneration; + } + + private static string[] defaultExtensions + { + get + { + var customExtensions = new[] {"json", "asmdef", "log"}; + return EditorSettings.projectGenerationBuiltinExtensions.Concat(EditorSettings.projectGenerationUserExtensions) + .Concat(customExtensions).Distinct().ToArray(); + } + } + + private static string[] HandledExtensions + { + get + { + return HandledExtensionsString.Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries).Select(s => s.TrimStart('.', '*')) + .ToArray(); + } + } + + private static string HandledExtensionsString + { + get { return EditorPrefs.GetString("Rider_UserExtensions", string.Join(";", defaultExtensions));} + set { EditorPrefs.SetString("Rider_UserExtensions", value); } + } + + private static bool SupportsExtension(string path) + { + var extension = Path.GetExtension(path); + if (string.IsNullOrEmpty(extension)) + return false; + return HandledExtensions.Contains(extension.TrimStart('.')); + } + + public void OnGUI() + { + var prevGenerate = EditorPrefs.GetBool(unity_generate_all, false); + var generateAll = EditorGUILayout.Toggle("Generate all .csproj files.", prevGenerate); + if (generateAll != prevGenerate) + { + EditorPrefs.SetBool(unity_generate_all, generateAll); + } + + m_ProjectGeneration.GenerateAll(generateAll); + + if (ShouldLoadEditorPlugin(CurrentEditor)) + { + HandledExtensionsString = EditorGUILayout.TextField(new GUIContent("Extensions handled: "), HandledExtensionsString); + } + } + + public void SyncIfNeeded(string[] addedFiles, string[] deletedFiles, string[] movedFiles, string[] movedFromFiles, + string[] importedFiles) + { + m_ProjectGeneration.SyncIfNeeded(addedFiles.Union(deletedFiles).Union(movedFiles).Union(movedFromFiles), + importedFiles); + } + + public void SyncAll() + { + AssetDatabase.Refresh(); + if (RiderScriptEditorData.instance.HasChanges) + { + m_ProjectGeneration.Sync(); + RiderScriptEditorData.instance.HasChanges = false; + } + } + + public void Initialize(string editorInstallationPath) // is called each time ExternalEditor is changed + { + m_ProjectGeneration.Sync(); // regenerate csproj and sln for new editor + } + + public bool OpenProject(string path, int line, int column) + { + if (path != "" && !SupportsExtension(path)) // Assets - Open C# Project passes empty path here + { + return false; + } + + if (path == "" && SystemInfo.operatingSystemFamily == OperatingSystemFamily.MacOSX) + { + // there is a bug in DllImplementation - use package implementation here instead https://github.cds.internal.unity3d.com/unity/com.unity.ide.rider/issues/21 + return OpenOSXApp(path, line, column); + } + + if (!IsUnityScript(path)) + { + var fastOpenResult = EditorPluginInterop.OpenFileDllImplementation(path, line, column); + if (fastOpenResult) + return true; + } + + if (SystemInfo.operatingSystemFamily == OperatingSystemFamily.MacOSX) + { + return OpenOSXApp(path, line, column); + } + + var solution = GetSolutionFile(path); // TODO: If solution file doesn't exist resync. + solution = solution == "" ? "" : $"\"{solution}\""; + var process = new Process + { + StartInfo = new ProcessStartInfo + { + FileName = CodeEditor.CurrentEditorInstallation, + Arguments = $"{solution} -l {line} \"{path}\"", + UseShellExecute = true, + } + }; + + process.Start(); + + return true; + } + + private bool OpenOSXApp(string path, int line, int column) + { + var solution = GetSolutionFile(path); // TODO: If solution file doesn't exist resync. + solution = solution == "" ? "" : $"\"{solution}\""; + var pathArguments = path == "" ? "" : $"-l {line} \"{path}\""; + var process = new Process + { + StartInfo = new ProcessStartInfo + { + FileName = "open", + Arguments = $"-n \"{CodeEditor.CurrentEditorInstallation}\" --args {solution} {pathArguments}", + CreateNoWindow = true, + UseShellExecute = true, + } + }; + + process.Start(); + + return true; + } + + private string GetSolutionFile(string path) + { + if (IsUnityScript(path)) + { + return Path.Combine(GetBaseUnityDeveloperFolder(), "Projects/CSharp/Unity.CSharpProjects.gen.sln"); + } + + var solutionFile = m_ProjectGeneration.SolutionFile(); + if (File.Exists(solutionFile)) + { + return solutionFile; + } + + return ""; + } + + static bool IsUnityScript(string path) + { + if (UnityEditor.Unsupported.IsDeveloperBuild()) + { + var baseFolder = GetBaseUnityDeveloperFolder().Replace("\\", "/"); + var lowerPath = path.ToLowerInvariant().Replace("\\", "/"); + + if (lowerPath.Contains((baseFolder + "/Runtime").ToLowerInvariant()) + || lowerPath.Contains((baseFolder + "/Editor").ToLowerInvariant())) + { + return true; + } + } + + return false; + } + + static string GetBaseUnityDeveloperFolder() + { + return Directory.GetParent(EditorApplication.applicationPath).Parent.Parent.FullName; + } + + public bool TryGetInstallationForPath(string editorPath, out CodeEditor.Installation installation) + { + if (FileSystemUtil.EditorPathExists(editorPath) && IsRiderInstallation(editorPath)) + { + var info = new RiderPathLocator.RiderInfo(editorPath, false); + installation = new CodeEditor.Installation + { + Name = info.Presentation, + Path = info.Path + }; + return true; + } + + installation = default; + return false; + } + + public static bool IsRiderInstallation(string path) + { + if (string.IsNullOrEmpty(path)) + { + return false; + } + + var fileInfo = new FileInfo(path); + var filename = fileInfo.Name.ToLowerInvariant(); + return filename.StartsWith("rider", StringComparison.Ordinal); + } + + public static string CurrentEditor // works fast, doesn't validate if executable really exists + => EditorPrefs.GetString("kScriptsDefaultApp"); + + public static bool ShouldLoadEditorPlugin(string path) + { + var ver = RiderPathLocator.GetBuildNumber(path); + if (!Version.TryParse(ver, out var version)) + return false; + + return version >= new Version("191.7141.156"); + } + + public CodeEditor.Installation[] Installations => m_Discoverability.PathCallback(); + + public void CreateSolutionIfDoesntExist() + { + if (!m_ProjectGeneration.HasSolutionBeenGenerated()) + { + m_ProjectGeneration.Sync(); + } + } + } +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/Rider/Editor/RiderScriptEditorData.cs b/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/Rider/Editor/RiderScriptEditorData.cs new file mode 100644 index 00000000..d05428bb --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/Rider/Editor/RiderScriptEditorData.cs @@ -0,0 +1,10 @@ +using UnityEditor; +using UnityEngine; + +namespace Packages.Rider.Editor +{ + public class RiderScriptEditorData:ScriptableSingleton + { + [SerializeField] internal bool HasChanges = true; // sln/csproj files were changed + } +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/Rider/Editor/Util/FileSystemUtil.cs b/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/Rider/Editor/Util/FileSystemUtil.cs new file mode 100644 index 00000000..3d0624b2 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/Rider/Editor/Util/FileSystemUtil.cs @@ -0,0 +1,66 @@ +using System; +using System.ComponentModel; +using System.IO; +using System.Text; +using JetBrains.Annotations; +using UnityEngine; + +namespace Packages.Rider.Editor.Util +{ + public static class FileSystemUtil + { + [NotNull] + public static string GetFinalPathName([NotNull] string path) + { + if (path == null) throw new ArgumentNullException("path"); + + // up to MAX_PATH. MAX_PATH on Linux currently 4096, on Mac OS X 1024 + // doc: http://man7.org/linux/man-pages/man3/realpath.3.html + var sb = new StringBuilder(8192); + var result = LibcNativeInterop.realpath(path, sb); + if (result == IntPtr.Zero) + { + throw new Win32Exception($"{path} was not resolved."); + } + + return new FileInfo(sb.ToString()).FullName; + } + + public static string FileNameWithoutExtension(string path) + { + if (string.IsNullOrEmpty(path)) + { + return ""; + } + + var indexOfDot = -1; + var indexOfSlash = 0; + for (var i = path.Length - 1; i >= 0; i--) + { + if (indexOfDot == -1 && path[i] == '.') + { + indexOfDot = i; + } + + if (indexOfSlash == 0 && path[i] == '/' || path[i] == '\\') + { + indexOfSlash = i + 1; + break; + } + } + + if (indexOfDot == -1) + { + indexOfDot = path.Length - 1; + } + + return path.Substring(indexOfSlash, indexOfDot - indexOfSlash); + } + + public static bool EditorPathExists(string editorPath) + { + return SystemInfo.operatingSystemFamily == OperatingSystemFamily.MacOSX && new DirectoryInfo(editorPath).Exists + || SystemInfo.operatingSystemFamily != OperatingSystemFamily.MacOSX && new FileInfo(editorPath).Exists; + } + } +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/Rider/Editor/Util/LibcNativeInterop.cs b/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/Rider/Editor/Util/LibcNativeInterop.cs new file mode 100644 index 00000000..a4070f28 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/Rider/Editor/Util/LibcNativeInterop.cs @@ -0,0 +1,12 @@ +using System; +using System.Runtime.InteropServices; +using System.Text; + +namespace Packages.Rider.Editor.Util +{ + internal static class LibcNativeInterop + { + [DllImport("libc", SetLastError = true)] + public static extern IntPtr realpath(string path, StringBuilder resolved_path); + } +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/Rider/Editor/Util/UnityUtils.cs b/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/Rider/Editor/Util/UnityUtils.cs new file mode 100644 index 00000000..03c9922e --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/Rider/Editor/Util/UnityUtils.cs @@ -0,0 +1,20 @@ +using System; +using System.Linq; +using UnityEngine; + +namespace Packages.Rider.Editor.Util +{ + public static class UnityUtils + { + internal static readonly string UnityApplicationVersion = Application.unityVersion; + + public static Version UnityVersion + { + get + { + var ver = UnityApplicationVersion.Split(".".ToCharArray()).Take(2).Aggregate((a, b) => a + "." + b); + return new Version(ver); + } + } + } +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/Rider/Editor/com.unity.ide.rider.asmdef b/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/Rider/Editor/com.unity.ide.rider.asmdef new file mode 100644 index 00000000..2e652fa9 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/Rider/Editor/com.unity.ide.rider.asmdef @@ -0,0 +1,9 @@ +{ + "name": "Unity.Rider.Editor", + "references": [], + "optionalUnityReferences": [], + "includePlatforms": [ + "Editor" + ], + "excludePlatforms": [] +} diff --git a/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/package.json b/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/package.json new file mode 100644 index 00000000..ac4a762f --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ide.rider@1.1.0/package.json @@ -0,0 +1,19 @@ +{ + "name": "com.unity.ide.rider", + "displayName": "Rider Editor", + "description": "Code editor integration for supporting Rider as code editor for unity. Adds support for generating csproj files for code completion, auto discovery of installations, etc.", + "version": "1.1.0", + "unity": "2019.2", + "unityRelease": "0a12", + "dependencies": { + "com.unity.ext.nunit": "1.0.0" + }, + "relatedPackages": { + "com.unity.ide.rider.tests": "1.1.0" + }, + "repository": { + "type": "git", + "url": "git@github.cds.internal.unity3d.com:unity/com.unity.ide.rider.git", + "revision": "80ad81f593b04a6104771ae0d01cc71773d07b02" + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.ide.vscode@1.1.0/CHANGELOG.md b/KerbalVR/Library/PackageCache/com.unity.ide.vscode@1.1.0/CHANGELOG.md new file mode 100644 index 00000000..e7a32b4d --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ide.vscode@1.1.0/CHANGELOG.md @@ -0,0 +1,34 @@ +# Code Editor Package for Visual Studio Code + +## [1.1.0] - 2019-08-07 + +Adds support for choosing extensions to be opened with VSCode. This can be done through the GUI in Preferences. +Avoids opening all extensions after the change in core unity. + + +## [1.0.7] - 2019-05-15 + +Fix various OSX specific issues. +Generate project on load if they are not generated. +Fix path recognition. + + +## [1.0.6] - 2019-04-30 + +Ensure asset database is refreshed when generating csproj and solution files. + +## [1.0.5] - 2019-04-27 + +Add support for generating all csproj files. + +## [1.0.4] - 2019-04-18 + +Fix relative package paths. +Fix opening editor on mac. +Add %LOCALAPPDATA%/Programs to the path of install paths. + +## [1.0.3] - 2019-01-01 + +### This is the first release of *Unity Package vscode_editor*. + +Using the newly created api to integrate Visual Studio Code with Unity. diff --git a/KerbalVR/Library/PackageCache/com.unity.ide.vscode@1.1.0/CONTRIBUTING.md b/KerbalVR/Library/PackageCache/com.unity.ide.vscode@1.1.0/CONTRIBUTING.md new file mode 100644 index 00000000..576d0963 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ide.vscode@1.1.0/CONTRIBUTING.md @@ -0,0 +1,6 @@ +# Contributing + +## All contributions are subject to the [Unity Contribution Agreement(UCA)](https://unity3d.com/legal/licenses/Unity_Contribution_Agreement) +By making a pull request, you are confirming agreement to the terms and conditions of the UCA, including that your Contributions are your original creation and that you have complete right and authority to make your Contributions. + +## Once you have a change ready following these ground rules. Simply make a pull request \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.ide.vscode@1.1.0/Editor/ProjectGeneration.cs b/KerbalVR/Library/PackageCache/com.unity.ide.vscode@1.1.0/Editor/ProjectGeneration.cs new file mode 100644 index 00000000..1f16d96c --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ide.vscode@1.1.0/Editor/ProjectGeneration.cs @@ -0,0 +1,837 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Security; +using System.Security.Cryptography; +using System.Text; +using System.Text.RegularExpressions; +using UnityEditor; +using UnityEditor.Compilation; +using UnityEditor.PackageManager; +using UnityEditorInternal; +using UnityEngine; +using UnityEngine.Profiling; + +namespace VSCodeEditor +{ + public interface IGenerator { + bool SyncIfNeeded(IEnumerable affectedFiles, IEnumerable reimportedFiles); + void Sync(); + bool HasSolutionBeenGenerated(); + string SolutionFile(); + string ProjectDirectory { get; } + void GenerateAll(bool generateAll); + } + + public interface IAssemblyNameProvider + { + string GetAssemblyNameFromScriptPath(string path); + IEnumerable GetAllAssemblies(Func shouldFileBePartOfSolution); + IEnumerable GetAllAssetPaths(); + UnityEditor.PackageManager.PackageInfo FindForAssetPath(string assetPath); + } + + public struct TestSettings { + public bool ShouldSync; + public Dictionary SyncPath; + } + + class AssemblyNameProvider : IAssemblyNameProvider + { + public string GetAssemblyNameFromScriptPath(string path) + { + return CompilationPipeline.GetAssemblyNameFromScriptPath(path); + } + + public IEnumerable GetAllAssemblies(Func shouldFileBePartOfSolution) + { + return CompilationPipeline.GetAssemblies().Where(i => 0 < i.sourceFiles.Length && i.sourceFiles.Any(shouldFileBePartOfSolution)); + } + + public IEnumerable GetAllAssetPaths() + { + return AssetDatabase.GetAllAssetPaths(); + } + + public UnityEditor.PackageManager.PackageInfo FindForAssetPath(string assetPath) + { + return UnityEditor.PackageManager.PackageInfo.FindForAssetPath(assetPath); + } + } + + + public class ProjectGeneration : IGenerator + { + enum ScriptingLanguage + { + None, + CSharp + } + + public static readonly string MSBuildNamespaceUri = "http://schemas.microsoft.com/developer/msbuild/2003"; + + const string k_WindowsNewline = "\r\n"; + + const string k_SettingsJson = @"{ + ""files.exclude"": + { + ""**/.DS_Store"":true, + ""**/.git"":true, + ""**/.gitignore"":true, + ""**/.gitmodules"":true, + ""**/*.booproj"":true, + ""**/*.pidb"":true, + ""**/*.suo"":true, + ""**/*.user"":true, + ""**/*.userprefs"":true, + ""**/*.unityproj"":true, + ""**/*.dll"":true, + ""**/*.exe"":true, + ""**/*.pdf"":true, + ""**/*.mid"":true, + ""**/*.midi"":true, + ""**/*.wav"":true, + ""**/*.gif"":true, + ""**/*.ico"":true, + ""**/*.jpg"":true, + ""**/*.jpeg"":true, + ""**/*.png"":true, + ""**/*.psd"":true, + ""**/*.tga"":true, + ""**/*.tif"":true, + ""**/*.tiff"":true, + ""**/*.3ds"":true, + ""**/*.3DS"":true, + ""**/*.fbx"":true, + ""**/*.FBX"":true, + ""**/*.lxo"":true, + ""**/*.LXO"":true, + ""**/*.ma"":true, + ""**/*.MA"":true, + ""**/*.obj"":true, + ""**/*.OBJ"":true, + ""**/*.asset"":true, + ""**/*.cubemap"":true, + ""**/*.flare"":true, + ""**/*.mat"":true, + ""**/*.meta"":true, + ""**/*.prefab"":true, + ""**/*.unity"":true, + ""build/"":true, + ""Build/"":true, + ""Library/"":true, + ""library/"":true, + ""obj/"":true, + ""Obj/"":true, + ""ProjectSettings/"":true, + ""temp/"":true, + ""Temp/"":true + } +}"; + + /// + /// Map source extensions to ScriptingLanguages + /// + static readonly Dictionary k_BuiltinSupportedExtensions = new Dictionary + { + { "cs", ScriptingLanguage.CSharp }, + { "uxml", ScriptingLanguage.None }, + { "uss", ScriptingLanguage.None }, + { "shader", ScriptingLanguage.None }, + { "compute", ScriptingLanguage.None }, + { "cginc", ScriptingLanguage.None }, + { "hlsl", ScriptingLanguage.None }, + { "glslinc", ScriptingLanguage.None } + }; + + string m_SolutionProjectEntryTemplate = string.Join("\r\n", @"Project(""{{{0}}}"") = ""{1}"", ""{2}"", ""{{{3}}}""", @"EndProject").Replace(" ", "\t"); + + string m_SolutionProjectConfigurationTemplate = string.Join("\r\n", @" {{{0}}}.Debug|Any CPU.ActiveCfg = Debug|Any CPU", @" {{{0}}}.Debug|Any CPU.Build.0 = Debug|Any CPU", @" {{{0}}}.Release|Any CPU.ActiveCfg = Release|Any CPU", @" {{{0}}}.Release|Any CPU.Build.0 = Release|Any CPU").Replace(" ", "\t"); + + static readonly string[] k_ReimportSyncExtensions = { ".dll", ".asmdef" }; + + /// + /// Map ScriptingLanguages to project extensions + /// + /*static readonly Dictionary k_ProjectExtensions = new Dictionary + { + { ScriptingLanguage.CSharp, ".csproj" }, + { ScriptingLanguage.None, ".csproj" }, + };*/ + + static readonly Regex k_ScriptReferenceExpression = new Regex( + @"^Library.ScriptAssemblies.(?(?.*)\.dll$)", + RegexOptions.Compiled | RegexOptions.IgnoreCase); + + string[] m_ProjectSupportedExtensions = new string[0]; + public string ProjectDirectory { get; } + bool m_ShouldGenerateAll; + + public void GenerateAll(bool generateAll) + { + m_ShouldGenerateAll = generateAll; + } + + public TestSettings Settings { get; set; } + + readonly string m_ProjectName; + readonly IAssemblyNameProvider m_AssemblyNameProvider; + const string k_ToolsVersion = "4.0"; + const string k_ProductVersion = "10.0.20506"; + const string k_BaseDirectory = "."; + const string k_TargetFrameworkVersion = "v4.7.1"; + const string k_TargetLanguageVersion = "latest"; + + public ProjectGeneration() : this(Directory.GetParent(Application.dataPath).FullName, new AssemblyNameProvider()) + { + } + + public ProjectGeneration(string tempDirectory) : this(tempDirectory, new AssemblyNameProvider()) { + } + + public ProjectGeneration(string tempDirectory, IAssemblyNameProvider assemblyNameProvider) { + Settings = new TestSettings { ShouldSync = true }; + ProjectDirectory = tempDirectory.Replace('\\', '/'); + m_ProjectName = Path.GetFileName(ProjectDirectory); + m_AssemblyNameProvider = assemblyNameProvider; + } + + /// + /// Syncs the scripting solution if any affected files are relevant. + /// + /// + /// Whether the solution was synced. + /// + /// + /// A set of files whose status has changed + /// + /// + /// A set of files that got reimported + /// + public bool SyncIfNeeded(IEnumerable affectedFiles, IEnumerable reimportedFiles) + { + Profiler.BeginSample("SolutionSynchronizerSync"); + SetupProjectSupportedExtensions(); + + // Don't sync if we haven't synced before + if (HasSolutionBeenGenerated() && HasFilesBeenModified(affectedFiles, reimportedFiles)) + { + Sync(); + + Profiler.EndSample(); + return true; + } + + Profiler.EndSample(); + return false; + } + + bool HasFilesBeenModified(IEnumerable affectedFiles, IEnumerable reimportedFiles) + { + return affectedFiles.Any(ShouldFileBePartOfSolution) || reimportedFiles.Any(ShouldSyncOnReimportedAsset); + } + + static bool ShouldSyncOnReimportedAsset(string asset) + { + return k_ReimportSyncExtensions.Contains(new FileInfo(asset).Extension); + } + + public void Sync() + { + SetupProjectSupportedExtensions(); + GenerateAndWriteSolutionAndProjects(); + } + + public bool HasSolutionBeenGenerated() + { + return File.Exists(SolutionFile()); + } + + void SetupProjectSupportedExtensions() + { + m_ProjectSupportedExtensions = EditorSettings.projectGenerationUserExtensions; + } + + bool ShouldFileBePartOfSolution(string file) + { + string extension = Path.GetExtension(file); + + // Exclude files coming from packages except if they are internalized. + if (!m_ShouldGenerateAll && IsInternalizedPackagePath(file)) + { + return false; + } + + // Dll's are not scripts but still need to be included.. + if (extension == ".dll") + return true; + + if (file.ToLower().EndsWith(".asmdef")) + return true; + + return IsSupportedExtension(extension); + } + + bool IsSupportedExtension(string extension) + { + extension = extension.TrimStart('.'); + if (k_BuiltinSupportedExtensions.ContainsKey(extension)) + return true; + if (m_ProjectSupportedExtensions.Contains(extension)) + return true; + return false; + } + + static ScriptingLanguage ScriptingLanguageFor(Assembly island) + { + return ScriptingLanguageFor(GetExtensionOfSourceFiles(island.sourceFiles)); + } + + static string GetExtensionOfSourceFiles(string[] files) + { + return files.Length > 0 ? GetExtensionOfSourceFile(files[0]) : "NA"; + } + + static string GetExtensionOfSourceFile(string file) + { + var ext = Path.GetExtension(file).ToLower(); + ext = ext.Substring(1); //strip dot + return ext; + } + + static ScriptingLanguage ScriptingLanguageFor(string extension) + { + return k_BuiltinSupportedExtensions.TryGetValue(extension.TrimStart('.'), out var result) + ? result + : ScriptingLanguage.None; + } + + public void GenerateAndWriteSolutionAndProjects() + { + // Only synchronize islands that have associated source files and ones that we actually want in the project. + // This also filters out DLLs coming from .asmdef files in packages. + var assemblies = m_AssemblyNameProvider.GetAllAssemblies(ShouldFileBePartOfSolution); + + var allAssetProjectParts = GenerateAllAssetProjectParts(); + + var monoIslands = assemblies.ToList(); + + SyncSolution(monoIslands); + var allProjectIslands = RelevantIslandsForMode(monoIslands).ToList(); + foreach (Assembly assembly in allProjectIslands) + { + var responseFileData = ParseResponseFileData(assembly); + SyncProject(assembly, allAssetProjectParts, responseFileData, allProjectIslands); + } + + if (Settings.ShouldSync) + { + WriteVSCodeSettingsFiles(); + } + } + + IEnumerable ParseResponseFileData(Assembly assembly) + { + var systemReferenceDirectories = CompilationPipeline.GetSystemAssemblyDirectories(assembly.compilerOptions.ApiCompatibilityLevel); + + Dictionary responseFilesData = assembly.compilerOptions.ResponseFiles.ToDictionary(x => x, x => CompilationPipeline.ParseResponseFile( + Path.Combine(ProjectDirectory, x), + ProjectDirectory, + systemReferenceDirectories + )); + + Dictionary responseFilesWithErrors = responseFilesData.Where(x => x.Value.Errors.Any()) + .ToDictionary(x => x.Key, x => x.Value); + + if (responseFilesWithErrors.Any()) + { + foreach (var error in responseFilesWithErrors) + foreach (var valueError in error.Value.Errors) + { + Debug.LogError($"{error.Key} Parse Error : {valueError}"); + } + } + + return responseFilesData.Select(x => x.Value); + } + + Dictionary GenerateAllAssetProjectParts() + { + Dictionary stringBuilders = new Dictionary(); + + foreach (string asset in m_AssemblyNameProvider.GetAllAssetPaths()) + { + // Exclude files coming from packages except if they are internalized. + // TODO: We need assets from the assembly API + if (!m_ShouldGenerateAll && IsInternalizedPackagePath(asset)) + { + continue; + } + + string extension = Path.GetExtension(asset); + if (IsSupportedExtension(extension) && ScriptingLanguage.None == ScriptingLanguageFor(extension)) + { + // Find assembly the asset belongs to by adding script extension and using compilation pipeline. + var assemblyName = m_AssemblyNameProvider.GetAssemblyNameFromScriptPath(asset + ".cs"); + + if (string.IsNullOrEmpty(assemblyName)) + { + continue; + } + + assemblyName = Utility.FileNameWithoutExtension(assemblyName); + + if (!stringBuilders.TryGetValue(assemblyName, out var projectBuilder)) + { + projectBuilder = new StringBuilder(); + stringBuilders[assemblyName] = projectBuilder; + } + + projectBuilder.Append(" ").Append(k_WindowsNewline); + } + } + + var result = new Dictionary(); + + foreach (var entry in stringBuilders) + result[entry.Key] = entry.Value.ToString(); + + return result; + } + + bool IsInternalizedPackagePath(string file) + { + if (string.IsNullOrWhiteSpace(file)) + { + return false; + } + + var packageInfo = m_AssemblyNameProvider.FindForAssetPath(file); + if (packageInfo == null) { + return false; + } + var packageSource = packageInfo.source; + return packageSource != PackageSource.Embedded && packageSource != PackageSource.Local; + } + + void SyncProject( + Assembly island, + Dictionary allAssetsProjectParts, + IEnumerable responseFilesData, + List allProjectIslands) + { + SyncProjectFileIfNotChanged(ProjectFile(island), ProjectText(island, allAssetsProjectParts, responseFilesData, allProjectIslands)); + } + + void SyncProjectFileIfNotChanged(string path, string newContents) + { + if (Path.GetExtension(path) == ".csproj") + { + //newContents = AssetPostprocessingInternal.CallOnGeneratedCSProject(path, newContents); TODO: Call specific code here + } + + SyncFileIfNotChanged(path, newContents); + } + + void SyncSolutionFileIfNotChanged(string path, string newContents) + { + //newContents = AssetPostprocessingInternal.CallOnGeneratedSlnSolution(path, newContents); TODO: Call specific code here + + SyncFileIfNotChanged(path, newContents); + } + + void SyncFileIfNotChanged(string filename, string newContents) + { + if (File.Exists(filename) && + newContents == File.ReadAllText(filename)) + { + return; + } + if (Settings.ShouldSync) + { + File.WriteAllText(filename, newContents, Encoding.UTF8); + } + else + { + var utf8 = Encoding.UTF8; + byte[] utfBytes = utf8.GetBytes(newContents); + Settings.SyncPath[filename] = utf8.GetString(utfBytes, 0, utfBytes.Length); + } + } + + string ProjectText(Assembly assembly, + Dictionary allAssetsProjectParts, + IEnumerable responseFilesData, + List allProjectIslands) + { + var projectBuilder = new StringBuilder(ProjectHeader(assembly, responseFilesData)); + var references = new List(); + var projectReferences = new List(); + + foreach (string file in assembly.sourceFiles) + { + if (!ShouldFileBePartOfSolution(file)) + continue; + + var extension = Path.GetExtension(file).ToLower(); + var fullFile = EscapedRelativePathFor(file); + if (".dll" != extension) + { + projectBuilder.Append(" ").Append(k_WindowsNewline); + } + else + { + references.Add(fullFile); + } + } + + var assemblyName = Utility.FileNameWithoutExtension(assembly.outputPath); + + // Append additional non-script files that should be included in project generation. + if (allAssetsProjectParts.TryGetValue(assemblyName, out var additionalAssetsForProject)) + projectBuilder.Append(additionalAssetsForProject); + + var islandRefs = references.Union(assembly.allReferences); + + foreach (string reference in islandRefs) + { + if (reference.EndsWith("/UnityEditor.dll", StringComparison.Ordinal) + || reference.EndsWith("/UnityEngine.dll", StringComparison.Ordinal) + || reference.EndsWith("\\UnityEditor.dll", StringComparison.Ordinal) + || reference.EndsWith("\\UnityEngine.dll", StringComparison.Ordinal)) + continue; + + var match = k_ScriptReferenceExpression.Match(reference); + if (match.Success) + { + // assume csharp language + // Add a reference to a project except if it's a reference to a script assembly + // that we are not generating a project for. This will be the case for assemblies + // coming from .assembly.json files in non-internalized packages. + var dllName = match.Groups["dllname"].Value; + if (allProjectIslands.Any(i => Path.GetFileName(i.outputPath) == dllName)) + { + projectReferences.Add(match); + continue; + } + } + + string fullReference = Path.IsPathRooted(reference) ? reference : Path.Combine(ProjectDirectory, reference); + + AppendReference(fullReference, projectBuilder); + } + + var responseRefs = responseFilesData.SelectMany(x => x.FullPathReferences.Select(r => r)); + foreach (var reference in responseRefs) + { + AppendReference(reference, projectBuilder); + } + + if (0 < projectReferences.Count) + { + projectBuilder.AppendLine(" "); + projectBuilder.AppendLine(" "); + foreach (Match reference in projectReferences) + { + var referencedProject = reference.Groups["project"].Value; + + projectBuilder.Append(" ").Append(k_WindowsNewline); + projectBuilder.Append(" {").Append(ProjectGuid(Path.Combine("Temp", reference.Groups["project"].Value + ".dll"))).Append("}").Append(k_WindowsNewline); + projectBuilder.Append(" ").Append(referencedProject).Append("").Append(k_WindowsNewline); + projectBuilder.AppendLine(" "); + } + } + + projectBuilder.Append(ProjectFooter()); + return projectBuilder.ToString(); + } + + static void AppendReference(string fullReference, StringBuilder projectBuilder) + { + //replace \ with / and \\ with / + var escapedFullPath = SecurityElement.Escape(fullReference); + escapedFullPath = escapedFullPath.Replace("\\", "/"); + escapedFullPath = escapedFullPath.Replace("\\\\", "/"); + projectBuilder.Append(" ").Append(k_WindowsNewline); + projectBuilder.Append(" ").Append(escapedFullPath).Append("").Append(k_WindowsNewline); + projectBuilder.Append(" ").Append(k_WindowsNewline); + } + + public string ProjectFile(Assembly assembly) + { + return Path.Combine(ProjectDirectory, $"{Utility.FileNameWithoutExtension(assembly.outputPath)}.csproj"); + } + + public string SolutionFile() + { + return Path.Combine(ProjectDirectory, $"{m_ProjectName}.sln"); + } + + string ProjectHeader( + Assembly island, + IEnumerable responseFilesData + ) + { + var arguments = new object[] + { + k_ToolsVersion, k_ProductVersion, ProjectGuid(island.outputPath), + InternalEditorUtility.GetEngineAssemblyPath(), + InternalEditorUtility.GetEditorAssemblyPath(), + string.Join(";", new[] { "DEBUG", "TRACE" }.Concat(EditorUserBuildSettings.activeScriptCompilationDefines).Concat(island.defines).Concat(responseFilesData.SelectMany(x => x.Defines)).Distinct().ToArray()), + MSBuildNamespaceUri, + Utility.FileNameWithoutExtension(island.outputPath), + EditorSettings.projectGenerationRootNamespace, + k_TargetFrameworkVersion, + k_TargetLanguageVersion, + k_BaseDirectory, + island.compilerOptions.AllowUnsafeCode | responseFilesData.Any(x => x.Unsafe) + }; + + try + { + return string.Format(GetProjectHeaderTemplate(), arguments); + } + catch (Exception) + { + throw new NotSupportedException("Failed creating c# project because the c# project header did not have the correct amount of arguments, which is " + arguments.Length); + } + } + + static string GetSolutionText() + { + return string.Join("\r\n", @"", @"Microsoft Visual Studio Solution File, Format Version {0}", @"# Visual Studio {1}", @"{2}", @"Global", @" GlobalSection(SolutionConfigurationPlatforms) = preSolution", @" Debug|Any CPU = Debug|Any CPU", @" Release|Any CPU = Release|Any CPU", @" EndGlobalSection", @" GlobalSection(ProjectConfigurationPlatforms) = postSolution", @"{3}", @" EndGlobalSection", @" GlobalSection(SolutionProperties) = preSolution", @" HideSolutionNode = FALSE", @" EndGlobalSection", @"EndGlobal", @"").Replace(" ", "\t"); + } + + static string GetProjectFooterTemplate() + { + return string.Join("\r\n", @" ", @" ", @" ", @"", @""); + } + + static string GetProjectHeaderTemplate() + { + var header = new[] + { + @"", + @"", + @" ", + @" {10}", + @" ", + @" ", + @" Debug", + @" AnyCPU", + @" {1}", + @" 2.0", + @" {8}", + @" {{{2}}}", + @" Library", + @" Properties", + @" {7}", + @" {9}", + @" 512", + @" {11}", + @" ", + @" ", + @" true", + @" full", + @" false", + @" Temp\bin\Debug\", + @" {5}", + @" prompt", + @" 4", + @" 0169", + @" {12}", + @" ", + @" ", + @" pdbonly", + @" true", + @" Temp\bin\Release\", + @" prompt", + @" 4", + @" 0169", + @" {12}", + @" " + }; + + var forceExplicitReferences = new[] + { + @" ", + @" true", + @" true", + @" false", + @" false", + @" false", + @" " + }; + + var itemGroupStart = new[] + { + @" " + }; + + var footer = new[] + { + @" ", + @" {3}", + @" ", + @" ", + @" {4}", + @" ", + @" ", + @" ", + @"" + }; + + var text = header.Concat(forceExplicitReferences).Concat(itemGroupStart).Concat(footer).ToArray(); + return string.Join("\r\n", text); + } + + void SyncSolution(IEnumerable islands) + { + SyncSolutionFileIfNotChanged(SolutionFile(), SolutionText(islands)); + } + + string SolutionText(IEnumerable islands) + { + var fileversion = "11.00"; + var vsversion = "2010"; + + var relevantIslands = RelevantIslandsForMode(islands); + string projectEntries = GetProjectEntries(relevantIslands); + string projectConfigurations = string.Join(k_WindowsNewline, relevantIslands.Select(i => GetProjectActiveConfigurations(ProjectGuid(i.outputPath))).ToArray()); + return string.Format(GetSolutionText(), fileversion, vsversion, projectEntries, projectConfigurations); + } + + static IEnumerable RelevantIslandsForMode(IEnumerable islands) + { + IEnumerable relevantIslands = islands.Where(i => ScriptingLanguage.CSharp == ScriptingLanguageFor(i)); + return relevantIslands; + } + + /// + /// Get a Project("{guid}") = "MyProject", "MyProject.unityproj", "{projectguid}" + /// entry for each relevant language + /// + string GetProjectEntries(IEnumerable islands) + { + var projectEntries = islands.Select(i => string.Format( + m_SolutionProjectEntryTemplate, + SolutionGuid(i), Utility.FileNameWithoutExtension(i.outputPath), Path.GetFileName(ProjectFile(i)), ProjectGuid(i.outputPath) + )); + + return string.Join(k_WindowsNewline, projectEntries.ToArray()); + } + + /// + /// Generate the active configuration string for a given project guid + /// + string GetProjectActiveConfigurations(string projectGuid) + { + return string.Format( + m_SolutionProjectConfigurationTemplate, + projectGuid); + } + + string EscapedRelativePathFor(string file) + { + var projectDir = ProjectDirectory.Replace('/', '\\'); + file = file.Replace('/', '\\'); + var path = SkipPathPrefix(file, projectDir); + + var packageInfo = m_AssemblyNameProvider.FindForAssetPath(path.Replace('\\', '/')); + if (packageInfo != null) { + // We have to normalize the path, because the PackageManagerRemapper assumes + // dir seperators will be os specific. + var absolutePath = Path.GetFullPath(NormalizePath(path)).Replace('/', '\\'); + path = SkipPathPrefix(absolutePath, projectDir); + } + + return SecurityElement.Escape(path); + } + + static string SkipPathPrefix(string path, string prefix) + { + if (path.Replace("\\","/").StartsWith($"{prefix}/")) + return path.Substring(prefix.Length + 1); + return path; + } + + static string NormalizePath(string path) + { + if (Path.DirectorySeparatorChar == '\\') + return path.Replace('/', Path.DirectorySeparatorChar); + return path.Replace('\\', Path.DirectorySeparatorChar); + } + + + string ProjectGuid(string assembly) + { + return SolutionGuidGenerator.GuidForProject(m_ProjectName + Utility.FileNameWithoutExtension(assembly)); + } + + string SolutionGuid(Assembly island) + { + return SolutionGuidGenerator.GuidForSolution(m_ProjectName, GetExtensionOfSourceFiles(island.sourceFiles)); + } + + static string ProjectFooter() + { + return GetProjectFooterTemplate(); + } + + static string GetProjectExtension() + { + return ".csproj"; + } + + void WriteVSCodeSettingsFiles() + { + var vsCodeDirectory = Path.Combine(ProjectDirectory, ".vscode"); + + if (!Directory.Exists(vsCodeDirectory)) + Directory.CreateDirectory(vsCodeDirectory); + + var vsCodeSettingsJson = Path.Combine(vsCodeDirectory, "settings.json"); + + if (!File.Exists(vsCodeSettingsJson)) + File.WriteAllText(vsCodeSettingsJson, k_SettingsJson); + } + } + + public static class SolutionGuidGenerator + { + public static string GuidForProject(string projectName) + { + return ComputeGuidHashFor(projectName + "salt"); + } + + public static string GuidForSolution(string projectName, string sourceFileExtension) + { + if (sourceFileExtension.ToLower() == "cs") + // GUID for a C# class library: http://www.codeproject.com/Reference/720512/List-of-Visual-Studio-Project-Type-GUIDs + return "FAE04EC0-301F-11D3-BF4B-00C04F79EFBC"; + + return ComputeGuidHashFor(projectName); + } + + static string ComputeGuidHashFor(string input) + { + var hash = MD5.Create().ComputeHash(Encoding.Default.GetBytes(input)); + return HashAsGuid(HashToString(hash)); + } + + static string HashAsGuid(string hash) + { + var guid = hash.Substring(0, 8) + "-" + hash.Substring(8, 4) + "-" + hash.Substring(12, 4) + "-" + hash.Substring(16, 4) + "-" + hash.Substring(20, 12); + return guid.ToUpper(); + } + + static string HashToString(byte[] bs) + { + var sb = new StringBuilder(); + foreach (byte b in bs) + sb.Append(b.ToString("x2")); + return sb.ToString(); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.ide.vscode@1.1.0/Editor/Unity.com.unity.vscode.Editor.asmdef b/KerbalVR/Library/PackageCache/com.unity.ide.vscode@1.1.0/Editor/Unity.com.unity.vscode.Editor.asmdef new file mode 100644 index 00000000..032da7cb --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ide.vscode@1.1.0/Editor/Unity.com.unity.vscode.Editor.asmdef @@ -0,0 +1,9 @@ +{ + "name": "Unity.VSCode.Editor", + "references": [], + "optionalUnityReferences": [], + "includePlatforms": [ + "Editor" + ], + "excludePlatforms": [] +} diff --git a/KerbalVR/Library/PackageCache/com.unity.ide.vscode@1.1.0/Editor/Utility.cs b/KerbalVR/Library/PackageCache/com.unity.ide.vscode@1.1.0/Editor/Utility.cs new file mode 100644 index 00000000..d5848569 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ide.vscode@1.1.0/Editor/Utility.cs @@ -0,0 +1,35 @@ +namespace VSCodeEditor +{ + public static class Utility + { + public static string FileNameWithoutExtension(string path) + { + if (string.IsNullOrEmpty(path)) + { + return ""; + } + + var indexOfDot = -1; + var indexOfSlash = 0; + for (var i = path.Length - 1; i >= 0; i--) + { + if (indexOfDot == -1 && path[i] == '.') + { + indexOfDot = i; + } + if (indexOfSlash == 0 && path[i] == '/' || path[i] == '\\') + { + indexOfSlash = i + 1; + break; + } + } + + if (indexOfDot == -1) + { + indexOfDot = path.Length - 1; + } + + return path.Substring(indexOfSlash, indexOfDot - indexOfSlash); + } + } +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.ide.vscode@1.1.0/Editor/VSCodeDiscovery.cs b/KerbalVR/Library/PackageCache/com.unity.ide.vscode@1.1.0/Editor/VSCodeDiscovery.cs new file mode 100644 index 00000000..9d2d1f2e --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ide.vscode@1.1.0/Editor/VSCodeDiscovery.cs @@ -0,0 +1,136 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using UnityEditor; +using UnityEngine; +using Unity.CodeEditor; + +namespace VSCodeEditor +{ + public interface IDiscovery { + CodeEditor.Installation[] PathCallback(); + } + + public class VSCodeDiscovery : IDiscovery { + List m_Installations; + + public CodeEditor.Installation[] PathCallback() + { + if (m_Installations == null) + { + m_Installations = new List(); + FindInstallationPaths(); + } + + return m_Installations.ToArray(); + } + + void FindInstallationPaths() + { + string[] possiblePaths = +#if UNITY_EDITOR_OSX + { + "/Applications/Visual Studio Code.app", + "/Applications/Visual Studio Code - Insiders.app" + }; +#elif UNITY_EDITOR_WIN + { + GetProgramFiles() + @"/Microsoft VS Code/bin/code.cmd", + GetProgramFiles() + @"/Microsoft VS Code/Code.exe", + GetProgramFiles() + @"/Microsoft VS Code Insiders/bin/code-insiders.cmd", + GetProgramFiles() + @"/Microsoft VS Code Insiders/Code.exe", + GetLocalAppData() + @"/Programs/Microsoft VS Code/bin/code.cmd", + GetLocalAppData() + @"/Programs/Microsoft VS Code/Code.exe", + GetLocalAppData() + @"/Programs/Microsoft VS Code Insiders/bin/code-insiders.cmd", + GetLocalAppData() + @"/Programs/Microsoft VS Code Insiders/Code.exe", + }; +#else + { + "/usr/bin/code", + "/bin/code", + "/usr/local/bin/code", + "/var/lib/flatpak/exports/bin/com.visualstudio.code", + "/snap/current/bin/code" + }; +#endif + var existingPaths = possiblePaths.Where(VSCodeExists).ToList(); + if (!existingPaths.Any()) + { + return; + } + + var lcp = GetLongestCommonPrefix(existingPaths); + switch (existingPaths.Count) + { + case 1: + { + var path = existingPaths.First(); + m_Installations = new List + { + new CodeEditor.Installation + { + Path = path, + Name = path.Contains("Insiders") + ? "Visual Studio Code Insiders" + : "Visual Studio Code" + } + }; + break; + } + case 2 when existingPaths.Any(path => !(path.Substring(lcp.Length).Contains("/") || path.Substring(lcp.Length).Contains("\\"))): + { + goto case 1; + } + default: + { + m_Installations = existingPaths.Select(path => new CodeEditor.Installation + { + Name = $"Visual Studio Code Insiders ({path.Substring(lcp.Length)})", + Path = path + }).ToList(); + + break; + } + } + } + +#if UNITY_EDITOR_WIN + static string GetProgramFiles() + { + return Environment.GetEnvironmentVariable("ProgramFiles")?.Replace("\\", "/"); + } + + static string GetLocalAppData() + { + return Environment.GetEnvironmentVariable("LOCALAPPDATA")?.Replace("\\", "/"); + } +#endif + + static string GetLongestCommonPrefix(List paths) + { + var baseLength = paths.First().Length; + for (var pathIndex = 1; pathIndex < paths.Count; pathIndex++) + { + baseLength = Math.Min(baseLength, paths[pathIndex].Length); + for (var i = 0; i < baseLength; i++) + { + if (paths[pathIndex][i] == paths[0][i]) continue; + + baseLength = i; + break; + } + } + return paths[0].Substring(0, baseLength); + } + + static bool VSCodeExists(string path) + { +#if UNITY_EDITOR_OSX + return System.IO.Directory.Exists(path); +#else + return new FileInfo(path).Exists; +#endif + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.ide.vscode@1.1.0/Editor/VSCodeScriptEditor.cs b/KerbalVR/Library/PackageCache/com.unity.ide.vscode@1.1.0/Editor/VSCodeScriptEditor.cs new file mode 100644 index 00000000..87f1b4cd --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ide.vscode@1.1.0/Editor/VSCodeScriptEditor.cs @@ -0,0 +1,253 @@ +using System; +using System.IO; +using System.Linq; +using System.Diagnostics; +using UnityEditor; +using UnityEngine; +using Unity.CodeEditor; + +namespace VSCodeEditor { + [InitializeOnLoad] + public class VSCodeScriptEditor : IExternalCodeEditor + { + const string vscode_argument = "vscode_arguments"; + const string vscode_generate_all = "unity_generate_all_csproj"; + const string vscode_extension = "vscode_userExtensions"; + static readonly GUIContent k_ResetArguments = EditorGUIUtility.TrTextContent("Reset argument"); + string m_Arguments; + + IDiscovery m_Discoverability; + IGenerator m_ProjectGeneration; + + static readonly string[] k_SupportedFileNames = { "code.exe", "visualstudiocode.app", "visualstudiocode-insiders.app", "vscode.app", "code.app", "code.cmd", "code-insiders.cmd", "code", "com.visualstudio.code" }; + + static bool IsOSX => Application.platform == RuntimePlatform.OSXEditor; + + static string GetDefaultApp => EditorPrefs.GetString("kScriptsDefaultApp"); + + static string DefaultArgument { get; } = "\"$(ProjectPath)\" -g \"$(File)\":$(Line):$(Column)"; + string Arguments + { + get => m_Arguments ?? (m_Arguments = EditorPrefs.GetString(vscode_argument, DefaultArgument)); + set + { + m_Arguments = value; + EditorPrefs.SetString(vscode_argument, value); + } + } + + static string[] defaultExtensions + { + get + { + var customExtensions = new[] {"json", "asmdef", "log"}; + return EditorSettings.projectGenerationBuiltinExtensions + .Concat(EditorSettings.projectGenerationUserExtensions) + .Concat(customExtensions) + .Distinct().ToArray(); + } + } + + static string[] HandledExtensions + { + get + { + return HandledExtensionsString + .Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries) + .Select(s => s.TrimStart('.', '*')) + .ToArray(); + } + } + + static string HandledExtensionsString + { + get => EditorPrefs.GetString(vscode_extension, string.Join(";", defaultExtensions)); + set => EditorPrefs.SetString(vscode_extension, value); + } + + public bool TryGetInstallationForPath(string editorPath, out CodeEditor.Installation installation) + { + var lowerCasePath = editorPath.ToLower(); + var filename = Path.GetFileName(lowerCasePath).Replace(" ", ""); + var installations = Installations; + if (!k_SupportedFileNames.Contains(filename)) + { + installation = default; + return false; + } + if (!installations.Any()) + { + installation = new CodeEditor.Installation + { + Name = "Visual Studio Code", + Path = editorPath + }; + } + else + { + try + { + installation = installations.First(inst => inst.Path == editorPath); + } + catch (InvalidOperationException) + { + installation = new CodeEditor.Installation + { + Name = "Visual Studio Code", + Path = editorPath + }; + } + } + + return true; + } + + public void OnGUI() + { + Arguments = EditorGUILayout.TextField("External Script Editor Args", Arguments); + if (GUILayout.Button(k_ResetArguments, GUILayout.Width(120))) + { + Arguments = DefaultArgument; + } + var prevGenerate = EditorPrefs.GetBool(vscode_generate_all, false); + + var generateAll = EditorGUILayout.Toggle("Generate all .csproj files.", prevGenerate); + if (generateAll != prevGenerate) + { + EditorPrefs.SetBool(vscode_generate_all, generateAll); + } + m_ProjectGeneration.GenerateAll(generateAll); + + HandledExtensionsString = EditorGUILayout.TextField(new GUIContent("Extensions handled: "), HandledExtensionsString); + } + + public void CreateIfDoesntExist() + { + if (!m_ProjectGeneration.HasSolutionBeenGenerated()) + { + m_ProjectGeneration.Sync(); + } + } + + public void SyncIfNeeded(string[] addedFiles, string[] deletedFiles, string[] movedFiles, string[] movedFromFiles, string[] importedFiles) + { + m_ProjectGeneration.SyncIfNeeded(addedFiles.Union(deletedFiles).Union(movedFiles).Union(movedFromFiles), importedFiles); + } + + public void SyncAll() + { + AssetDatabase.Refresh(); + m_ProjectGeneration.Sync(); + } + + public bool OpenProject(string path, int line, int column) + { + if (path != "" && !SupportsExtension(path)) // Assets - Open C# Project passes empty path here + { + return false; + } + + if (line == -1) + line = 1; + if (column == -1) + column = 0; + + string arguments; + if (Arguments != DefaultArgument) + { + arguments = m_ProjectGeneration.ProjectDirectory != path + ? CodeEditor.ParseArgument(Arguments, path, line, column) + : m_ProjectGeneration.ProjectDirectory; + } + else + { + arguments = $@"""{m_ProjectGeneration.ProjectDirectory}"""; + if (m_ProjectGeneration.ProjectDirectory != path && path.Length != 0) + { + arguments += $@" -g ""{path}"":{line}:{column}"; + } + } + + if (IsOSX) + { + return OpenOSX(arguments); + } + + var process = new Process + { + StartInfo = new ProcessStartInfo + { + FileName = GetDefaultApp, + Arguments = arguments, + WindowStyle = ProcessWindowStyle.Hidden, + CreateNoWindow = true, + UseShellExecute = true, + } + }; + + process.Start(); + return true; + } + + static bool OpenOSX(string arguments) + { + var process = new Process + { + StartInfo = new ProcessStartInfo + { + FileName = "open", + Arguments = $"\"{GetDefaultApp}\" --args {arguments}", + UseShellExecute = true, + } + }; + + process.Start(); + return true; + } + + static bool SupportsExtension(string path) + { + var extension = Path.GetExtension(path); + if (string.IsNullOrEmpty(extension)) + return false; + return HandledExtensions.Contains(extension.TrimStart('.')); + } + + public CodeEditor.Installation[] Installations => m_Discoverability.PathCallback(); + + public VSCodeScriptEditor(IDiscovery discovery, IGenerator projectGeneration) + { + m_Discoverability = discovery; + m_ProjectGeneration = projectGeneration; + } + + static VSCodeScriptEditor() + { + var editor = new VSCodeScriptEditor(new VSCodeDiscovery(), new ProjectGeneration()); + CodeEditor.Register(editor); + + if (IsVSCodeInstallation(CodeEditor.CurrentEditorInstallation)) + { + editor.CreateIfDoesntExist(); + } + } + + static bool IsVSCodeInstallation(string path) + { + if (string.IsNullOrEmpty(path)) + { + return false; + } + + var lowerCasePath = path.ToLower(); + var filename = Path + .GetFileName(lowerCasePath.Replace('\\', Path.DirectorySeparatorChar).Replace('/', Path.DirectorySeparatorChar)) + .Replace(" ", ""); + return k_SupportedFileNames.Contains(filename); + } + + public void Initialize(string editorInstallationPath) + { + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.ide.vscode@1.1.0/LICENSE.md b/KerbalVR/Library/PackageCache/com.unity.ide.vscode@1.1.0/LICENSE.md new file mode 100644 index 00000000..eb18dfb7 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ide.vscode@1.1.0/LICENSE.md @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Unity Technologies + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/KerbalVR/Library/PackageCache/com.unity.ide.vscode@1.1.0/package.json b/KerbalVR/Library/PackageCache/com.unity.ide.vscode@1.1.0/package.json new file mode 100644 index 00000000..2972856c --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.ide.vscode@1.1.0/package.json @@ -0,0 +1,17 @@ +{ + "name": "com.unity.ide.vscode", + "displayName": "Visual Studio Code Editor", + "description": "Code editor integration for supporting Visual Studio Code as code editor for unity. Adds support for generating csproj files for intellisense purposes, auto discovery of installations, etc.", + "version": "1.1.0", + "unity": "2019.2", + "unityRelease": "0a12", + "dependencies": {}, + "relatedPackages": { + "com.unity.ide.vscode.tests": "1.0.4" + }, + "repository": { + "type": "git", + "url": "git@github.cds.internal.unity3d.com:unity/com.unity.ide.vscode.git", + "revision": "be12768c09e4711e6d38ba647df27fac67dbfd1f" + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/CHANGELOG.md b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/CHANGELOG.md new file mode 100644 index 00000000..951b9b8d --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/CHANGELOG.md @@ -0,0 +1,55 @@ +# Changelog + +## [1.0.2] - 2019-03-18 + +### Changed +- Fixed issue with population of Syncvar variable on a class derived from a networkbehaviour base class (case 1066429) +- Fixed issue with IsDynamic not working on .net 3.5 profile (use something else)] +- Fixed file lock error when building under certain conditions (case 1115492) + +## [1.0.1] - 2019-02-14 + +### Changed +- Disabled warnings around the usage of the 'new' keyword in the NetworkTransform, it's needed sometimes but can trigger when building (likely because of stripping) and the warning messed with CI/automation + +## [1.0.0] - 2019-02-13 + +### Changed +- Only updating version to 1.0.0 to reflect the status of the package + +## [0.2.6-preview] - 2019-02-13 + +### Changed +- Got rid of all warnings generated when the package is built, so it's CI/automation friendly +- Readme updated + +## [0.2.5-preview] - 2019-01-29 + +### Changed +- Fixed Syncvar variable update issue. Modify both the writing and reading syncvar data as per channel. (Fixed cases 1110031, 1111442 and 1117258) + +## [0.2.4-preview] - 2019-01-11 + +### Changed +- Fixed issue with assembly dependencies not being found by the weaver during certain conditions (like when doing full reimport). + +### Added +- Added API documentation, migrated from unity source repo, only some formatting changes, text itself unchanged. + +## [0.2.3-preview] - 2018-12-17 + +### This is the first release of the *Unity Multiplayer HLAPI \*. + +Initial release of the Unity Multiplayer HLAPI (or UNet HLAPI) moved into a package. This will +work with Unity 2019.1.0a12 and onwards. + +This was previously an extension DLL but the layout has been moved from the extension style to a package format. Also all +parts which existed in the Unity engine (native code) have been moved out and utilize public API instead. Mostly +this involved +- Update bump is now created with a hidden game object, instead of registering in the player loop internally +- Domain reloads are detected with public APIs +- Weaver invocation (used for code generation) registers with the compiliation pipeline API and receives callbacks + every time compilation finishes so it can parse the DLLs. +- Profiler panel functionality was made possible by making some internal APIs puplic for now. + +Also, some runtime tests have been moved to the package as playmode tests. \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkAnimatorEditor.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkAnimatorEditor.cs new file mode 100644 index 00000000..e5383bdf --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkAnimatorEditor.cs @@ -0,0 +1,97 @@ +#if ENABLE_UNET +using System; +using UnityEditor.Animations; +using UnityEngine; +using UnityEngine.Networking; + +namespace UnityEditor +{ + [CustomEditor(typeof(NetworkAnimator), true)] + [CanEditMultipleObjects] + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class NetworkAnimatorEditor : Editor + { + NetworkAnimator m_AnimSync; + [NonSerialized] bool m_Initialized; + + SerializedProperty m_AnimatorProperty; + GUIContent m_AnimatorLabel; + + void Init() + { + if (m_Initialized) + return; + + m_Initialized = true; + m_AnimSync = target as NetworkAnimator; + + m_AnimatorProperty = serializedObject.FindProperty("m_Animator"); + m_AnimatorLabel = TextUtility.TextContent("Animator", "The Animator component to synchronize."); + } + + public override void OnInspectorGUI() + { + Init(); + serializedObject.Update(); + DrawControls(); + serializedObject.ApplyModifiedProperties(); + } + + void DrawControls() + { + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(m_AnimatorProperty, m_AnimatorLabel); + if (EditorGUI.EndChangeCheck()) + { + m_AnimSync.ResetParameterOptions(); + } + + if (m_AnimSync.animator == null) + return; + + var controller = m_AnimSync.animator.runtimeAnimatorController as AnimatorController; + if (controller != null) + { + var showWarning = false; + EditorGUI.indentLevel += 1; + int i = 0; + + foreach (var p in controller.parameters) + { + if (i >= 32) + { + showWarning = true; + break; + } + + bool oldSend = m_AnimSync.GetParameterAutoSend(i); + bool send = EditorGUILayout.Toggle(p.name, oldSend); + if (send != oldSend) + { + m_AnimSync.SetParameterAutoSend(i, send); + EditorUtility.SetDirty(target); + } + i += 1; + } + + if (showWarning) + { + EditorGUILayout.HelpBox("NetworkAnimator can only select between the first 32 parameters in a mecanim controller", MessageType.Warning); + } + + EditorGUI.indentLevel -= 1; + } + + if (Application.isPlaying) + { + EditorGUILayout.Separator(); + if (m_AnimSync.param0 != "") EditorGUILayout.LabelField("Param 0", m_AnimSync.param0); + if (m_AnimSync.param1 != "") EditorGUILayout.LabelField("Param 1", m_AnimSync.param1); + if (m_AnimSync.param2 != "") EditorGUILayout.LabelField("Param 2", m_AnimSync.param2); + if (m_AnimSync.param3 != "") EditorGUILayout.LabelField("Param 3", m_AnimSync.param3); + if (m_AnimSync.param4 != "") EditorGUILayout.LabelField("Param 4", m_AnimSync.param4); + } + } + } +} +#endif diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkBehaviourInspector.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkBehaviourInspector.cs new file mode 100644 index 00000000..064d7c0b --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkBehaviourInspector.cs @@ -0,0 +1,177 @@ +#if ENABLE_UNET +using System; +using System.Collections; +using System.Collections.Generic; +using System.Reflection; +using UnityEngine; +using UnityEngine.Networking; + +namespace UnityEditor +{ + [CustomEditor(typeof(NetworkBehaviour), true)] + [CanEditMultipleObjects] + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class NetworkBehaviourInspector : Editor + { + bool m_Initialized; + protected List m_SyncVarNames = new List(); + Type m_ScriptClass; + bool m_HasOnSerialize; + bool[] m_ShowSyncLists; + + GUIContent m_SyncVarIndicatorContent; + protected GUIContent m_NetworkChannelLabel; + protected GUIContent m_NetworkSendIntervalLabel; + + internal virtual bool hideScriptField + { + get { return false; } + } + + void Init(MonoScript script) + { + m_Initialized = true; + m_ScriptClass = script.GetClass(); + + m_SyncVarIndicatorContent = TextUtility.TextContent("SyncVar", "This variable has been marked with the [SyncVar] attribute."); + m_NetworkChannelLabel = TextUtility.TextContent("Network Channel", "QoS channel used for updates. Use the [NetworkSettings] class attribute to change this."); + m_NetworkSendIntervalLabel = TextUtility.TextContent("Network Send Interval", "Maximum update rate in seconds. Use the [NetworkSettings] class attribute to change this, or implement GetNetworkSendInterval"); + + foreach (var field in m_ScriptClass.GetFields(BindingFlags.Public | BindingFlags.Instance)) + { + Attribute[] fieldMarkers = (Attribute[])field.GetCustomAttributes(typeof(SyncVarAttribute), true); + if (fieldMarkers.Length > 0) + { + m_SyncVarNames.Add(field.Name); + } + } + var meth = script.GetClass().GetMethod("OnSerialize"); + if (meth != null) + { + if (meth.DeclaringType != typeof(NetworkBehaviour)) + { + m_HasOnSerialize = true; + } + } + + int numSyncLists = 0; + foreach (var f in serializedObject.targetObject.GetType().GetFields()) + { + if (f.FieldType.BaseType != null && f.FieldType.BaseType.Name.Contains("SyncList")) + { + numSyncLists += 1; + } + } + if (numSyncLists > 0) + { + m_ShowSyncLists = new bool[numSyncLists]; + } + } + + public override void OnInspectorGUI() + { + if (!m_Initialized) + { + serializedObject.Update(); + SerializedProperty scriptProperty = serializedObject.FindProperty("m_Script"); + if (scriptProperty == null) + return; + + MonoScript targetScript = scriptProperty.objectReferenceValue as MonoScript; + Init(targetScript); + } + + EditorGUI.BeginChangeCheck(); + serializedObject.Update(); + + // Loop through properties and create one field (including children) for each top level property. + SerializedProperty property = serializedObject.GetIterator(); + bool expanded = true; + while (property.NextVisible(expanded)) + { + bool isSyncVar = m_SyncVarNames.Contains(property.name); + if (property.propertyType == SerializedPropertyType.ObjectReference) + { + if (property.name == "m_Script") + { + if (hideScriptField) + { + continue; + } + + EditorGUI.BeginDisabledGroup(true); + } + + EditorGUILayout.PropertyField(property, true); + + if (isSyncVar) + { + GUILayout.Label(m_SyncVarIndicatorContent, EditorStyles.miniLabel, GUILayout.Width(EditorStyles.miniLabel.CalcSize(m_SyncVarIndicatorContent).x)); + } + + if (property.name == "m_Script") + { + EditorGUI.EndDisabledGroup(); + } + } + else + { + EditorGUILayout.BeginHorizontal(); + + EditorGUILayout.PropertyField(property, true); + + if (isSyncVar) + { + GUILayout.Label(m_SyncVarIndicatorContent, EditorStyles.miniLabel, GUILayout.Width(EditorStyles.miniLabel.CalcSize(m_SyncVarIndicatorContent).x)); + } + + EditorGUILayout.EndHorizontal(); + } + expanded = false; + } + serializedObject.ApplyModifiedProperties(); + EditorGUI.EndChangeCheck(); + + // find SyncLists.. they are not properties. + int syncListIndex = 0; + foreach (var field in serializedObject.targetObject.GetType().GetFields()) + { + if (field.FieldType.BaseType != null && field.FieldType.BaseType.Name.Contains("SyncList")) + { + m_ShowSyncLists[syncListIndex] = EditorGUILayout.Foldout(m_ShowSyncLists[syncListIndex], "SyncList " + field.Name + " [" + field.FieldType.Name + "]"); + if (m_ShowSyncLists[syncListIndex]) + { + EditorGUI.indentLevel += 1; + var synclist = field.GetValue(serializedObject.targetObject) as IEnumerable; + if (synclist != null) + { + int index = 0; + var enu = synclist.GetEnumerator(); + while (enu.MoveNext()) + { + if (enu.Current != null) + { + EditorGUILayout.LabelField("Item:" + index, enu.Current.ToString()); + } + index += 1; + } + } + EditorGUI.indentLevel -= 1; + } + syncListIndex += 1; + } + } + + if (m_HasOnSerialize) + { + var beh = target as NetworkBehaviour; + if (beh != null) + { + EditorGUILayout.LabelField(m_NetworkChannelLabel, new GUIContent(beh.GetNetworkChannel().ToString())); + EditorGUILayout.LabelField(m_NetworkSendIntervalLabel, new GUIContent(beh.GetNetworkSendInterval().ToString())); + } + } + } + } +} //namespace +#endif //ENABLE_UNET diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkDiscoveryEditor.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkDiscoveryEditor.cs new file mode 100644 index 00000000..bd2e6f3a --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkDiscoveryEditor.cs @@ -0,0 +1,134 @@ +#if ENABLE_UNET +using System; +using UnityEngine; +using UnityEngine.Networking; + +#pragma warning disable 618 +namespace UnityEditor +{ + [CustomEditor(typeof(NetworkDiscovery), true)] + [CanEditMultipleObjects] + public class NetworkDiscoveryEditor : Editor + { + bool m_Initialized; + NetworkDiscovery m_Discovery; + + SerializedProperty m_BroadcastPortProperty; + SerializedProperty m_BroadcastKeyProperty; + SerializedProperty m_BroadcastVersionProperty; + SerializedProperty m_BroadcastSubVersionProperty; + SerializedProperty m_BroadcastIntervalProperty; + SerializedProperty m_UseNetworkManagerProperty; + SerializedProperty m_BroadcastDataProperty; + SerializedProperty m_ShowGUIProperty; + SerializedProperty m_OffsetXProperty; + SerializedProperty m_OffsetYProperty; + + GUIContent m_BroadcastPortLabel; + GUIContent m_BroadcastKeyLabel; + GUIContent m_BroadcastVersionLabel; + GUIContent m_BroadcastSubVersionLabel; + GUIContent m_BroadcastIntervalLabel; + GUIContent m_UseNetworkManagerLabel; + GUIContent m_BroadcastDataLabel; + GUIContent m_ShowGUILabel; + GUIContent m_OffsetXLabel; + GUIContent m_OffsetYLabel; + + void Init() + { + if (m_Initialized) + { + if (m_BroadcastPortProperty == null) + { + // need to re-init + } + else + { + return; + } + } + + m_Initialized = true; + m_Discovery = target as NetworkDiscovery; + + m_BroadcastPortProperty = serializedObject.FindProperty("m_BroadcastPort"); + m_BroadcastKeyProperty = serializedObject.FindProperty("m_BroadcastKey"); + m_BroadcastVersionProperty = serializedObject.FindProperty("m_BroadcastVersion"); + m_BroadcastSubVersionProperty = serializedObject.FindProperty("m_BroadcastSubVersion"); + m_BroadcastIntervalProperty = serializedObject.FindProperty("m_BroadcastInterval"); + m_UseNetworkManagerProperty = serializedObject.FindProperty("m_UseNetworkManager"); + m_BroadcastDataProperty = serializedObject.FindProperty("m_BroadcastData"); + m_ShowGUIProperty = serializedObject.FindProperty("m_ShowGUI"); + m_OffsetXProperty = serializedObject.FindProperty("m_OffsetX"); + m_OffsetYProperty = serializedObject.FindProperty("m_OffsetY"); + + m_BroadcastPortLabel = TextUtility.TextContent("Broadcast Port", "The network port to broadcast to, and listen on."); + m_BroadcastKeyLabel = TextUtility.TextContent("Broadcast Key", "The key to broadcast. This key typically identifies the application."); + m_BroadcastVersionLabel = TextUtility.TextContent("Broadcast Version", "The version of the application to broadcast. This is used to match versions of the same application."); + m_BroadcastSubVersionLabel = TextUtility.TextContent("Broadcast SubVersion", "The sub-version of the application to broadcast."); + m_BroadcastIntervalLabel = TextUtility.TextContent("Broadcast Interval", "How often in milliseconds to broadcast when running as a server."); + m_UseNetworkManagerLabel = TextUtility.TextContent("Use NetworkManager", "Broadcast information from the NetworkManager, and auto-join matching games using the NetworkManager."); + m_BroadcastDataLabel = TextUtility.TextContent("Broadcast Data", "The data to broadcast when not using the NetworkManager"); + m_ShowGUILabel = TextUtility.TextContent("Show GUI", "Enable to draw the default broadcast control UI."); + m_OffsetXLabel = TextUtility.TextContent("Offset X", "The horizonal offset of the GUI."); + m_OffsetYLabel = TextUtility.TextContent("Offset Y", "The vertical offset of the GUI."); + } + + public override void OnInspectorGUI() + { + Init(); + serializedObject.Update(); + DrawControls(); + serializedObject.ApplyModifiedProperties(); + } + + void DrawControls() + { + if (m_Discovery == null) + return; + + EditorGUI.BeginChangeCheck(); + + EditorGUILayout.PropertyField(m_BroadcastPortProperty, m_BroadcastPortLabel); + + EditorGUILayout.PropertyField(m_BroadcastKeyProperty, m_BroadcastKeyLabel); + EditorGUILayout.PropertyField(m_BroadcastVersionProperty, m_BroadcastVersionLabel); + EditorGUILayout.PropertyField(m_BroadcastSubVersionProperty, m_BroadcastSubVersionLabel); + EditorGUILayout.PropertyField(m_BroadcastIntervalProperty, m_BroadcastIntervalLabel); + EditorGUILayout.PropertyField(m_UseNetworkManagerProperty, m_UseNetworkManagerLabel); + if (m_Discovery.useNetworkManager) + { + EditorGUILayout.LabelField(m_BroadcastDataLabel, new GUIContent(m_BroadcastDataProperty.stringValue)); + } + else + { + EditorGUILayout.PropertyField(m_BroadcastDataProperty, m_BroadcastDataLabel); + } + + EditorGUILayout.Separator(); + EditorGUILayout.PropertyField(m_ShowGUIProperty, m_ShowGUILabel); + if (m_Discovery.showGUI) + { + EditorGUILayout.PropertyField(m_OffsetXProperty, m_OffsetXLabel); + EditorGUILayout.PropertyField(m_OffsetYProperty, m_OffsetYLabel); + } + + if (EditorGUI.EndChangeCheck()) + { + serializedObject.ApplyModifiedProperties(); + } + + if (Application.isPlaying) + { + EditorGUILayout.Separator(); + EditorGUILayout.LabelField("hostId", m_Discovery.hostId.ToString()); + EditorGUILayout.LabelField("running", m_Discovery.running.ToString()); + EditorGUILayout.LabelField("isServer", m_Discovery.isServer.ToString()); + EditorGUILayout.LabelField("isClient", m_Discovery.isClient.ToString()); + } + } + } +} +#pragma warning restore 618 +#endif diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkIdentityEditor.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkIdentityEditor.cs new file mode 100644 index 00000000..5fb517e7 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkIdentityEditor.cs @@ -0,0 +1,122 @@ +#if ENABLE_UNET +using System; +using UnityEngine; +using UnityEngine.Networking; + +namespace UnityEditor +{ + [CustomEditor(typeof(NetworkIdentity), true)] + [CanEditMultipleObjects] + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class NetworkIdentityEditor : Editor + { + SerializedProperty m_ServerOnlyProperty; + SerializedProperty m_LocalPlayerAuthorityProperty; + + GUIContent m_ServerOnlyLabel; + GUIContent m_LocalPlayerAuthorityLabel; + GUIContent m_SpawnLabel; + + NetworkIdentity m_NetworkIdentity; + bool m_Initialized; + bool m_ShowObservers; + + void Init() + { + if (m_Initialized) + { + return; + } + m_Initialized = true; + m_NetworkIdentity = target as NetworkIdentity; + + m_ServerOnlyProperty = serializedObject.FindProperty("m_ServerOnly"); + m_LocalPlayerAuthorityProperty = serializedObject.FindProperty("m_LocalPlayerAuthority"); + + m_ServerOnlyLabel = TextUtility.TextContent("Server Only", "True if the object should only exist on the server."); + m_LocalPlayerAuthorityLabel = TextUtility.TextContent("Local Player Authority", "True if this object will be controlled by a player on a client."); + m_SpawnLabel = TextUtility.TextContent("Spawn Object", "This causes an unspawned server object to be spawned on clients"); + } + + public override void OnInspectorGUI() + { + if (m_ServerOnlyProperty == null) + { + m_Initialized = false; + } + + Init(); + + serializedObject.Update(); + + if (m_ServerOnlyProperty.boolValue) + { + EditorGUILayout.PropertyField(m_ServerOnlyProperty, m_ServerOnlyLabel); + EditorGUILayout.LabelField("Local Player Authority cannot be set for server-only objects"); + } + else if (m_LocalPlayerAuthorityProperty.boolValue) + { + EditorGUILayout.LabelField("Server Only cannot be set for Local Player Authority objects"); + EditorGUILayout.PropertyField(m_LocalPlayerAuthorityProperty, m_LocalPlayerAuthorityLabel); + } + else + { + EditorGUILayout.PropertyField(m_ServerOnlyProperty, m_ServerOnlyLabel); + EditorGUILayout.PropertyField(m_LocalPlayerAuthorityProperty, m_LocalPlayerAuthorityLabel); + } + + serializedObject.ApplyModifiedProperties(); + + if (!Application.isPlaying) + { + return; + } + + // Runtime actions below here + + EditorGUILayout.Separator(); + + if (m_NetworkIdentity.observers != null && m_NetworkIdentity.observers.Count > 0) + { + m_ShowObservers = EditorGUILayout.Foldout(m_ShowObservers, "Observers"); + if (m_ShowObservers) + { + EditorGUI.indentLevel += 1; + foreach (var o in m_NetworkIdentity.observers) + { + GameObject obj = null; + foreach (var p in o.playerControllers) + { + if (p != null) + { + obj = p.gameObject; + break; + } + } + if (obj) + EditorGUILayout.ObjectField("Connection " + o.connectionId, obj, typeof(GameObject), false); + else + EditorGUILayout.TextField("Connection " + o.connectionId); + } + EditorGUI.indentLevel -= 1; + } + } + + if (PrefabUtility.IsPartOfPrefabAsset(m_NetworkIdentity.gameObject)) + return; + + if (m_NetworkIdentity.gameObject.activeSelf && m_NetworkIdentity.netId.IsEmpty() && NetworkServer.active) + { + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.LabelField(m_SpawnLabel); + if (GUILayout.Toggle(false, "Spawn", EditorStyles.miniButtonLeft)) + { + NetworkServer.Spawn(m_NetworkIdentity.gameObject); + EditorUtility.SetDirty(target); // preview window STILL doens't update immediately.. + } + EditorGUILayout.EndHorizontal(); + } + } + } +} +#endif //ENABLE_UNET diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkInformationPreview.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkInformationPreview.cs new file mode 100644 index 00000000..08453082 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkInformationPreview.cs @@ -0,0 +1,286 @@ +#if ENABLE_UNET +using System; +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.Networking; +using UnityObject = UnityEngine.Object; + +#pragma warning disable 618 +namespace UnityEditor.Networking +{ + [CustomPreview(typeof(GameObject))] + class NetworkInformationPreview : ObjectPreview + { + class NetworkIdentityInfo + { + public GUIContent name; + public GUIContent value; + } + + class NetworkBehaviourInfo + { + // This is here just so we can check if it's enabled/disabled + public NetworkBehaviour behaviour; + public GUIContent name; + } + + class Styles + { + public GUIStyle labelStyle = new GUIStyle(EditorStyles.label); + public GUIStyle componentName = new GUIStyle(EditorStyles.boldLabel); + public GUIStyle disabledName = new GUIStyle(EditorStyles.miniLabel); + + public Styles() + { + Color fontColor = new Color(0.7f, 0.7f, 0.7f); + labelStyle.padding.right += 20; + labelStyle.normal.textColor = fontColor; + labelStyle.active.textColor = fontColor; + labelStyle.focused.textColor = fontColor; + labelStyle.hover.textColor = fontColor; + labelStyle.onNormal.textColor = fontColor; + labelStyle.onActive.textColor = fontColor; + labelStyle.onFocused.textColor = fontColor; + labelStyle.onHover.textColor = fontColor; + + componentName.normal.textColor = fontColor; + componentName.active.textColor = fontColor; + componentName.focused.textColor = fontColor; + componentName.hover.textColor = fontColor; + componentName.onNormal.textColor = fontColor; + componentName.onActive.textColor = fontColor; + componentName.onFocused.textColor = fontColor; + componentName.onHover.textColor = fontColor; + + disabledName.normal.textColor = fontColor; + disabledName.active.textColor = fontColor; + disabledName.focused.textColor = fontColor; + disabledName.hover.textColor = fontColor; + disabledName.onNormal.textColor = fontColor; + disabledName.onActive.textColor = fontColor; + disabledName.onFocused.textColor = fontColor; + disabledName.onHover.textColor = fontColor; + } + } + + List m_Info; + List m_Behaviours; + NetworkIdentity m_Identity; + GUIContent m_Title; + Styles m_Styles = new Styles(); + + public override void Initialize(UnityObject[] targets) + { + base.Initialize(targets); + GetNetworkInformation(target as GameObject); + } + + public override GUIContent GetPreviewTitle() + { + if (m_Title == null) + { + m_Title = TextUtility.TextContent("Network Information"); + } + return m_Title; + } + + public override bool HasPreviewGUI() + { + return m_Info != null && m_Info.Count > 0; + } + + public override void OnPreviewGUI(Rect r, GUIStyle background) + { + if (Event.current.type != EventType.Repaint) + return; + + if (m_Info == null || m_Info.Count == 0) + return; + + if (m_Styles == null) + m_Styles = new Styles(); + + // Get required label size for the names of the information values we're going to show + // There are two columns, one with label for the name of the info and the next for the value + Vector2 maxNameLabelSize = new Vector2(140, 16); + Vector2 maxValueLabelSize = GetMaxNameLabelSize(); + + //Apply padding + RectOffset previewPadding = new RectOffset(-5, -5, -5, -5); + r = previewPadding.Add(r); + + //Centering + float initialX = r.x + 10; + float initialY = r.y + 10; + + Rect labelRect = new Rect(initialX, initialY, maxNameLabelSize.x, maxNameLabelSize.y); + Rect idLabelRect = new Rect(maxNameLabelSize.x, initialY, maxValueLabelSize.x, maxValueLabelSize.y); + + foreach (var info in m_Info) + { + GUI.Label(labelRect, info.name, m_Styles.labelStyle); + GUI.Label(idLabelRect, info.value, m_Styles.componentName); + labelRect.y += labelRect.height; + labelRect.x = initialX; + idLabelRect.y += idLabelRect.height; + } + + // Show behaviours list in a different way than the name/value pairs above + float lastY = labelRect.y; + if (m_Behaviours != null && m_Behaviours.Count > 0) + { + Vector2 maxBehaviourLabelSize = GetMaxBehaviourLabelSize(); + Rect behaviourRect = new Rect(initialX, labelRect.y + 10, maxBehaviourLabelSize.x, maxBehaviourLabelSize.y); + + GUI.Label(behaviourRect, TextUtility.TextContent("Network Behaviours"), m_Styles.labelStyle); + behaviourRect.x += 20; // indent names + behaviourRect.y += behaviourRect.height; + + foreach (var info in m_Behaviours) + { + if (info.behaviour == null) + { + // could be the case in the editor after existing play mode. + continue; + } + if (info.behaviour.enabled) + { + GUI.Label(behaviourRect, info.name, m_Styles.componentName); + } + else + { + GUI.Label(behaviourRect, info.name, m_Styles.disabledName); + } + behaviourRect.y += behaviourRect.height; + lastY = behaviourRect.y; + } + + if (m_Identity.observers != null && m_Identity.observers.Count > 0) + { + Rect observerRect = new Rect(initialX, lastY + 10, 200, 20); + + GUI.Label(observerRect, TextUtility.TextContent("Network observers"), m_Styles.labelStyle); + observerRect.x += 20; // indent names + observerRect.y += observerRect.height; + + foreach (var info in m_Identity.observers) + { + GUI.Label(observerRect, info.address + ":" + info.connectionId, m_Styles.componentName); + observerRect.y += observerRect.height; + lastY = observerRect.y; + } + } + + if (m_Identity.clientAuthorityOwner != null) + { + Rect ownerRect = new Rect(initialX, lastY + 10, 400, 20); + GUI.Label(ownerRect, TextUtility.TextContent("Client Authority: " + m_Identity.clientAuthorityOwner), m_Styles.labelStyle); + } + } + } + + // Get the maximum size used by the value of information items + Vector2 GetMaxNameLabelSize() + { + Vector2 maxLabelSize = Vector2.zero; + foreach (var info in m_Info) + { + Vector2 labelSize = m_Styles.labelStyle.CalcSize(info.value); + if (maxLabelSize.x < labelSize.x) + { + maxLabelSize.x = labelSize.x; + } + if (maxLabelSize.y < labelSize.y) + { + maxLabelSize.y = labelSize.y; + } + } + return maxLabelSize; + } + + Vector2 GetMaxBehaviourLabelSize() + { + Vector2 maxLabelSize = Vector2.zero; + foreach (var behaviour in m_Behaviours) + { + Vector2 labelSize = m_Styles.labelStyle.CalcSize(behaviour.name); + if (maxLabelSize.x < labelSize.x) + { + maxLabelSize.x = labelSize.x; + } + if (maxLabelSize.y < labelSize.y) + { + maxLabelSize.y = labelSize.y; + } + } + return maxLabelSize; + } + + void GetNetworkInformation(GameObject gameObject) + { + m_Identity = gameObject.GetComponent(); + if (m_Identity != null) + { + m_Info = new List(); + + m_Info.Add(GetAssetId()); + m_Info.Add(GetString("Scene ID", m_Identity.sceneId.ToString())); + + if (!Application.isPlaying) + { + return; + } + + m_Info.Add(GetString("Network ID", m_Identity.netId.ToString())); + + m_Info.Add(GetString("Player Controller ID", m_Identity.playerControllerId.ToString())); + + m_Info.Add(GetBoolean("Is Client", m_Identity.isClient)); + m_Info.Add(GetBoolean("Is Server", m_Identity.isServer)); + m_Info.Add(GetBoolean("Has Authority", m_Identity.hasAuthority)); + m_Info.Add(GetBoolean("Is Local Player", m_Identity.isLocalPlayer)); + + NetworkBehaviour[] behaviours = gameObject.GetComponents(); + if (behaviours.Length > 0) + { + m_Behaviours = new List(); + foreach (var behaviour in behaviours) + { + NetworkBehaviourInfo info = new NetworkBehaviourInfo(); + info.name = new GUIContent(behaviour.GetType().FullName); + info.behaviour = behaviour; + m_Behaviours.Add(info); + } + } + } + } + + NetworkIdentityInfo GetAssetId() + { + string assetId = m_Identity.assetId.ToString(); + if (string.IsNullOrEmpty(assetId)) + { + assetId = ""; + } + return GetString("Asset ID", assetId); + } + + static NetworkIdentityInfo GetString(string name, string value) + { + NetworkIdentityInfo info = new NetworkIdentityInfo(); + info.name = new GUIContent(name); + info.value = new GUIContent(value); + return info; + } + + static NetworkIdentityInfo GetBoolean(string name, bool value) + { + NetworkIdentityInfo info = new NetworkIdentityInfo(); + info.name = new GUIContent(name); + info.value = new GUIContent((value ? "Yes" : "No")); + return info; + } + } +} +#pragma warning restore 618 +#endif //ENABLE_UNET diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkLobbyManagerEditor.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkLobbyManagerEditor.cs new file mode 100644 index 00000000..0643cc0d --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkLobbyManagerEditor.cs @@ -0,0 +1,257 @@ +#if ENABLE_UNET +using System; +using UnityEngine; +using UnityEngine.Networking; +using UnityObject = UnityEngine.Object; + +#pragma warning disable 618 +namespace UnityEditor +{ + [CustomEditor(typeof(NetworkLobbyManager), true)] + [CanEditMultipleObjects] + class NetworkLobbyManagerEditor : NetworkManagerEditor + { + SerializedProperty m_ShowLobbyGUIProperty; + SerializedProperty m_MaxPlayersProperty; + SerializedProperty m_MaxPlayersPerConnectionProperty; + SerializedProperty m_MinPlayersProperty; + SerializedProperty m_LobbyPlayerPrefabProperty; + SerializedProperty m_GamePlayerPrefabProperty; + + GUIContent m_LobbySceneLabel; + GUIContent m_PlaySceneLabel; + + GUIContent m_MaxPlayersLabel; + GUIContent m_MaxPlayersPerConnectionLabel; + GUIContent m_MinPlayersLabel; + + GUIContent m_ShowLobbyGUILabel; + GUIContent m_LobbyPlayerPrefabLabel; + GUIContent m_GamePlayerPrefabLabel; + + bool ShowSlots; + + void InitLobby() + { + if (!m_Initialized) + { + m_LobbySceneLabel = TextUtility.TextContent("Lobby Scene", "The scene loaded for the lobby."); + m_PlaySceneLabel = TextUtility.TextContent("Play Scene", "The scene loaded to play the game."); + + m_MaxPlayersLabel = TextUtility.TextContent("Max Players", "The maximum number of players allowed in the lobby."); + m_MaxPlayersPerConnectionLabel = TextUtility.TextContent("Max Players Per Connection", "The maximum number of players that each connection/client can have in the lobby. Defaults to 1."); + m_MinPlayersLabel = TextUtility.TextContent("Minimum Players", "The minimum number of players required to be ready for the game to start. If this is zero then the game can start with any number of players."); + + m_ShowLobbyGUILabel = TextUtility.TextContent("Show Lobby GUI", "Enable to display the default lobby UI."); + m_LobbyPlayerPrefabLabel = TextUtility.TextContent("Lobby Player Prefab", "The prefab to use for a player in the Lobby Scene."); + m_GamePlayerPrefabLabel = TextUtility.TextContent("Game Player Prefab", "The prefab to use for a player in the Play Scene."); + + m_ShowLobbyGUIProperty = serializedObject.FindProperty("m_ShowLobbyGUI"); + m_MaxPlayersProperty = serializedObject.FindProperty("m_MaxPlayers"); + m_MaxPlayersPerConnectionProperty = serializedObject.FindProperty("m_MaxPlayersPerConnection"); + m_MinPlayersProperty = serializedObject.FindProperty("m_MinPlayers"); + m_LobbyPlayerPrefabProperty = serializedObject.FindProperty("m_LobbyPlayerPrefab"); + m_GamePlayerPrefabProperty = serializedObject.FindProperty("m_GamePlayerPrefab"); + + var lobby = target as NetworkLobbyManager; + if (lobby == null) + return; + + if (lobby.lobbyScene != "") + { + var offlineObj = GetSceneObject(lobby.lobbyScene); + if (offlineObj == null) + { + Debug.LogWarning("LobbyScene '" + lobby.lobbyScene + "' not found. You must repopulate the LobbyScene slot of the NetworkLobbyManager"); + lobby.lobbyScene = ""; + } + } + + + if (lobby.playScene != "") + { + var onlineObj = GetSceneObject(lobby.playScene); + if (onlineObj == null) + { + Debug.LogWarning("PlayScene '" + lobby.playScene + "' not found. You must repopulate the PlayScene slot of the NetworkLobbyManager"); + lobby.playScene = ""; + } + } + } + + Init(); + } + + public override void OnInspectorGUI() + { + if (m_DontDestroyOnLoadProperty == null || m_DontDestroyOnLoadLabel == null) + m_Initialized = false; + + InitLobby(); + + var lobby = target as NetworkLobbyManager; + if (lobby == null) + return; + + serializedObject.Update(); + EditorGUILayout.PropertyField(m_DontDestroyOnLoadProperty, m_DontDestroyOnLoadLabel); + EditorGUILayout.PropertyField(m_RunInBackgroundProperty , m_RunInBackgroundLabel); + + if (EditorGUILayout.PropertyField(m_LogLevelProperty)) + { + LogFilter.currentLogLevel = (int)m_NetworkManager.logLevel; + } + + ShowLobbyScenes(); + + EditorGUILayout.PropertyField(m_ShowLobbyGUIProperty, m_ShowLobbyGUILabel); + EditorGUILayout.PropertyField(m_MaxPlayersProperty, m_MaxPlayersLabel); + EditorGUILayout.PropertyField(m_MaxPlayersPerConnectionProperty, m_MaxPlayersPerConnectionLabel); + EditorGUILayout.PropertyField(m_MinPlayersProperty, m_MinPlayersLabel); + EditorGUILayout.PropertyField(m_LobbyPlayerPrefabProperty, m_LobbyPlayerPrefabLabel); + + EditorGUI.BeginChangeCheck(); + var newGamPlayer = EditorGUILayout.ObjectField(m_GamePlayerPrefabLabel, lobby.gamePlayerPrefab, typeof(NetworkIdentity), false); + if (EditorGUI.EndChangeCheck()) + { + if (newGamPlayer == null) + { + m_GamePlayerPrefabProperty.objectReferenceValue = null; + } + else + { + var newGamePlayerIdentity = newGamPlayer as NetworkIdentity; + if (newGamePlayerIdentity != null) + { + if (newGamePlayerIdentity.gameObject != lobby.gamePlayerPrefab) + { + m_GamePlayerPrefabProperty.objectReferenceValue = newGamePlayerIdentity.gameObject; + } + } + } + } + + EditorGUILayout.Separator(); + + ShowNetworkInfo(); + ShowSpawnInfo(); + ShowConfigInfo(); + ShowSimulatorInfo(); + serializedObject.ApplyModifiedProperties(); + + ShowDerivedProperties(typeof(NetworkLobbyManager), typeof(NetworkManager)); + + if (!Application.isPlaying) + return; + + EditorGUILayout.Separator(); + ShowLobbySlots(); + } + + protected void ShowLobbySlots() + { + var lobby = target as NetworkLobbyManager; + if (lobby == null) + return; + + ShowSlots = EditorGUILayout.Foldout(ShowSlots, "LobbySlots"); + if (ShowSlots) + { + EditorGUI.indentLevel += 1; + foreach (var slot in lobby.lobbySlots) + { + if (slot == null) + continue; + + EditorGUILayout.ObjectField("Slot " + slot.slot, slot.gameObject, typeof(UnityObject), true); + } + EditorGUI.indentLevel -= 1; + } + } + + void SetLobbyScene(NetworkLobbyManager lobby, string sceneName) + { + var prop = serializedObject.FindProperty("m_LobbyScene"); + prop.stringValue = sceneName; + + var offlineProp = serializedObject.FindProperty("m_OfflineScene"); + offlineProp.stringValue = sceneName; + + EditorUtility.SetDirty(lobby); + } + + void SetPlayScene(NetworkLobbyManager lobby, string sceneName) + { + var prop = serializedObject.FindProperty("m_PlayScene"); + prop.stringValue = sceneName; + + var onlineProp = serializedObject.FindProperty("m_OnlineScene"); + onlineProp.stringValue = ""; // this is set to empty deliberately to prevent base class functionality from interfering with LobbyManager + + EditorUtility.SetDirty(lobby); + } + + protected void ShowLobbyScenes() + { + var lobby = target as NetworkLobbyManager; + if (lobby == null) + return; + + var offlineObj = GetSceneObject(lobby.lobbyScene); + + EditorGUI.BeginChangeCheck(); + var newOfflineScene = EditorGUILayout.ObjectField(m_LobbySceneLabel, offlineObj, typeof(SceneAsset), false); + if (EditorGUI.EndChangeCheck()) + { + if (newOfflineScene == null) + { + SetLobbyScene(lobby, ""); + } + else + { + if (newOfflineScene.name != lobby.offlineScene) + { + var sceneObj = GetSceneObject(newOfflineScene.name); + if (sceneObj == null) + { + Debug.LogWarning("The scene " + newOfflineScene.name + " cannot be used. To use this scene add it to the build settings for the project"); + } + else + { + SetLobbyScene(lobby, newOfflineScene.name); + } + } + } + } + + var onlineObj = GetSceneObject(lobby.playScene); + + EditorGUI.BeginChangeCheck(); + var newOnlineScene = EditorGUILayout.ObjectField(m_PlaySceneLabel, onlineObj, typeof(SceneAsset), false); + if (EditorGUI.EndChangeCheck()) + { + if (newOnlineScene == null) + { + SetPlayScene(lobby, ""); + } + else + { + if (newOnlineScene.name != m_NetworkManager.onlineScene) + { + var sceneObj = GetSceneObject(newOnlineScene.name); + if (sceneObj == null) + { + Debug.LogWarning("The scene " + newOnlineScene.name + " cannot be used. To use this scene add it to the build settings for the project"); + } + else + { + SetPlayScene(lobby, newOnlineScene.name); + } + } + } + } + } + } +} +#pragma warning restore 618 +#endif // ENABLE_UNET diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkManagerEditor.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkManagerEditor.cs new file mode 100644 index 00000000..95d650fb --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkManagerEditor.cs @@ -0,0 +1,641 @@ +#if ENABLE_UNET +using System; +using System.IO; +using System.Reflection; +using UnityEditorInternal; +using UnityEngine; +using UnityEngine.Networking; +using UnityObject = UnityEngine.Object; + +namespace UnityEditor +{ + [CustomEditor(typeof(NetworkManager), true)] + [CanEditMultipleObjects] + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class NetworkManagerEditor : Editor + { + protected SerializedProperty m_DontDestroyOnLoadProperty; + protected SerializedProperty m_RunInBackgroundProperty; + protected SerializedProperty m_ScriptCRCCheckProperty; + SerializedProperty m_NetworkAddressProperty; + + SerializedProperty m_NetworkPortProperty; + SerializedProperty m_ServerBindToIPProperty; + SerializedProperty m_ServerBindAddressProperty; + SerializedProperty m_MaxDelayProperty; + SerializedProperty m_MaxBufferedPacketsProperty; + SerializedProperty m_AllowFragmentationProperty; + + protected SerializedProperty m_LogLevelProperty; + SerializedProperty m_MatchHostProperty; + SerializedProperty m_MatchPortProperty; + SerializedProperty m_MatchNameProperty; + SerializedProperty m_MatchSizeProperty; + + SerializedProperty m_PlayerPrefabProperty; + SerializedProperty m_AutoCreatePlayerProperty; + SerializedProperty m_PlayerSpawnMethodProperty; + SerializedProperty m_SpawnListProperty; + + SerializedProperty m_CustomConfigProperty; + + SerializedProperty m_UseWebSocketsProperty; + SerializedProperty m_UseSimulatorProperty; + SerializedProperty m_SimulatedLatencyProperty; + SerializedProperty m_PacketLossPercentageProperty; + + SerializedProperty m_ChannelListProperty; + ReorderableList m_ChannelList; + + GUIContent m_ShowNetworkLabel; + GUIContent m_ShowSpawnLabel; + + GUIContent m_OfflineSceneLabel; + GUIContent m_OnlineSceneLabel; + protected GUIContent m_DontDestroyOnLoadLabel; + protected GUIContent m_RunInBackgroundLabel; + protected GUIContent m_ScriptCRCCheckLabel; + + GUIContent m_MaxConnectionsLabel; + GUIContent m_MinUpdateTimeoutLabel; + GUIContent m_ConnectTimeoutLabel; + GUIContent m_DisconnectTimeoutLabel; + GUIContent m_PingTimeoutLabel; + + GUIContent m_ThreadAwakeTimeoutLabel; + GUIContent m_ReactorModelLabel; + GUIContent m_ReactorMaximumReceivedMessagesLabel; + GUIContent m_ReactorMaximumSentMessagesLabel; + + GUIContent m_MaxBufferedPacketsLabel; + GUIContent m_AllowFragmentationLabel; + GUIContent m_UseWebSocketsLabel; + GUIContent m_UseSimulatorLabel; + GUIContent m_LatencyLabel; + GUIContent m_PacketLossPercentageLabel; + GUIContent m_MatchHostLabel; + GUIContent m_MatchPortLabel; + GUIContent m_MatchNameLabel; + GUIContent m_MatchSizeLabel; + + GUIContent m_NetworkAddressLabel; + GUIContent m_NetworkPortLabel; + GUIContent m_ServerBindToIPLabel; + GUIContent m_ServerBindAddressLabel; + GUIContent m_MaxDelayLabel; + + GUIContent m_PlayerPrefabLabel; + GUIContent m_AutoCreatePlayerLabel; + GUIContent m_PlayerSpawnMethodLabel; + + GUIContent m_AdvancedConfigurationLabel; + + ReorderableList m_SpawnList; + + protected bool m_Initialized; + + protected NetworkManager m_NetworkManager; + + protected void Init() + { + if (m_Initialized) + { + return; + } + m_Initialized = true; + m_NetworkManager = target as NetworkManager; + + m_ShowNetworkLabel = TextUtility.TextContent("Network Info", "Network host settings"); + m_ShowSpawnLabel = TextUtility.TextContent("Spawn Info", "Registered spawnable objects"); + m_OfflineSceneLabel = TextUtility.TextContent("Offline Scene", "The scene loaded when the network goes offline (disconnected from server)"); + m_OnlineSceneLabel = TextUtility.TextContent("Online Scene", "The scene loaded when the network comes online (connected to server)"); + m_DontDestroyOnLoadLabel = TextUtility.TextContent("Don't Destroy on Load", "Enable to persist the NetworkManager across scene changes."); + m_RunInBackgroundLabel = TextUtility.TextContent("Run in Background", "Enable to ensure that the application runs when it does not have focus.\n\nThis is required when testing multiple instances on a single machine, but not recommended for shipping on mobile platforms."); + m_ScriptCRCCheckLabel = TextUtility.TextContent("Script CRC Check", "Enable to cause a CRC check between server and client that ensures the NetworkBehaviour scripts match.\n\nThis may not be appropriate in some cases, such as when the client and server are different Unity projects."); + + m_MaxConnectionsLabel = TextUtility.TextContent("Max Connections", "Maximum number of network connections"); + m_MinUpdateTimeoutLabel = TextUtility.TextContent("Min Update Timeout", "Minimum time network thread waits for events"); + m_ConnectTimeoutLabel = TextUtility.TextContent("Connect Timeout", "Time to wait for timeout on connecting"); + m_DisconnectTimeoutLabel = TextUtility.TextContent("Disconnect Timeout", "Time to wait for detecting disconnect"); + m_PingTimeoutLabel = TextUtility.TextContent("Ping Timeout", "Time to wait for ping messages"); + + m_ThreadAwakeTimeoutLabel = TextUtility.TextContent("Thread Awake Timeout", "The minimum time period when system will check if there are any messages for send (or receive)."); + m_ReactorModelLabel = TextUtility.TextContent("Reactor Model", "Defines reactor model for the network library"); + m_ReactorMaximumReceivedMessagesLabel = TextUtility.TextContent("Reactor Max Recv Messages", "Defines maximum amount of messages in the receive queue"); + m_ReactorMaximumSentMessagesLabel = TextUtility.TextContent("Reactor Max Sent Messages", "Defines maximum message count in sent queue"); + + m_MaxBufferedPacketsLabel = TextUtility.TextContent("Max Buffered Packets", "The maximum number of packets that can be buffered by a NetworkConnection for each channel. This corresponds to the 'ChannelOption.MaxPendingBuffers' channel option."); + m_AllowFragmentationLabel = TextUtility.TextContent("Packet Fragmentation", "Enable to allow NetworkConnection instances to fragment packets that are larger than the maxPacketSize, up to a maximum size of 64K.\n\nThis can cause delays when sending large packets."); + m_UseWebSocketsLabel = TextUtility.TextContent("Use WebSockets", "This makes the server listen for connections using WebSockets. This allows WebGL clients to connect to the server."); + m_UseSimulatorLabel = TextUtility.TextContent("Use Network Simulator", "This simulates network latency and packet loss on clients. Useful for testing under internet-like conditions"); + m_LatencyLabel = TextUtility.TextContent("Simulated Average Latency", "The amount of delay in milliseconds to add to network packets"); + m_PacketLossPercentageLabel = TextUtility.TextContent("Simulated Packet Loss", "The percentage of packets that should be dropped"); + m_MatchHostLabel = TextUtility.TextContent("MatchMaker Host URI", "The hostname of the matchmaking server.\n\nThe default is mm.unet.unity3d.com, which will connect a client to the nearest data center geographically."); + m_MatchPortLabel = TextUtility.TextContent("MatchMaker Port", "The port of the matchmaking service."); + m_MatchNameLabel = TextUtility.TextContent("Match Name", "The name that will be used when creating a match in MatchMaker."); + m_MatchSizeLabel = TextUtility.TextContent("Maximum Match Size", "The maximum size for the match. This value is compared to the maximum size specified in the service configuration at multiplayer.unity3d.com and the lower of the two is enforced. It must be greater than 1. This is typically used to override the match size for various game modes."); + m_NetworkAddressLabel = TextUtility.TextContent("Network Address", "The network address currently in use."); + m_NetworkPortLabel = TextUtility.TextContent("Network Port", "The network port currently in use."); + m_ServerBindToIPLabel = TextUtility.TextContent("Server Bind to IP", "Enable to bind the server to a specific IP address."); + m_ServerBindAddressLabel = TextUtility.TextContent("Server Bind Address Label", "IP to bind the server to, when Server Bind to IP is enabled."); + m_MaxDelayLabel = TextUtility.TextContent("Max Delay", "The maximum delay before sending packets on connections."); + m_PlayerPrefabLabel = TextUtility.TextContent("Player Prefab", "The default prefab to be used to create player objects on the server."); + m_AutoCreatePlayerLabel = TextUtility.TextContent("Auto Create Player", "Enable to automatically create player objects on connect and on Scene change."); + m_PlayerSpawnMethodLabel = TextUtility.TextContent("Player Spawn Method", "How to determine which NetworkStartPosition to spawn players at, from all NetworkStartPositions in the Scene.\n\nRandom chooses a random NetworkStartPosition.\n\nRound Robin chooses the next NetworkStartPosition on a round-robin basis."); + m_AdvancedConfigurationLabel = TextUtility.TextContent("Advanced Configuration", "Enable to view and edit advanced settings."); + + // top-level properties + m_DontDestroyOnLoadProperty = serializedObject.FindProperty("m_DontDestroyOnLoad"); + m_RunInBackgroundProperty = serializedObject.FindProperty("m_RunInBackground"); + m_ScriptCRCCheckProperty = serializedObject.FindProperty("m_ScriptCRCCheck"); + m_LogLevelProperty = serializedObject.FindProperty("m_LogLevel"); + + // network foldout properties + m_NetworkAddressProperty = serializedObject.FindProperty("m_NetworkAddress"); + m_NetworkPortProperty = serializedObject.FindProperty("m_NetworkPort"); + m_ServerBindToIPProperty = serializedObject.FindProperty("m_ServerBindToIP"); + m_ServerBindAddressProperty = serializedObject.FindProperty("m_ServerBindAddress"); + m_MaxDelayProperty = serializedObject.FindProperty("m_MaxDelay"); + m_MaxBufferedPacketsProperty = serializedObject.FindProperty("m_MaxBufferedPackets"); + m_AllowFragmentationProperty = serializedObject.FindProperty("m_AllowFragmentation"); + m_MatchHostProperty = serializedObject.FindProperty("m_MatchHost"); + m_MatchPortProperty = serializedObject.FindProperty("m_MatchPort"); + m_MatchNameProperty = serializedObject.FindProperty("matchName"); + m_MatchSizeProperty = serializedObject.FindProperty("matchSize"); + + // spawn foldout properties + m_PlayerPrefabProperty = serializedObject.FindProperty("m_PlayerPrefab"); + m_AutoCreatePlayerProperty = serializedObject.FindProperty("m_AutoCreatePlayer"); + m_PlayerSpawnMethodProperty = serializedObject.FindProperty("m_PlayerSpawnMethod"); + m_SpawnListProperty = serializedObject.FindProperty("m_SpawnPrefabs"); + + m_SpawnList = new ReorderableList(serializedObject, m_SpawnListProperty); + m_SpawnList.drawHeaderCallback = DrawHeader; + m_SpawnList.drawElementCallback = DrawChild; + m_SpawnList.onReorderCallback = Changed; + m_SpawnList.onRemoveCallback = RemoveButton; + m_SpawnList.onChangedCallback = Changed; + m_SpawnList.onReorderCallback = Changed; + m_SpawnList.onAddCallback = AddButton; + m_SpawnList.elementHeight = 16; // this uses a 16x16 icon. other sizes make it stretch. + + // network configuration + m_CustomConfigProperty = serializedObject.FindProperty("m_CustomConfig"); + m_ChannelListProperty = serializedObject.FindProperty("m_Channels"); + m_ChannelList = new ReorderableList(serializedObject, m_ChannelListProperty); + m_ChannelList.drawHeaderCallback = ChannelDrawHeader; + m_ChannelList.drawElementCallback = ChannelDrawChild; + m_ChannelList.onReorderCallback = ChannelChanged; + m_ChannelList.onAddDropdownCallback = ChannelAddButton; + m_ChannelList.onRemoveCallback = ChannelRemoveButton; + m_ChannelList.onChangedCallback = ChannelChanged; + m_ChannelList.onReorderCallback = ChannelChanged; + m_ChannelList.onAddCallback = ChannelChanged; + + // Network Simulator + m_UseWebSocketsProperty = serializedObject.FindProperty("m_UseWebSockets"); + m_UseSimulatorProperty = serializedObject.FindProperty("m_UseSimulator"); + m_SimulatedLatencyProperty = serializedObject.FindProperty("m_SimulatedLatency"); + m_PacketLossPercentageProperty = serializedObject.FindProperty("m_PacketLossPercentage"); + } + + static void ShowPropertySuffix(GUIContent content, SerializedProperty prop, string suffix) + { + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.PropertyField(prop, content); + GUILayout.Label(suffix, EditorStyles.miniLabel, GUILayout.Width(64)); + EditorGUILayout.EndHorizontal(); + } + + protected void ShowSimulatorInfo() + { + EditorGUILayout.PropertyField(m_UseSimulatorProperty, m_UseSimulatorLabel); + + if (m_UseSimulatorProperty.boolValue) + { + EditorGUI.indentLevel += 1; + + if (Application.isPlaying && m_NetworkManager.client != null) + { + // read only at runtime + EditorGUILayout.LabelField(m_LatencyLabel, new GUIContent(m_NetworkManager.simulatedLatency + " milliseconds")); + EditorGUILayout.LabelField(m_PacketLossPercentageLabel, new GUIContent(m_NetworkManager.packetLossPercentage + "%")); + } + else + { + // Latency + int oldLatency = m_NetworkManager.simulatedLatency; + EditorGUILayout.BeginHorizontal(); + int newLatency = EditorGUILayout.IntSlider(m_LatencyLabel, oldLatency, 1, 400); + GUILayout.Label("millsec", EditorStyles.miniLabel, GUILayout.Width(64)); + EditorGUILayout.EndHorizontal(); + if (newLatency != oldLatency) + { + m_SimulatedLatencyProperty.intValue = newLatency; + } + + // Packet Loss + float oldPacketLoss = m_NetworkManager.packetLossPercentage; + EditorGUILayout.BeginHorizontal(); + float newPacketLoss = EditorGUILayout.Slider(m_PacketLossPercentageLabel, oldPacketLoss, 0f, 20f); + GUILayout.Label("%", EditorStyles.miniLabel, GUILayout.Width(64)); + EditorGUILayout.EndHorizontal(); + if (newPacketLoss != oldPacketLoss) + { + m_PacketLossPercentageProperty.floatValue = newPacketLoss; + } + } + + EditorGUI.indentLevel -= 1; + } + } + + protected void ShowConfigInfo() + { + bool oldCustomConfig = m_NetworkManager.customConfig; + EditorGUILayout.PropertyField(m_CustomConfigProperty, m_AdvancedConfigurationLabel); + + // Populate default channels first time a custom config is created. + if (m_CustomConfigProperty.boolValue) + { + if (!oldCustomConfig) + { + if (m_NetworkManager.channels.Count == 0) + { + m_NetworkManager.channels.Add(QosType.ReliableSequenced); + m_NetworkManager.channels.Add(QosType.Unreliable); + m_NetworkManager.customConfig = true; + m_CustomConfigProperty.serializedObject.Update(); + m_ChannelList.serializedProperty.serializedObject.Update(); + } + } + } + + if (m_NetworkManager.customConfig) + { + EditorGUI.indentLevel += 1; + var maxConn = serializedObject.FindProperty("m_MaxConnections"); + ShowPropertySuffix(m_MaxConnectionsLabel, maxConn, "connections"); + + m_ChannelList.DoLayoutList(); + + maxConn.isExpanded = EditorGUILayout.Foldout(maxConn.isExpanded, "Timeouts"); + if (maxConn.isExpanded) + { + EditorGUI.indentLevel += 1; + var minUpdateTimeout = serializedObject.FindProperty("m_ConnectionConfig.m_MinUpdateTimeout"); + var connectTimeout = serializedObject.FindProperty("m_ConnectionConfig.m_ConnectTimeout"); + var disconnectTimeout = serializedObject.FindProperty("m_ConnectionConfig.m_DisconnectTimeout"); + var pingTimeout = serializedObject.FindProperty("m_ConnectionConfig.m_PingTimeout"); + + ShowPropertySuffix(m_MinUpdateTimeoutLabel, minUpdateTimeout, "millisec"); + ShowPropertySuffix(m_ConnectTimeoutLabel, connectTimeout, "millisec"); + ShowPropertySuffix(m_DisconnectTimeoutLabel, disconnectTimeout, "millisec"); + ShowPropertySuffix(m_PingTimeoutLabel, pingTimeout, "millisec"); + EditorGUI.indentLevel -= 1; + } + + var threadAwakeTimeout = serializedObject.FindProperty("m_GlobalConfig.m_ThreadAwakeTimeout"); + threadAwakeTimeout.isExpanded = EditorGUILayout.Foldout(threadAwakeTimeout.isExpanded, "Global Config"); + if (threadAwakeTimeout.isExpanded) + { + EditorGUI.indentLevel += 1; + var reactorModel = serializedObject.FindProperty("m_GlobalConfig.m_ReactorModel"); + var reactorMaximumReceivedMessages = serializedObject.FindProperty("m_GlobalConfig.m_ReactorMaximumReceivedMessages"); + var reactorMaximumSentMessages = serializedObject.FindProperty("m_GlobalConfig.m_ReactorMaximumSentMessages"); + + ShowPropertySuffix(m_ThreadAwakeTimeoutLabel, threadAwakeTimeout, "millisec"); + EditorGUILayout.PropertyField(reactorModel, m_ReactorModelLabel); + ShowPropertySuffix(m_ReactorMaximumReceivedMessagesLabel, reactorMaximumReceivedMessages, "messages"); + ShowPropertySuffix(m_ReactorMaximumSentMessagesLabel, reactorMaximumSentMessages, "messages"); + EditorGUI.indentLevel -= 1; + } + + EditorGUI.indentLevel -= 1; + } + } + + protected void ShowSpawnInfo() + { + m_PlayerPrefabProperty.isExpanded = EditorGUILayout.Foldout(m_PlayerPrefabProperty.isExpanded, m_ShowSpawnLabel); + if (!m_PlayerPrefabProperty.isExpanded) + { + return; + } + + EditorGUI.indentLevel += 1; + + //The NetworkLobbyManager doesnt use playerPrefab, it has its own player prefab slots, so dont show this + if (!typeof(NetworkLobbyManager).IsAssignableFrom(m_NetworkManager.GetType())) + { + EditorGUILayout.PropertyField(m_PlayerPrefabProperty, m_PlayerPrefabLabel); + } + + EditorGUILayout.PropertyField(m_AutoCreatePlayerProperty, m_AutoCreatePlayerLabel); + EditorGUILayout.PropertyField(m_PlayerSpawnMethodProperty, m_PlayerSpawnMethodLabel); + + + EditorGUI.BeginChangeCheck(); + m_SpawnList.DoLayoutList(); + if (EditorGUI.EndChangeCheck()) + { + serializedObject.ApplyModifiedProperties(); + } + + EditorGUI.indentLevel -= 1; + } + + protected SceneAsset GetSceneObject(string sceneObjectName) + { + if (string.IsNullOrEmpty(sceneObjectName)) + { + return null; + } + + foreach (var editorScene in EditorBuildSettings.scenes) + { + var sceneNameWithoutExtension = Path.GetFileNameWithoutExtension(editorScene.path); + if (sceneNameWithoutExtension == sceneObjectName) + { + return AssetDatabase.LoadAssetAtPath(editorScene.path, typeof(SceneAsset)) as SceneAsset; + } + } + if (LogFilter.logWarn) { Debug.LogWarning("Scene [" + sceneObjectName + "] cannot be used with networking. Add this scene to the 'Scenes in the Build' in build settings."); } + return null; + } + + protected void ShowNetworkInfo() + { + m_NetworkAddressProperty.isExpanded = EditorGUILayout.Foldout(m_NetworkAddressProperty.isExpanded, m_ShowNetworkLabel); + if (!m_NetworkAddressProperty.isExpanded) + { + return; + } + EditorGUI.indentLevel += 1; + + if (EditorGUILayout.PropertyField(m_UseWebSocketsProperty, m_UseWebSocketsLabel)) + { + NetworkServer.useWebSockets = m_NetworkManager.useWebSockets; + } + + EditorGUILayout.PropertyField(m_NetworkAddressProperty, m_NetworkAddressLabel); + EditorGUILayout.PropertyField(m_NetworkPortProperty, m_NetworkPortLabel); + EditorGUILayout.PropertyField(m_ServerBindToIPProperty, m_ServerBindToIPLabel); + if (m_NetworkManager.serverBindToIP) + { + EditorGUI.indentLevel += 1; + EditorGUILayout.PropertyField(m_ServerBindAddressProperty, m_ServerBindAddressLabel); + EditorGUI.indentLevel -= 1; + } + EditorGUILayout.PropertyField(m_ScriptCRCCheckProperty, m_ScriptCRCCheckLabel); + EditorGUILayout.PropertyField(m_MaxDelayProperty, m_MaxDelayLabel); + EditorGUILayout.PropertyField(m_MaxBufferedPacketsProperty, m_MaxBufferedPacketsLabel); + EditorGUILayout.PropertyField(m_AllowFragmentationProperty, m_AllowFragmentationLabel); + EditorGUILayout.PropertyField(m_MatchHostProperty, m_MatchHostLabel); + EditorGUILayout.PropertyField(m_MatchPortProperty, m_MatchPortLabel); + EditorGUILayout.PropertyField(m_MatchNameProperty, m_MatchNameLabel); + EditorGUILayout.PropertyField(m_MatchSizeProperty, m_MatchSizeLabel); + + EditorGUI.indentLevel -= 1; + } + + protected void ShowScenes() + { + var offlineObj = GetSceneObject(m_NetworkManager.offlineScene); + var newOfflineScene = EditorGUILayout.ObjectField(m_OfflineSceneLabel, offlineObj, typeof(SceneAsset), false); + if (newOfflineScene == null) + { + var prop = serializedObject.FindProperty("m_OfflineScene"); + prop.stringValue = ""; + EditorUtility.SetDirty(target); + } + else + { + if (newOfflineScene.name != m_NetworkManager.offlineScene) + { + var sceneObj = GetSceneObject(newOfflineScene.name); + if (sceneObj == null) + { + Debug.LogWarning("The scene " + newOfflineScene.name + " cannot be used. To use this scene add it to the build settings for the project"); + } + else + { + var prop = serializedObject.FindProperty("m_OfflineScene"); + prop.stringValue = newOfflineScene.name; + EditorUtility.SetDirty(target); + } + } + } + + var onlineObj = GetSceneObject(m_NetworkManager.onlineScene); + var newOnlineScene = EditorGUILayout.ObjectField(m_OnlineSceneLabel, onlineObj, typeof(SceneAsset), false); + if (newOnlineScene == null) + { + var prop = serializedObject.FindProperty("m_OnlineScene"); + prop.stringValue = ""; + EditorUtility.SetDirty(target); + } + else + { + if (newOnlineScene.name != m_NetworkManager.onlineScene) + { + var sceneObj = GetSceneObject(newOnlineScene.name); + if (sceneObj == null) + { + Debug.LogWarning("The scene " + newOnlineScene.name + " cannot be used. To use this scene add it to the build settings for the project"); + } + else + { + var prop = serializedObject.FindProperty("m_OnlineScene"); + prop.stringValue = newOnlineScene.name; + EditorUtility.SetDirty(target); + } + } + } + } + + protected void ShowDerivedProperties(Type baseType, Type superType) + { + bool first = true; + + SerializedProperty property = serializedObject.GetIterator(); + bool expanded = true; + while (property.NextVisible(expanded)) + { + // ignore properties from base class. + var f = baseType.GetField(property.name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + var p = baseType.GetProperty(property.name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + + if (f == null && superType != null) + { + f = superType.GetField(property.name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + } + + if (p == null && superType != null) + { + p = superType.GetProperty(property.name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + } + + if (f == null && p == null) + { + if (first) + { + first = false; + EditorGUI.BeginChangeCheck(); + serializedObject.Update(); + + EditorGUILayout.Separator(); + } + EditorGUILayout.PropertyField(property, true); + expanded = false; + } + } + if (!first) + { + serializedObject.ApplyModifiedProperties(); + EditorGUI.EndChangeCheck(); + } + } + + public override void OnInspectorGUI() + { + if (m_DontDestroyOnLoadProperty == null || m_DontDestroyOnLoadLabel == null) + m_Initialized = false; + + Init(); + + serializedObject.Update(); + EditorGUILayout.PropertyField(m_DontDestroyOnLoadProperty, m_DontDestroyOnLoadLabel); + EditorGUILayout.PropertyField(m_RunInBackgroundProperty , m_RunInBackgroundLabel); + + if (EditorGUILayout.PropertyField(m_LogLevelProperty)) + { + LogFilter.currentLogLevel = (int)m_NetworkManager.logLevel; + } + + ShowScenes(); + ShowNetworkInfo(); + ShowSpawnInfo(); + ShowConfigInfo(); + ShowSimulatorInfo(); + serializedObject.ApplyModifiedProperties(); + + ShowDerivedProperties(typeof(NetworkManager), null); + } + + static void DrawHeader(Rect headerRect) + { + GUI.Label(headerRect, "Registered Spawnable Prefabs:"); + } + + internal void DrawChild(Rect r, int index, bool isActive, bool isFocused) + { + SerializedProperty prefab = m_SpawnListProperty.GetArrayElementAtIndex(index); + GameObject go = (GameObject)prefab.objectReferenceValue; + + GUIContent label; + if (go == null) + { + label = TextUtility.TextContent("Empty", "Drag a prefab with a NetworkIdentity here"); + } + else + { + var uv = go.GetComponent(); + if (uv != null) + { + label = new GUIContent(go.name, "AssetId: [" + uv.assetId + "]"); + } + else + { + label = new GUIContent(go.name, "No Network Identity"); + } + } + + var newGameObject = (GameObject)EditorGUI.ObjectField(r, label, go, typeof(GameObject), false); + + if (newGameObject != go) + { + if (newGameObject != null && !newGameObject.GetComponent()) + { + if (LogFilter.logError) { Debug.LogError("Prefab " + newGameObject + " cannot be added as spawnable as it doesn't have a NetworkIdentity."); } + return; + } + prefab.objectReferenceValue = newGameObject; + } + } + + internal void Changed(ReorderableList list) + { + EditorUtility.SetDirty(target); + } + + internal void AddButton(ReorderableList list) + { + m_SpawnListProperty.arraySize += 1; + list.index = m_SpawnListProperty.arraySize - 1; + + var obj = m_SpawnListProperty.GetArrayElementAtIndex(m_SpawnListProperty.arraySize - 1); + if (obj.objectReferenceValue != null) + obj.objectReferenceValue = null; + + m_SpawnList.index = m_SpawnList.count - 1; + + Changed(list); + } + + internal void RemoveButton(ReorderableList list) + { + m_SpawnListProperty.DeleteArrayElementAtIndex(m_SpawnList.index); + if (list.index >= m_SpawnListProperty.arraySize) + { + list.index = m_SpawnListProperty.arraySize - 1; + } + } + + // List widget functions + + static void ChannelDrawHeader(Rect headerRect) + { + GUI.Label(headerRect, "Qos Channels:"); + } + + internal void ChannelDrawChild(Rect r, int index, bool isActive, bool isFocused) + { + QosType qos = (QosType)m_ChannelListProperty.GetArrayElementAtIndex(index).enumValueIndex; + QosType newValue = (QosType)EditorGUI.EnumPopup(r, "Channel #" + index, qos); + if (newValue != qos) + { + var obj = m_ChannelListProperty.GetArrayElementAtIndex(index); + obj.enumValueIndex = (int)newValue; + } + } + + internal void ChannelChanged(ReorderableList list) + { + EditorUtility.SetDirty(target); + } + + internal void ChannelAddButton(Rect rect, ReorderableList list) + { + m_ChannelListProperty.arraySize += 1; + var obj = m_ChannelListProperty.GetArrayElementAtIndex(m_ChannelListProperty.arraySize - 1); + obj.enumValueIndex = (int)QosType.ReliableSequenced; + list.index = m_ChannelListProperty.arraySize - 1; + } + + internal void ChannelRemoveButton(ReorderableList list) + { + if (m_NetworkManager.channels.Count == 1) + { + if (LogFilter.logError) { Debug.LogError("Cannot remove channel. There must be at least one QoS channel."); } + return; + } + m_ChannelListProperty.DeleteArrayElementAtIndex(m_ChannelList.index); + if (list.index >= m_ChannelListProperty.arraySize - 1) + { + list.index = m_ChannelListProperty.arraySize - 1; + } + } + } +} +#endif //ENABLE_UNET diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkManagerHUDEditor.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkManagerHUDEditor.cs new file mode 100644 index 00000000..874a0883 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkManagerHUDEditor.cs @@ -0,0 +1,471 @@ +#if ENABLE_UNET +using System; +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.Networking; +using UnityObject = UnityEngine.Object; + +namespace UnityEditor +{ + [CustomEditor(typeof(NetworkManagerHUD), true)] + [CanEditMultipleObjects] + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class NetworkManagerHUDEditor : Editor + { + SerializedProperty m_ShowGUIProperty; + SerializedProperty m_OffsetXProperty; + SerializedProperty m_OffsetYProperty; + + protected GUIContent m_ShowNetworkLabel; + protected GUIContent m_ShowServerLabel; + protected GUIContent m_ShowServerConnectionsLabel; + protected GUIContent m_ShowServerObjectsLabel; + protected GUIContent m_ShowClientLabel; + protected GUIContent m_ShowClientObjectsLabel; + protected GUIContent m_ShowMatchMakerLabel; + protected GUIContent m_ShowControlsLabel; + protected GUIContent m_ShowRuntimeGuiLabel; + protected GUIContent m_OffsetXLabel; + protected GUIContent m_OffsetYLabel; + + bool m_ShowServer; + bool m_ShowServerConnections; + bool m_ShowServerObjects; + bool m_ShowClient; + bool m_ShowClientObjects; + bool m_ShowMatchMaker; + + bool m_ShowControls; + + bool m_Initialized; + + + NetworkManagerHUD m_ManagerHud; + NetworkManager m_Manager; + + void Init() + { + if (m_Initialized) + { + if (m_ShowGUIProperty == null) + { + // initialize again.. something got broken + } + else + { + return; + } + } + m_Initialized = true; + m_ManagerHud = target as NetworkManagerHUD; + if (m_ManagerHud != null) + { + m_Manager = m_ManagerHud.manager; + } + + m_ShowGUIProperty = serializedObject.FindProperty("showGUI"); + m_OffsetXProperty = serializedObject.FindProperty("offsetX"); + m_OffsetYProperty = serializedObject.FindProperty("offsetY"); + + m_ShowServerLabel = TextUtility.TextContent("Server Info", "Details of internal server state"); + m_ShowServerConnectionsLabel = TextUtility.TextContent("Server Connections", "List of local and remote network connections to the server"); + m_ShowServerObjectsLabel = TextUtility.TextContent("Server Objects", "Networked objects spawned by the server"); + m_ShowClientLabel = TextUtility.TextContent("Client Info", "Details of internal client state"); + m_ShowClientObjectsLabel = TextUtility.TextContent("Client Objects", "Networked objects created on the client"); + m_ShowMatchMakerLabel = TextUtility.TextContent("MatchMaker Info", "Details about the matchmaker state"); + m_ShowControlsLabel = TextUtility.TextContent("Runtime Controls", "Buttons for controlling network state at runtime"); + m_ShowRuntimeGuiLabel = TextUtility.TextContent("Show Runtime GUI", "Show the default network control GUI when the game is running"); + m_OffsetXLabel = TextUtility.TextContent("GUI Horizontal Offset", "Horizontal offset of runtime GUI"); + m_OffsetYLabel = TextUtility.TextContent("GUI Vertical Offset", "Vertical offset of runtime GUI"); + } + + List m_ShowDetailForConnections; + List m_ShowPlayersForConnections; + List m_ShowVisibleForConnections; + List m_ShowOwnedForConnections; + + void ShowServerConnections() + { + m_ShowServerConnections = EditorGUILayout.Foldout(m_ShowServerConnections, m_ShowServerConnectionsLabel); + if (m_ShowServerConnections) + { + EditorGUI.indentLevel += 1; + + // ensure arrays of bools exists and are large enough + if (m_ShowDetailForConnections == null) + { + m_ShowDetailForConnections = new List(); + m_ShowPlayersForConnections = new List(); + m_ShowVisibleForConnections = new List(); + m_ShowOwnedForConnections = new List(); + } + while (m_ShowDetailForConnections.Count < NetworkServer.connections.Count) + { + m_ShowDetailForConnections.Add(false); + m_ShowPlayersForConnections.Add(false); + m_ShowVisibleForConnections.Add(false); + m_ShowOwnedForConnections.Add(false); + } + + // all connections + int index = 0; + foreach (var con in NetworkServer.connections) + { + if (con == null) + { + index += 1; + continue; + } + + m_ShowDetailForConnections[index] = EditorGUILayout.Foldout(m_ShowDetailForConnections[index], "Conn: " + con.connectionId + " (" + con.address + ")"); + if (m_ShowDetailForConnections[index]) + { + EditorGUI.indentLevel += 1; + + m_ShowPlayersForConnections[index] = EditorGUILayout.Foldout(m_ShowPlayersForConnections[index], "Players"); + if (m_ShowPlayersForConnections[index]) + { + EditorGUI.indentLevel += 1; + foreach (var player in con.playerControllers) + { + EditorGUILayout.ObjectField("Player: " + player.playerControllerId, player.gameObject, typeof(GameObject), true); + } + EditorGUI.indentLevel -= 1; + } + + m_ShowVisibleForConnections[index] = EditorGUILayout.Foldout(m_ShowVisibleForConnections[index], "Visible Objects"); + if (m_ShowVisibleForConnections[index]) + { + EditorGUI.indentLevel += 1; + foreach (var v in con.visList) + { + EditorGUILayout.ObjectField("NetId: " + v.netId, v, typeof(NetworkIdentity), true); + } + EditorGUI.indentLevel -= 1; + } + + if (con.clientOwnedObjects != null) + { + m_ShowOwnedForConnections[index] = EditorGUILayout.Foldout(m_ShowOwnedForConnections[index], "Owned Objects"); + if (m_ShowOwnedForConnections[index]) + { + EditorGUI.indentLevel += 1; + foreach (var netId in con.clientOwnedObjects) + { + var obj = NetworkServer.FindLocalObject(netId); + EditorGUILayout.ObjectField("Owned: " + netId, obj, typeof(NetworkIdentity), true); + } + EditorGUI.indentLevel -= 1; + } + } + EditorGUI.indentLevel -= 1; + } + index += 1; + } + EditorGUI.indentLevel -= 1; + } + } + + void ShowServerObjects() + { + m_ShowServerObjects = EditorGUILayout.Foldout(m_ShowServerObjects, m_ShowServerObjectsLabel); + if (m_ShowServerObjects) + { + EditorGUI.indentLevel += 1; + + foreach (var obj in NetworkServer.objects) + { + string first = "NetId:" + obj.Key; + GameObject value = null; + if (obj.Value != null) + { + NetworkIdentity uv = obj.Value.GetComponent(); + first += " SceneId:" + uv.sceneId; + value = obj.Value.gameObject; + } + EditorGUILayout.ObjectField(first, value, typeof(GameObject), true); + } + EditorGUI.indentLevel -= 1; + } + } + + void ShowServerInfo() + { + if (!NetworkServer.active) + { + return; + } + + m_ShowServer = EditorGUILayout.Foldout(m_ShowServer, m_ShowServerLabel); + if (!m_ShowServer) + { + return; + } + + EditorGUI.indentLevel += 1; + EditorGUILayout.BeginVertical(); + ShowServerConnections(); + ShowServerObjects(); + EditorGUILayout.EndVertical(); + EditorGUI.indentLevel -= 1; + } + + void ShowClientObjects() + { + m_ShowClientObjects = EditorGUILayout.Foldout(m_ShowClientObjects, m_ShowClientObjectsLabel); + if (m_ShowClientObjects) + { + EditorGUI.indentLevel += 1; + foreach (var obj in ClientScene.objects) + { + string first = "NetId:" + obj.Key; + GameObject value = null; + if (obj.Value != null) + { + NetworkIdentity id = obj.Value.GetComponent(); + first += " SceneId:" + id.sceneId; + value = obj.Value.gameObject; + } + EditorGUILayout.ObjectField(first, value, typeof(GameObject), true); + } + EditorGUI.indentLevel -= 1; + } + } + + void ShowClientInfo() + { + if (!NetworkClient.active) + { + return; + } + + m_ShowClient = EditorGUILayout.Foldout(m_ShowClient, m_ShowClientLabel); + if (!m_ShowClient) + { + return; + } + + EditorGUI.indentLevel += 1; + EditorGUILayout.BeginVertical(); + + int count = 0; + foreach (var cl in NetworkClient.allClients) + { + if (cl.connection == null) + { + EditorGUILayout.TextField("client " + count + ": ", cl.GetType().Name + " Conn: null"); + } + else + { + EditorGUILayout.TextField("client " + count + ":" , cl.GetType().Name + " Conn: " + cl.connection); + EditorGUI.indentLevel += 1; + foreach (var p in cl.connection.playerControllers) + { + EditorGUILayout.LabelField("Player", p.ToString()); + } + EditorGUI.indentLevel -= 1; + } + count++; + } + + ShowClientObjects(); + EditorGUILayout.EndVertical(); + EditorGUI.indentLevel -= 1; + } + + void ShowMatchMakerInfo() + { + if (m_Manager == null || m_Manager.matchMaker == null) + { + return; + } + + m_ShowMatchMaker = EditorGUILayout.Foldout(m_ShowMatchMaker, m_ShowMatchMakerLabel); + if (!m_ShowMatchMaker) + { + return; + } + + EditorGUI.indentLevel += 1; + EditorGUILayout.BeginVertical(); + + EditorGUILayout.LabelField("Match Information", m_Manager.matchInfo == null ? "None" : m_Manager.matchInfo.ToString()); + + EditorGUILayout.EndVertical(); + EditorGUI.indentLevel -= 1; + } + + static UnityObject GetSceneObject(string sceneObjectName) + { + if (string.IsNullOrEmpty(sceneObjectName)) + { + return null; + } + + foreach (var editorScene in EditorBuildSettings.scenes) + { + if (editorScene.path.IndexOf(sceneObjectName) != -1) + { + return AssetDatabase.LoadAssetAtPath(editorScene.path, typeof(UnityObject)); + } + } + return null; + } + + static Rect GetButtonRect() + { + Rect rect = EditorGUILayout.GetControlRect(); + float endcap = rect.width / 6; + Rect newRect = new Rect(rect.xMin + endcap, rect.yMin, rect.width - (endcap * 2), rect.height); + return newRect; + } + + void ShowControls() + { + m_ShowControls = EditorGUILayout.Foldout(m_ShowControls, m_ShowControlsLabel); + if (!m_ShowControls) + { + return; + } + + if (!string.IsNullOrEmpty(NetworkManager.networkSceneName)) + { + EditorGUILayout.ObjectField("Current Scene:", GetSceneObject(NetworkManager.networkSceneName), typeof(UnityObject), true); + } + EditorGUILayout.Separator(); + + if (!NetworkClient.active && !NetworkServer.active && m_Manager.matchMaker == null) + { + EditorGUILayout.BeginHorizontal(); + if (GUILayout.Toggle(false, "LAN Host", EditorStyles.miniButton)) + { + m_Manager.StartHost(); + } + if (GUILayout.Toggle(false, "LAN Server", EditorStyles.miniButton)) + { + m_Manager.StartServer(); + } + if (GUILayout.Toggle(false, "LAN Client", EditorStyles.miniButton)) + { + m_Manager.StartClient(); + } + if (GUILayout.Toggle(false, "Start Matchmaker", EditorStyles.miniButton)) + { + m_Manager.StartMatchMaker(); + m_ShowMatchMaker = true; + } + EditorGUILayout.EndHorizontal(); + } + + if (NetworkClient.active && !ClientScene.ready) + { + if (GUI.Button(GetButtonRect(), "Client Ready")) + { + ClientScene.Ready(m_Manager.client.connection); + + if (ClientScene.localPlayers.Count == 0) + { + ClientScene.AddPlayer(0); + } + } + } + + if (NetworkServer.active || NetworkClient.active) + { + if (GUI.Button(GetButtonRect(), "Stop")) + { + m_Manager.StopServer(); + m_Manager.StopClient(); + } + } + if (!NetworkServer.active && !NetworkClient.active) + { + EditorGUILayout.Separator(); + if (m_Manager.matchMaker != null) + { + if (m_Manager.matchInfo == null) + { + if (m_Manager.matches == null) + { + EditorGUILayout.BeginHorizontal(); + if (GUILayout.Toggle(false, "Create Internet Match", EditorStyles.miniButton)) + { + m_Manager.matchMaker.CreateMatch(m_Manager.matchName, m_Manager.matchSize, true, "", "", "", 0, 0, m_Manager.OnMatchCreate); + } + if (GUILayout.Toggle(false, "Find Internet Match", EditorStyles.miniButton)) + { + m_Manager.matchMaker.ListMatches(0, 20, "", false, 0, 0, m_Manager.OnMatchList); + } + if (GUILayout.Toggle(false, "Stop MatchMaker", EditorStyles.miniButton)) + { + m_Manager.StopMatchMaker(); + } + EditorGUILayout.EndHorizontal(); + m_Manager.matchName = EditorGUILayout.TextField("Room Name:", m_Manager.matchName); + m_Manager.matchSize = (uint)EditorGUILayout.IntField("Room Size:", (int)m_Manager.matchSize); + + EditorGUILayout.BeginHorizontal(); + if (GUILayout.Toggle(false, "Use Local Relay", EditorStyles.miniButton)) + { + m_Manager.SetMatchHost("localhost", 1337, false); + } + if (GUILayout.Toggle(false, "Use Internet Relay", EditorStyles.miniButton)) + { + m_Manager.SetMatchHost("mm.unet.unity3d.com", 443, true); + } + EditorGUILayout.EndHorizontal(); + + EditorGUILayout.Separator(); + } + else + { + foreach (var match in m_Manager.matches) + { + if (GUI.Button(GetButtonRect(), "Join Match:" + match.name)) + { + m_Manager.matchName = match.name; + m_Manager.matchSize = (uint)match.currentSize; + m_Manager.matchMaker.JoinMatch(match.networkId, "", "", "", 0, 0, m_Manager.OnMatchJoined); + } + } + if (GUI.Button(GetButtonRect(), "Stop MatchMaker")) + { + m_Manager.StopMatchMaker(); + } + } + } + } + } + + EditorGUILayout.Separator(); + } + + public override void OnInspectorGUI() + { + Init(); + + serializedObject.Update(); + EditorGUILayout.PropertyField(m_ShowGUIProperty, m_ShowRuntimeGuiLabel); + + if (m_ManagerHud.showGUI) + { + EditorGUI.indentLevel += 1; + EditorGUILayout.PropertyField(m_OffsetXProperty, m_OffsetXLabel); + EditorGUILayout.PropertyField(m_OffsetYProperty, m_OffsetYLabel); + EditorGUI.indentLevel -= 1; + } + serializedObject.ApplyModifiedProperties(); + + if (!Application.isPlaying) + { + return; + } + + ShowControls(); + ShowServerInfo(); + ShowClientInfo(); + ShowMatchMakerInfo(); + } + } +} +#endif //ENABLE_UNET diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkManagerPreview.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkManagerPreview.cs new file mode 100644 index 00000000..279206ea --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkManagerPreview.cs @@ -0,0 +1,113 @@ +#if ENABLE_UNET +using System; +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.Networking; +using UnityObject = UnityEngine.Object; + +#pragma warning disable 618 +namespace UnityEditor.Networking +{ + [CustomPreview(typeof(NetworkManager))] + class NetworkManagerPreview : ObjectPreview + { + NetworkManager m_Manager; + GUIContent m_Title; + + protected GUIContent m_ShowServerMessagesLabel; + protected GUIContent m_ShowClientMessagesLabel; + + const int k_Padding = 4; + const int k_ColumnWidth = 120; + const int k_RowHeight = 16; + + public override void Initialize(UnityObject[] targets) + { + base.Initialize(targets); + GetNetworkInformation(target as NetworkManager); + + m_ShowServerMessagesLabel = TextUtility.TextContent("Server Message Handlers:", "Registered network message handler functions"); + m_ShowClientMessagesLabel = TextUtility.TextContent("Client Message Handlers:", "Registered network message handler functions"); + } + + public override GUIContent GetPreviewTitle() + { + if (m_Title == null) + { + m_Title = TextUtility.TextContent("NetworkManager Message Handlers"); + } + return m_Title; + } + + public override bool HasPreviewGUI() + { + return m_Manager != null; + } + + public override void OnPreviewGUI(Rect r, GUIStyle background) + { + if (Event.current.type != EventType.Repaint) + return; + + if (m_Manager == null) + return; + + int posY = (int)(r.yMin + k_Padding); + + posY = ShowServerMessageHandlers(r, posY); + posY = ShowClientMessageHandlers(r, posY); + } + + static string FormatHandler(KeyValuePair handler) + { + return string.Format("{0}:{1}()", + handler.Value.Method.DeclaringType.Name, + handler.Value.Method.Name); + } + + int ShowServerMessageHandlers(Rect r, int posY) + { + if (NetworkServer.handlers.Count == 0) + return posY; + + GUI.Label(new Rect(r.xMin + k_Padding, posY, 400, k_RowHeight), m_ShowServerMessagesLabel); + posY += k_RowHeight; + + foreach (var handler in NetworkServer.handlers) + { + GUI.Label(new Rect(r.xMin + k_Padding * 4, posY, 400, k_RowHeight), MsgType.MsgTypeToString(handler.Key)); + GUI.Label(new Rect(r.xMin + k_Padding * 4 + k_ColumnWidth, posY, 400, k_RowHeight), FormatHandler(handler)); + posY += k_RowHeight; + } + return posY; + } + + int ShowClientMessageHandlers(Rect r, int posY) + { + if (NetworkClient.allClients.Count == 0) + return posY; + + NetworkClient client = NetworkClient.allClients[0]; + if (client == null) + return posY; + + GUI.Label(new Rect(r.xMin + k_Padding, posY, 400, k_RowHeight), m_ShowClientMessagesLabel); + posY += k_RowHeight; + + foreach (var handler in client.handlers) + { + GUI.Label(new Rect(r.xMin + k_Padding * 4, posY, 400, k_RowHeight), MsgType.MsgTypeToString(handler.Key)); + GUI.Label(new Rect(r.xMin + k_Padding * 4 + k_ColumnWidth, posY, 400, k_RowHeight), FormatHandler(handler)); + posY += k_RowHeight; + } + return posY; + } + + void GetNetworkInformation(NetworkManager man) + { + m_Manager = man; + } + } +} +#pragma warning restore 618 +#endif //ENABLE_UNET diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkMigrationManagerEditor.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkMigrationManagerEditor.cs new file mode 100644 index 00000000..48abedcb --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkMigrationManagerEditor.cs @@ -0,0 +1,134 @@ +#if ENABLE_UNET +using System; +using UnityEngine; +using UnityEngine.Networking; + +namespace UnityEditor +{ + [CustomEditor(typeof(NetworkMigrationManager), true)] + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class NetworkMigrationManagerEditor : Editor + { + bool m_Initialized; + NetworkMigrationManager m_Manager; + + SerializedProperty m_HostMigrationProperty; + SerializedProperty m_ShowGUIProperty; + SerializedProperty m_OffsetXProperty; + SerializedProperty m_OffsetYProperty; + + GUIContent m_HostMigrationLabel; + GUIContent m_ShowGUILabel; + GUIContent m_OffsetXLabel; + GUIContent m_OffsetYLabel; + + bool m_ShowPeers; + bool m_ShowPlayers; + + void Init() + { + if (m_Initialized) + { + if (m_HostMigrationProperty == null) + { + // need to re-init. don't return + } + else + { + return; + } + } + + m_Initialized = true; + m_Manager = target as NetworkMigrationManager; + + m_HostMigrationProperty = serializedObject.FindProperty("m_HostMigration"); + m_ShowGUIProperty = serializedObject.FindProperty("m_ShowGUI"); + m_OffsetXProperty = serializedObject.FindProperty("m_OffsetX"); + m_OffsetYProperty = serializedObject.FindProperty("m_OffsetY"); + + m_ShowGUILabel = TextUtility.TextContent("Show GUI", "Enable to display the default UI."); + m_OffsetXLabel = TextUtility.TextContent("Offset X", "The horizonal offset of the GUI."); + m_OffsetYLabel = TextUtility.TextContent("Offset Y", "The vertical offset of the GUI."); + + m_HostMigrationLabel = TextUtility.TextContent("Use Host Migration", "Enable to use host migration."); + } + + public override void OnInspectorGUI() + { + Init(); + serializedObject.Update(); + DrawControls(); + serializedObject.ApplyModifiedProperties(); + } + + void DrawControls() + { + if (m_Manager == null) + return; + + EditorGUI.BeginChangeCheck(); + + EditorGUILayout.PropertyField(m_HostMigrationProperty, m_HostMigrationLabel); + EditorGUILayout.PropertyField(m_ShowGUIProperty, m_ShowGUILabel); + if (m_Manager.showGUI) + { + EditorGUILayout.PropertyField(m_OffsetXProperty, m_OffsetXLabel); + EditorGUILayout.PropertyField(m_OffsetYProperty, m_OffsetYLabel); + } + + if (EditorGUI.EndChangeCheck()) + { + serializedObject.ApplyModifiedProperties(); + } + + if (Application.isPlaying) + { + EditorGUILayout.Separator(); + + //runtime data + EditorGUILayout.LabelField("Disconnected From Host", m_Manager.disconnectedFromHost.ToString()); + EditorGUILayout.LabelField("Waiting to become New Host", m_Manager.waitingToBecomeNewHost.ToString()); + EditorGUILayout.LabelField("Waitingto Reconnect to New Host", m_Manager.waitingReconnectToNewHost.ToString()); + EditorGUILayout.LabelField("Your ConnectionId", m_Manager.oldServerConnectionId.ToString()); + EditorGUILayout.LabelField("New Host Address", m_Manager.newHostAddress); + + if (m_Manager.peers != null) + { + m_ShowPeers = EditorGUILayout.Foldout(m_ShowPeers, "Peers"); + if (m_ShowPeers) + { + EditorGUI.indentLevel += 1; + foreach (var peer in m_Manager.peers) + { + EditorGUILayout.LabelField("Peer: ", peer.ToString()); + } + EditorGUI.indentLevel -= 1; + } + } + + if (m_Manager.pendingPlayers != null) + { + m_ShowPlayers = EditorGUILayout.Foldout(m_ShowPlayers, "Pending Players"); + if (m_ShowPlayers) + { + EditorGUI.indentLevel += 1; + foreach (var connId in m_Manager.pendingPlayers.Keys) + { + EditorGUILayout.LabelField("Connection: ", connId.ToString()); + EditorGUI.indentLevel += 1; + var players = m_Manager.pendingPlayers[connId].players; + foreach (var p in players) + { + EditorGUILayout.ObjectField("Player netId:" + p.netId + " contId:" + p.playerControllerId, p.obj, typeof(GameObject), false); + } + EditorGUI.indentLevel -= 1; + } + EditorGUI.indentLevel -= 1; + } + } + } + } + } +} +#endif diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkScenePostProcess.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkScenePostProcess.cs new file mode 100644 index 00000000..0b3b6de7 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkScenePostProcess.cs @@ -0,0 +1,55 @@ +#if ENABLE_UNET +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEditor.Callbacks; +using UnityEngine; +using UnityEngine.Networking; + +namespace UnityEditor +{ + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class NetworkScenePostProcess : MonoBehaviour + { + [PostProcessScene] + public static void OnPostProcessScene() + { + var prefabWarnings = new HashSet(); + + int nextSceneId = 1; + foreach (NetworkIdentity uv in FindObjectsOfType().OrderBy(identity => identity.name)) + { + // if we had a [ConflictComponent] attribute that would be better than this check. + // also there is no context about which scene this is in. + if (uv.GetComponent() != null) + { + Debug.LogError("NetworkManager has a NetworkIdentity component. This will cause the NetworkManager object to be disabled, so it is not recommended."); + } + + if (uv.isClient || uv.isServer) + continue; + + uv.gameObject.SetActive(false); + uv.ForceSceneId(nextSceneId++); + + var prefabGO = UnityEditor.PrefabUtility.GetCorrespondingObjectFromSource(uv.gameObject) as GameObject; + if (prefabGO) + { + var prefabRootGO = prefabGO.transform.root.gameObject; + if (prefabRootGO) + { + var identities = prefabRootGO.GetComponentsInChildren(); + if (identities.Length > 1 && !prefabWarnings.Contains(prefabRootGO.name)) + { + // make sure we only print one error per prefab + prefabWarnings.Add(prefabRootGO.name); + + Debug.LogWarningFormat("Prefab '{0}' has several NetworkIdentity components attached to itself or its children, this is not supported.", prefabRootGO.name); + } + } + } + } + } + } +} +#endif //ENABLE_UNET diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkTransformChildEditor.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkTransformChildEditor.cs new file mode 100644 index 00000000..3e18a59d --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkTransformChildEditor.cs @@ -0,0 +1,142 @@ +#if ENABLE_UNET +using System; +using UnityEditor; +using UnityEngine; +using System.Collections; +using UnityEngine.Networking; + + +namespace UnityEditor +{ + [CustomEditor(typeof(NetworkTransformChild), true)] + [CanEditMultipleObjects] + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class NetworkTransformChildEditor : Editor + { + private static GUIContent[] axisOptions = {TextUtility.TextContent("None"), new GUIContent("X"), TextUtility.TextContent("Y (Top-Down 2D)"), TextUtility.TextContent("Z (Side-on 2D)"), TextUtility.TextContent("XY (FPS)"), new GUIContent("XZ"), new GUIContent("YZ"), TextUtility.TextContent("XYZ (full 3D)")}; + + bool m_Initialized = false; + NetworkTransformChild sync; + + SerializedProperty m_Target; + SerializedProperty m_MovementThreshold; + + SerializedProperty m_InterpolateRotation; + SerializedProperty m_InterpolateMovement; + SerializedProperty m_RotationSyncCompression; + + protected GUIContent m_TargetLabel; + protected GUIContent m_MovementThresholdLabel; + + protected GUIContent m_InterpolateRotationLabel; + protected GUIContent m_InterpolateMovementLabel; + protected GUIContent m_RotationSyncCompressionLabel; + protected GUIContent m_RotationAxisLabel; + + SerializedProperty m_NetworkSendIntervalProperty; + GUIContent m_NetworkSendIntervalLabel; + + public void Init() + { + if (m_Initialized) + return; + + m_Initialized = true; + sync = target as NetworkTransformChild; + + m_Target = serializedObject.FindProperty("m_Target"); + if (sync.GetComponent() == null) + { + if (LogFilter.logError) { Debug.LogError("NetworkTransformChild must be on the root object with the NetworkTransform, not on the child node"); } + m_Target.objectReferenceValue = null; + } + + m_MovementThreshold = serializedObject.FindProperty("m_MovementThreshold"); + + m_InterpolateRotation = serializedObject.FindProperty("m_InterpolateRotation"); + m_InterpolateMovement = serializedObject.FindProperty("m_InterpolateMovement"); + m_RotationSyncCompression = serializedObject.FindProperty("m_RotationSyncCompression"); + + m_NetworkSendIntervalProperty = serializedObject.FindProperty("m_SendInterval"); + + m_TargetLabel = TextUtility.TextContent("Target", "The child transform to be synchronized."); + m_NetworkSendIntervalLabel = TextUtility.TextContent("Network Send Rate", "Number of network updates per second."); + EditorGUI.indentLevel += 1; + m_MovementThresholdLabel = TextUtility.TextContent("Movement Threshold", "The distance that this object can move without sending a movement synchronization update."); + + m_InterpolateRotationLabel = TextUtility.TextContent("Interpolate Rotation Factor", "The larger this number is, the faster the object will interpolate to the target facing direction."); + m_InterpolateMovementLabel = TextUtility.TextContent("Interpolate Movement Factor", "The larger this number is, the faster the object will interpolate to the target position."); + m_RotationSyncCompressionLabel = TextUtility.TextContent("Compress Rotation", "How much to compress rotation sync updates.\n\nChoose None for no compression.\n\nChoose Low for a low amount of compression that preserves accuracy.\n\nChoose High for a high amount of compression that sacrifices accuracy."); + m_RotationAxisLabel = TextUtility.TextContent("Rotation Axis", "Which axis to use for rotation."); + + EditorGUI.indentLevel -= 1; + } + + protected void ShowControls() + { + if (m_Target == null) + { + m_Initialized = false; + } + Init(); + + serializedObject.Update(); + + int sendRate = 0; + if (m_NetworkSendIntervalProperty.floatValue != 0) + { + sendRate = (int)(1 / m_NetworkSendIntervalProperty.floatValue); + } + int newSendRate = EditorGUILayout.IntSlider(m_NetworkSendIntervalLabel, sendRate, 0, 30); + if (newSendRate != sendRate) + { + if (newSendRate == 0) + { + m_NetworkSendIntervalProperty.floatValue = 0; + } + else + { + m_NetworkSendIntervalProperty.floatValue = 1.0f / newSendRate; + } + } + if (EditorGUILayout.PropertyField(m_Target, m_TargetLabel)) + { + if (sync.GetComponent() == null) + { + if (LogFilter.logError) { Debug.LogError("NetworkTransformChild must be on the root object with the NetworkTransform, not on the child node"); } + m_Target.objectReferenceValue = null; + } + } + + EditorGUILayout.PropertyField(m_MovementThreshold, m_MovementThresholdLabel); + if (m_MovementThreshold.floatValue < 0) + { + m_MovementThreshold.floatValue = 0; + EditorUtility.SetDirty(sync); + } + EditorGUILayout.PropertyField(m_InterpolateMovement, m_InterpolateMovementLabel); + + EditorGUILayout.PropertyField(m_InterpolateRotation, m_InterpolateRotationLabel); + + int newRotation = EditorGUILayout.Popup( + m_RotationAxisLabel, + (int)sync.syncRotationAxis, + axisOptions); + if ((NetworkTransform.AxisSyncMode)newRotation != sync.syncRotationAxis) + { + sync.syncRotationAxis = (NetworkTransform.AxisSyncMode)newRotation; + EditorUtility.SetDirty(sync); + } + + EditorGUILayout.PropertyField(m_RotationSyncCompression, m_RotationSyncCompressionLabel); + + serializedObject.ApplyModifiedProperties(); + } + + public override void OnInspectorGUI() + { + ShowControls(); + } + } +} +#endif //ENABLE_UNET diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkTransformEditor.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkTransformEditor.cs new file mode 100644 index 00000000..b659d219 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkTransformEditor.cs @@ -0,0 +1,213 @@ +#if ENABLE_UNET +using System; +using UnityEngine; +using UnityEngine.Networking; + +namespace UnityEditor +{ + [CustomEditor(typeof(NetworkTransform), true)] + [CanEditMultipleObjects] + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class NetworkTransformEditor : Editor + { + private static GUIContent[] axisOptions = {TextUtility.TextContent("None"), new GUIContent("X"), TextUtility.TextContent("Y (Top-Down 2D)"), TextUtility.TextContent("Z (Side-on 2D)"), TextUtility.TextContent("XY (FPS)"), new GUIContent("XZ"), new GUIContent("YZ"), TextUtility.TextContent("XYZ (full 3D)")}; + + bool m_Initialized; + NetworkTransform m_SyncTransform; + + SerializedProperty m_TransformSyncMode; + SerializedProperty m_MovementTheshold; + SerializedProperty m_VelocityThreshold; + SerializedProperty m_SnapThreshold; + + SerializedProperty m_InterpolateRotation; + SerializedProperty m_InterpolateMovement; + SerializedProperty m_RotationSyncCompression; + SerializedProperty m_SyncSpin; + + protected GUIContent m_MovementThesholdLabel; + protected GUIContent m_VelocityThresholdLabel; + protected GUIContent m_SnapThresholdLabel; + + protected GUIContent m_InterpolateRotationLabel; + protected GUIContent m_InterpolateMovementLabel; + protected GUIContent m_RotationSyncCompressionLabel; + protected GUIContent m_RotationAxisLabel; + protected GUIContent m_SyncSpinLabel; + + SerializedProperty m_NetworkSendIntervalProperty; + GUIContent m_NetworkSendIntervalLabel; + + public void Init() + { + if (m_Initialized) + return; + + m_Initialized = true; + m_SyncTransform = target as NetworkTransform; + + if (m_SyncTransform.transformSyncMode == NetworkTransform.TransformSyncMode.SyncNone) + { + if (m_SyncTransform.GetComponent() != null) + { + m_SyncTransform.transformSyncMode = NetworkTransform.TransformSyncMode.SyncRigidbody3D; + m_SyncTransform.syncRotationAxis = NetworkTransform.AxisSyncMode.AxisXYZ; + EditorUtility.SetDirty(m_SyncTransform); + } + else if (m_SyncTransform.GetComponent() != null) + { + m_SyncTransform.transformSyncMode = NetworkTransform.TransformSyncMode.SyncRigidbody2D; + m_SyncTransform.syncRotationAxis = NetworkTransform.AxisSyncMode.AxisZ; + EditorUtility.SetDirty(m_SyncTransform); + } + else if (m_SyncTransform.GetComponent() != null) + { + m_SyncTransform.transformSyncMode = NetworkTransform.TransformSyncMode.SyncCharacterController; + m_SyncTransform.syncRotationAxis = NetworkTransform.AxisSyncMode.AxisXYZ; + EditorUtility.SetDirty(m_SyncTransform); + } + else + { + m_SyncTransform.transformSyncMode = NetworkTransform.TransformSyncMode.SyncTransform; + m_SyncTransform.syncRotationAxis = NetworkTransform.AxisSyncMode.AxisXYZ; + EditorUtility.SetDirty(m_SyncTransform); + } + } + m_TransformSyncMode = serializedObject.FindProperty("m_TransformSyncMode"); + m_MovementTheshold = serializedObject.FindProperty("m_MovementTheshold"); + m_VelocityThreshold = serializedObject.FindProperty("m_VelocityThreshold"); + m_SnapThreshold = serializedObject.FindProperty("m_SnapThreshold"); + + m_InterpolateRotation = serializedObject.FindProperty("m_InterpolateRotation"); + m_InterpolateMovement = serializedObject.FindProperty("m_InterpolateMovement"); + m_RotationSyncCompression = serializedObject.FindProperty("m_RotationSyncCompression"); + m_SyncSpin = serializedObject.FindProperty("m_SyncSpin"); + + m_NetworkSendIntervalProperty = serializedObject.FindProperty("m_SendInterval"); + m_NetworkSendIntervalLabel = TextUtility.TextContent("Network Send Rate", "Number of network updates per second."); + EditorGUI.indentLevel += 1; + m_MovementThesholdLabel = TextUtility.TextContent("Movement Threshold", "The distance that this object can move without sending a movement synchronization update."); + m_VelocityThresholdLabel = TextUtility.TextContent("Velocity Threshold", "The minimum velocity difference that will be synchronized over the network."); + m_SnapThresholdLabel = TextUtility.TextContent("Snap Threshold", "If a movement update puts this object further from its current position that this value, it will snap to the updated position instead of moving smoothly."); + + m_InterpolateRotationLabel = TextUtility.TextContent("Interpolate Rotation Factor", "The larger this number is, the faster the object will interpolate to the target facing direction."); + m_InterpolateMovementLabel = TextUtility.TextContent("Interpolate Movement Factor", "The larger this number is, the faster the object will interpolate to the target position."); + m_RotationSyncCompressionLabel = TextUtility.TextContent("Compress Rotation", "How much to compress rotation sync updates.\n\nChoose None for no compression.\n\nChoose Low for a low amount of compression that preserves accuracy.\n\nChoose High for a high amount of compression that sacrifices accuracy."); + m_RotationAxisLabel = TextUtility.TextContent("Rotation Axis", "Which axis to use for rotation."); + m_SyncSpinLabel = TextUtility.TextContent("Sync Angular Velocity", "Enable to sync angular velocity."); + EditorGUI.indentLevel -= 1; + } + + protected void ShowControls() + { + if (m_TransformSyncMode == null) + { + m_Initialized = false; + } + Init(); + + serializedObject.Update(); + + int sendRate = 0; + if (m_NetworkSendIntervalProperty.floatValue != 0) + { + sendRate = (int)(1 / m_NetworkSendIntervalProperty.floatValue); + } + int newSendRate = EditorGUILayout.IntSlider(m_NetworkSendIntervalLabel, sendRate, 0, 30); + if (newSendRate != sendRate) + { + if (newSendRate == 0) + { + m_NetworkSendIntervalProperty.floatValue = 0; + } + else + { + m_NetworkSendIntervalProperty.floatValue = 1.0f / newSendRate; + } + } + EditorGUILayout.PropertyField(m_TransformSyncMode); + if (m_TransformSyncMode.enumValueIndex == (int)NetworkTransform.TransformSyncMode.SyncRigidbody3D) + { + Rigidbody r3D = m_SyncTransform.GetComponent(); + if (r3D == null) + { + Debug.LogError("Object has no Rigidbody component."); + m_TransformSyncMode.enumValueIndex = (int)NetworkTransform.TransformSyncMode.SyncTransform; + EditorUtility.SetDirty(m_SyncTransform); + } + } + if (m_TransformSyncMode.enumValueIndex == (int)NetworkTransform.TransformSyncMode.SyncRigidbody2D) + { + Rigidbody2D r2D = m_SyncTransform.GetComponent(); + if (r2D == null) + { + Debug.LogError("Object has no Rigidbody2D component."); + m_TransformSyncMode.enumValueIndex = (int)NetworkTransform.TransformSyncMode.SyncTransform; + EditorUtility.SetDirty(m_SyncTransform); + } + } + if (m_TransformSyncMode.enumValueIndex == (int)NetworkTransform.TransformSyncMode.SyncCharacterController) + { + var cc = m_SyncTransform.GetComponent(); + if (cc == null) + { + Debug.LogError("Object has no CharacterController component."); + m_TransformSyncMode.enumValueIndex = (int)NetworkTransform.TransformSyncMode.SyncTransform; + EditorUtility.SetDirty(m_SyncTransform); + } + } + + EditorGUILayout.LabelField("Movement:"); + EditorGUI.indentLevel += 1; + EditorGUILayout.PropertyField(m_MovementTheshold, m_MovementThesholdLabel); + + + if (m_VelocityThreshold.floatValue < 0) + { + m_VelocityThreshold.floatValue = 0; + EditorUtility.SetDirty(m_SyncTransform); + } + + if ((m_TransformSyncMode.enumValueIndex == (int)NetworkTransform.TransformSyncMode.SyncRigidbody3D) || (m_TransformSyncMode.enumValueIndex == (int)NetworkTransform.TransformSyncMode.SyncRigidbody2D)) + { + EditorGUILayout.PropertyField(m_VelocityThreshold, m_VelocityThresholdLabel); + } + + if (m_MovementTheshold.floatValue < 0) + { + m_MovementTheshold.floatValue = 0; + EditorUtility.SetDirty(m_SyncTransform); + } + EditorGUILayout.PropertyField(m_SnapThreshold, m_SnapThresholdLabel); + EditorGUILayout.PropertyField(m_InterpolateMovement, m_InterpolateMovementLabel); + EditorGUI.indentLevel -= 1; + + EditorGUILayout.LabelField("Rotation:"); + EditorGUI.indentLevel += 1; + + int newRotation = EditorGUILayout.Popup( + m_RotationAxisLabel, + (int)m_SyncTransform.syncRotationAxis, + axisOptions); + if ((NetworkTransform.AxisSyncMode)newRotation != m_SyncTransform.syncRotationAxis) + { + m_SyncTransform.syncRotationAxis = (NetworkTransform.AxisSyncMode)newRotation; + EditorUtility.SetDirty(m_SyncTransform); + } + + EditorGUILayout.PropertyField(m_InterpolateRotation, m_InterpolateRotationLabel); + EditorGUILayout.PropertyField(m_RotationSyncCompression, m_RotationSyncCompressionLabel); + EditorGUILayout.PropertyField(m_SyncSpin, m_SyncSpinLabel); + + EditorGUI.indentLevel -= 1; + + serializedObject.ApplyModifiedProperties(); + } + + public override void OnInspectorGUI() + { + ShowControls(); + } + } +} +#endif //ENABLE_UNET diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkTransformPreview.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkTransformPreview.cs new file mode 100644 index 00000000..19601292 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkTransformPreview.cs @@ -0,0 +1,88 @@ +#if ENABLE_UNET +using System; +using UnityEngine; +using UnityEngine.Networking; +using UnityObject = UnityEngine.Object; + +#pragma warning disable 618 +namespace UnityEditor.Networking +{ + [CustomPreview(typeof(GameObject))] + class NetworkTransformPreview : ObjectPreview + { + NetworkTransform m_Transform; + Rigidbody m_Rigidbody3D; + Rigidbody2D m_Rigidbody2D; + + GUIContent m_Title; + + public override void Initialize(UnityObject[] targets) + { + base.Initialize(targets); + GetNetworkInformation(target as GameObject); + } + + public override GUIContent GetPreviewTitle() + { + if (m_Title == null) + { + m_Title = TextUtility.TextContent("Network Transform"); + } + return m_Title; + } + + public override bool HasPreviewGUI() + { + return m_Transform != null; + } + + public override void OnPreviewGUI(Rect r, GUIStyle background) + { + if (Event.current.type != EventType.Repaint) + return; + + if (m_Transform == null) + return; + + const int padding = 4; + int posY = 4; + + float posDiff = (m_Transform.transform.position - m_Transform.targetSyncPosition).magnitude; + GUI.Label(new Rect(r.xMin + padding, r.y + posY, 600, 20), "Position: " + m_Transform.transform.position + " Target: " + m_Transform.targetSyncPosition + " Diff: " + posDiff); + posY += 20; + + if (m_Rigidbody3D != null) + { + float angleDiff3D = Quaternion.Angle(m_Transform.rigidbody3D.rotation, m_Transform.targetSyncRotation3D); + GUI.Label(new Rect(r.xMin + padding, r.y + posY, 600, 20), "Angle: " + m_Transform.rigidbody3D.rotation + " Target: " + m_Transform.targetSyncRotation3D + " Diff: " + angleDiff3D); + posY += 20; + + GUI.Label(new Rect(r.xMin + padding, r.y + posY, 600, 20), "Velocity: " + m_Transform.rigidbody3D.velocity + " Target: " + m_Transform.targetSyncVelocity); + posY += 20; + } + + if (m_Rigidbody2D != null) + { + float angleDiff2D = m_Transform.rigidbody2D.rotation - m_Transform.targetSyncRotation2D; + GUI.Label(new Rect(r.xMin + padding, r.y + posY, 600, 20), "Angle: " + m_Transform.rigidbody2D.rotation + " Target: " + m_Transform.targetSyncRotation2D + " Diff: " + angleDiff2D); + posY += 20; + + GUI.Label(new Rect(r.xMin + padding, r.y + posY, 600, 20), "Velocity: " + m_Transform.rigidbody2D.velocity + " Target: " + m_Transform.targetSyncVelocity); + posY += 20; + } + + GUI.Label(new Rect(r.xMin + padding, r.y + posY, 200, 20), "Last SyncTime: " + (Time.time - m_Transform.lastSyncTime)); + posY += 20; + } + + void GetNetworkInformation(GameObject gameObject) + { + m_Transform = gameObject.GetComponent(); + + m_Rigidbody3D = gameObject.GetComponent(); + m_Rigidbody2D = gameObject.GetComponent(); + } + } +} +#pragma warning restore 618 +#endif //ENABLE_UNET diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkTransformVisualizerEditor.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkTransformVisualizerEditor.cs new file mode 100644 index 00000000..d43d87d2 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/NetworkTransformVisualizerEditor.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using UnityEngine; +using UnityEngine.Networking; + +namespace UnityEditor +{ + [CustomEditor(typeof(NetworkTransformVisualizer), true)] + [CanEditMultipleObjects] + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class NetworkTransformVisualizerEditor : NetworkBehaviourInspector + { + internal override bool hideScriptField + { + get + { + return true; + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/Properties/AssemblyInfo.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..fb35d4f6 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/Properties/AssemblyInfo.cs @@ -0,0 +1,38 @@ +using System; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("UnityEditor.Networking")] +[assembly: AssemblyDescription("Networking High Level API Editor part")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Unity Technologies")] +[assembly: AssemblyProduct("UnityEditor.Networking")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] +[assembly: InternalsVisibleTo("Assembly-CSharp-Editor-testable")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("5f32cd94-baa9-4578-a686-d4b9d6b660f7")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/Tools/MiniJSON.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/Tools/MiniJSON.cs new file mode 100644 index 00000000..4bcf87f3 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/Tools/MiniJSON.cs @@ -0,0 +1,637 @@ +/* + * Copyright (c) 2013 Calvin Rien + * + * Based on the JSON parser by Patrick van Bergen + * http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html + * + * Simplified it so that it doesn't throw exceptions + * and can be used in Unity iPhone with maximum code stripping. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Reflection; +using System.IO; +using System.Linq; +using System.Text; + +namespace UnityEditor.Networking +{ + // Example usage: + // + // using UnityEngine; + // using UnityEditor; + // using System.Collections; + // using System.Collections.Generic; + // + // public class MiniJSONTest : MonoBehaviour { + // void Start () { + // var jsonString = "{ \"array\": [1.44,2,3], " + + // "\"object\": {\"key1\":\"value1\", \"key2\":256}, " + + // "\"string\": \"The quick brown fox \\\"jumps\\\" over the lazy dog \", " + + // "\"unicode\": \"\\u3041 Men\u00fa sesi\u00f3n\", " + + // "\"int\": 65536, " + + // "\"float\": 3.1415926, " + + // "\"bool\": true, " + + // "\"null\": null }"; + // + // var dict = Json.Deserialize (jsonString) as Dictionary; + // + // Debug.Log ("deserialized: " + dict.GetType ()); + // Debug.Log ("dict['array'][0]: " + ((List) dict["array"])[0]); + // Debug.Log ("dict['string']: " + (string) dict["string"]); + // Debug.Log ("dict['float']: " + (double) dict["float"]); // floats come out as doubles + // Debug.Log ("dict['int']: " + (long) dict["int"]); // ints come out as longs + // Debug.Log ("dict['unicode']: " + (string) dict["unicode"]); + // + // var str = Json.Serialize (dict); + // + // Debug.Log ("serialized: " + str); + // } + // } + + /// + /// This class encodes and decodes JSON strings. + /// Spec. details, see http://www.json.org/ + /// + /// JSON uses Arrays and Objects. These correspond here to the datatypes IList and IDictionary. + /// All numbers are parsed to doubles. + /// + internal static class Json + { + /// + /// Parses the string json into a value + /// + /// A JSON string. + /// An List<object>, a Dictionary<string, object>, a double, an integer,a string, null, true, or false + public static object Deserialize (string json) + { + // save the string for debug information + if (json == null) + { + return null; + } + + return Parser.Parse (json); + } + + sealed class Parser : IDisposable + { + const string WORD_BREAK = "{}[],:\""; + + public static bool IsWordBreak (char c) + { + return Char.IsWhiteSpace (c) || WORD_BREAK.IndexOf (c) != -1; + } + + enum TOKEN + { + NONE, + CURLY_OPEN, + CURLY_CLOSE, + SQUARED_OPEN, + SQUARED_CLOSE, + COLON, + COMMA, + STRING, + NUMBER, + TRUE, + FALSE, + NULL + }; + + StringReader json; + + Parser (string jsonString) + { + json = new StringReader (jsonString); + } + + public static object Parse (string jsonString) + { + using (var instance = new Parser (jsonString)) + { + return instance.ParseValue (); + } + } + + public void Dispose () + { + json.Dispose (); + json = null; + } + + Dictionary ParseObject () + { + Dictionary table = new Dictionary (); + + // ditch opening brace + json.Read (); + + // { + while (true) + { + switch (NextToken) + { + case TOKEN.NONE: + return null; + case TOKEN.COMMA: + continue; + case TOKEN.CURLY_CLOSE: + return table; + default: + // name + string name = ParseString (); + if (name == null) + { + return null; + } + + // : + if (NextToken != TOKEN.COLON) + { + return null; + } + // ditch the colon + json.Read (); + + // value + table[name] = ParseValue (); + break; + } + } + } + + List ParseArray () + { + List array = new List (); + + // ditch opening bracket + json.Read (); + + // [ + var parsing = true; + while (parsing) + { + TOKEN nextToken = NextToken; + + switch (nextToken) + { + case TOKEN.NONE: + return null; + case TOKEN.COMMA: + continue; + case TOKEN.SQUARED_CLOSE: + parsing = false; + break; + default: + object value = ParseByToken (nextToken); + + array.Add (value); + break; + } + } + + return array; + } + + object ParseValue () + { + TOKEN nextToken = NextToken; + return ParseByToken (nextToken); + } + + object ParseByToken (TOKEN token) + { + switch (token) + { + case TOKEN.STRING: + return ParseString (); + case TOKEN.NUMBER: + return ParseNumber (); + case TOKEN.CURLY_OPEN: + return ParseObject (); + case TOKEN.SQUARED_OPEN: + return ParseArray (); + case TOKEN.TRUE: + return true; + case TOKEN.FALSE: + return false; + case TOKEN.NULL: + return null; + default: + return null; + } + } + + string ParseString () + { + StringBuilder s = new StringBuilder (); + char c; + + // ditch opening quote + json.Read (); + + bool parsing = true; + while (parsing) + { + + if (json.Peek () == -1) + { + parsing = false; + break; + } + + c = NextChar; + switch (c) + { + case '"': + parsing = false; + break; + case '\\': + if (json.Peek () == -1) + { + parsing = false; + break; + } + + c = NextChar; + switch (c) + { + case '"': + case '\\': + case '/': + s.Append (c); + break; + case 'b': + s.Append ('\b'); + break; + case 'f': + s.Append ('\f'); + break; + case 'n': + s.Append ('\n'); + break; + case 'r': + s.Append ('\r'); + break; + case 't': + s.Append ('\t'); + break; + case 'u': + var hex = new char[4]; + + for (int i=0; i< 4; i++) + { + hex[i] = NextChar; + } + + s.Append ((char) Convert.ToInt32 (new string (hex), 16)); + break; + } + break; + default: + s.Append (c); + break; + } + } + + return s.ToString (); + } + + object ParseNumber () + { + string number = NextWord; + + if (number.IndexOf ('.') == -1) + { + long parsedInt; + Int64.TryParse (number, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out parsedInt); + return parsedInt; + } + + double parsedDouble; + Double.TryParse (number, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out parsedDouble); + return parsedDouble; + } + + void EatWhitespace () + { + while (Char.IsWhiteSpace (PeekChar)) + { + json.Read (); + + if (json.Peek () == -1) + { + break; + } + } + } + + char PeekChar + { + get + { + return Convert.ToChar (json.Peek ()); + } + } + + char NextChar + { + get + { + return Convert.ToChar (json.Read ()); + } + } + + string NextWord + { + get + { + StringBuilder word = new StringBuilder (); + + while (!IsWordBreak (PeekChar)) + { + word.Append (NextChar); + + if (json.Peek () == -1) + { + break; + } + } + + return word.ToString (); + } + } + + TOKEN NextToken + { + get + { + EatWhitespace (); + + if (json.Peek () == -1) + { + return TOKEN.NONE; + } + + switch (PeekChar) + { + case '{': + return TOKEN.CURLY_OPEN; + case '}': + json.Read (); + return TOKEN.CURLY_CLOSE; + case '[': + return TOKEN.SQUARED_OPEN; + case ']': + json.Read (); + return TOKEN.SQUARED_CLOSE; + case ',': + json.Read (); + return TOKEN.COMMA; + case '"': + return TOKEN.STRING; + case ':': + return TOKEN.COLON; + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + case '-': + return TOKEN.NUMBER; + } + + switch (NextWord) + { + case "false": + return TOKEN.FALSE; + case "true": + return TOKEN.TRUE; + case "null": + return TOKEN.NULL; + } + + return TOKEN.NONE; + } + } + } + + /// + /// Converts a IDictionary / IList object or a simple type (string, int, etc.) into a JSON string + /// + /// A Dictionary<string, object> / List<object> + /// A JSON encoded string, or null if object 'json' is not serializable + public static string Serialize (object obj) + { + return Serializer.Serialize (obj); + } + + sealed class Serializer + { + StringBuilder builder; + + Serializer () + { + builder = new StringBuilder (); + } + + public static string Serialize (object obj) + { + var instance = new Serializer (); + + instance.SerializeValue (obj); + + return instance.builder.ToString (); + } + + void SerializeValue (object value) + { + IList asList; + IDictionary asDict; + string asStr; + + if (value == null || value is Delegate) + { + builder.Append ("null"); + } + else if ((asStr = value as string) != null) + { + SerializeString (asStr); + } + else if (value is bool) + { + builder.Append ((bool) value ? "true" : "false"); + } + else if ((asList = value as IList) != null) + { + SerializeArray (asList); + } + else if ((asDict = value as IDictionary) != null) + { + SerializeObject (asDict); + } + else if (value is char) + { + SerializeString (new string ((char) value, 1)); + } + else + { + SerializeOther (value); + } + } + + void SerializeObject (IDictionary obj) + { + bool first = true; + + builder.Append ('{'); + + foreach (object e in obj.Keys) + { + if (!first) + { + builder.Append (','); + } + + SerializeString (e.ToString ()); + builder.Append (':'); + + SerializeValue (obj[e]); + + first = false; + } + + builder.Append ('}'); + } + + void SerializeArray (IList anArray) + { + builder.Append ('['); + + bool first = true; + + foreach (object obj in anArray) + { + if (!first) + { + builder.Append (','); + } + + SerializeValue (obj); + + first = false; + } + + builder.Append (']'); + } + + void SerializeString (string str) + { + builder.Append ('\"'); + + char[] charArray = str.ToCharArray (); + foreach (var c in charArray) + { + switch (c) + { + case '"': + builder.Append ("\\\""); + break; + case '\\': + builder.Append ("\\\\"); + break; + case '\b': + builder.Append ("\\b"); + break; + case '\f': + builder.Append ("\\f"); + break; + case '\n': + builder.Append ("\\n"); + break; + case '\r': + builder.Append ("\\r"); + break; + case '\t': + builder.Append ("\\t"); + break; + default: + int codepoint = Convert.ToInt32 (c); + if ((codepoint >= 32) && (codepoint <= 126)) + { + builder.Append (c); + } + else + { + builder.Append ("\\u"); + builder.Append (codepoint.ToString ("x4")); + } + break; + } + } + + builder.Append ('\"'); + } + + void SerializeOther (object value) + { + // NOTE: decimals lose precision during serialization. + // They always have, I'm just letting you know. + // Previously floats and doubles lost precision too. + if (value is float) + { + builder.Append (((float) value).ToString ("R", System.Globalization.CultureInfo.InvariantCulture)); + } + else if (value is int || value is uint || value is long || value is sbyte || value is byte || value is short || value is ushort || value is ulong) + { + builder.Append (value); + } + else if (value is double || value is decimal) + { + builder.Append (Convert.ToDouble (value).ToString ("R", System.Globalization.CultureInfo.InvariantCulture)); + } + else + { + Dictionary map = new Dictionary (); + List fields = value.GetType ().GetFields (BindingFlags.Instance | BindingFlags.Public).ToList (); + foreach (FieldInfo field in fields) + { + map.Add (field.Name, field.GetValue (value)); + } + List properties = value.GetType ().GetProperties (BindingFlags.Instance | BindingFlags.Public).ToList (); + foreach (PropertyInfo property in properties) + { + map.Add (property.Name, property.GetValue (value, null)); + } + SerializeObject (map); + } + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/Tools/TextUtility.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/Tools/TextUtility.cs new file mode 100644 index 00000000..5dbc2a54 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/Tools/TextUtility.cs @@ -0,0 +1,16 @@ +using UnityEngine; + +public static class TextUtility +{ + public static GUIContent TextContent(string name, string tooltip) + { + GUIContent newContent = new GUIContent(name); + newContent.tooltip = tooltip; + return newContent; + } + + public static GUIContent TextContent(string name) + { + return new GUIContent(name); + } +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/Tools/Weaver/AssemblyInfo.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/Tools/Weaver/AssemblyInfo.cs new file mode 100644 index 00000000..15a55055 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/Tools/Weaver/AssemblyInfo.cs @@ -0,0 +1,28 @@ +using System; +using System.Reflection; +using System.Runtime.CompilerServices; + +// Information about this assembly is defined by the following attributes. +// Change them to the values specific to your project. + +[assembly: AssemblyTitle("Unity.UNetWeaver")] +[assembly: AssemblyDescription("UNET assembly post processor for code generation.")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Unity Technologies")] +[assembly: AssemblyProduct("Unity.UNetWeaver")] +[assembly: AssemblyCopyright("Copyright © 2014")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] +[assembly: InternalsVisibleTo("Assembly-CSharp-Editor-testable")] + +// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". +// The form "{Major}.{Minor}.*" will automatically update the build and revision, +// and "{Major}.{Minor}.{Build}.*" will update just the revision. + +[assembly: AssemblyVersion("1.0.*")] + +// The following attributes are used to specify the signing key for the assembly, +// if desired. See the Mono documentation for more information about signing. + +//[assembly: AssemblyDelaySign(false)] +//[assembly: AssemblyKeyFile("")] diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/Tools/Weaver/Helpers.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/Tools/Weaver/Helpers.cs new file mode 100644 index 00000000..5e4b1458 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/Tools/Weaver/Helpers.cs @@ -0,0 +1,227 @@ +using System; +using System.Linq; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Reflection; +using Mono.Cecil; +using Mono.Cecil.Cil; +using Mono.Cecil.Mdb; +using Mono.Cecil.Pdb; + +namespace Unity.UNetWeaver +{ + class Helpers + { + // This code is taken from SerializationWeaver + + class AddSearchDirectoryHelper + { + delegate void AddSearchDirectoryDelegate(string directory); + readonly AddSearchDirectoryDelegate _addSearchDirectory; + + public AddSearchDirectoryHelper(IAssemblyResolver assemblyResolver) + { + // reflection is used because IAssemblyResolver doesn't implement AddSearchDirectory but both DefaultAssemblyResolver and NuGetAssemblyResolver do + var addSearchDirectory = assemblyResolver.GetType().GetMethod("AddSearchDirectory", BindingFlags.Instance | BindingFlags.Public, null, new Type[] { typeof(string) }, null); + if (addSearchDirectory == null) + throw new Exception("Assembly resolver doesn't implement AddSearchDirectory method."); + _addSearchDirectory = (AddSearchDirectoryDelegate)Delegate.CreateDelegate(typeof(AddSearchDirectoryDelegate), assemblyResolver, addSearchDirectory); + } + + public void AddSearchDirectory(string directory) + { + _addSearchDirectory(directory); + } + } + + public static string UnityEngineDLLDirectoryName() + { + var directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase); + return directoryName != null ? directoryName.Replace(@"file:\", "") : null; + } + + public static ISymbolReaderProvider GetSymbolReaderProvider(string inputFile) + { + string nakedFileName = inputFile.Substring(0, inputFile.Length - 4); + if (File.Exists(nakedFileName + ".pdb")) + { + Console.WriteLine("Symbols will be read from " + nakedFileName + ".pdb"); + return new PdbReaderProvider(); + } + if (File.Exists(nakedFileName + ".dll.mdb")) + { + Console.WriteLine("Symbols will be read from " + nakedFileName + ".dll.mdb"); + return new MdbReaderProvider(); + } + Console.WriteLine("No symbols for " + inputFile); + return null; + } + + public static bool InheritsFromSyncList(TypeReference typeRef, Weaver weaver) + { + try + { + // value types cant inherit from SyncList + if (typeRef.IsValueType) + { + return false; + } + + foreach (var type in ResolveInheritanceHierarchy(typeRef, weaver)) + { + // only need to check for generic instances, as we're looking for SyncList + if (type.IsGenericInstance) + { + // resolves the instance type to it's generic type definition, for example SyncList to SyncList + var typeDef = type.Resolve(); + if (typeDef.HasGenericParameters && typeDef.FullName == weaver.SyncListType.FullName) + { + return true; + } + } + } + } + catch + { + // sometimes this will fail if we reference a weird library that can't be resolved, so we just swallow that exception and return false + } + + return false; + } + + public static IEnumerable ResolveInheritanceHierarchy(TypeReference type, Weaver weaver) + { + // for value types the hierarchy is pre-defined as " : System.ValueType : System.Object" + if (type.IsValueType) + { + yield return type; + yield return weaver.valueTypeType; + yield return weaver.objectType; + yield break; + } + + // resolve entire hierarchy from to System.Object + while (type != null && type.FullName != weaver.objectType.FullName) + { + yield return type; + + try + { + var typeDef = type.Resolve(); + if (typeDef == null) + { + break; + } + else + { + type = typeDef.BaseType; + } + } + catch + { + // when calling type.Resolve() we can sometimes get an exception if some dependant library + // could not be loaded (for whatever reason) so just swallow it and break out of the loop + break; + } + } + + + yield return weaver.objectType; + } + + public static string DestinationFileFor(string outputDir, string assemblyPath) + { + var fileName = Path.GetFileName(assemblyPath); + Debug.Assert(fileName != null, "fileName != null"); + + return Path.Combine(outputDir, fileName); + } + + public static string PrettyPrintType(TypeReference type) + { + // generic instances, such as List + if (type.IsGenericInstance) + { + var giType = (GenericInstanceType)type; + return giType.Name.Substring(0, giType.Name.Length - 2) + "<" + String.Join(", ", giType.GenericArguments.Select(PrettyPrintType).ToArray()) + ">"; + } + + // generic types, such as List + if (type.HasGenericParameters) + { + return type.Name.Substring(0, type.Name.Length - 2) + "<" + String.Join(", ", type.GenericParameters.Select(x => x.Name).ToArray()) + ">"; + } + + // non-generic type such as Int + return type.Name; + } + + public static ReaderParameters ReaderParameters(string assemblyPath, IEnumerable extraPaths, IAssemblyResolver assemblyResolver, string unityEngineDLLPath, string unityUNetDLLPath) + { + var parameters = new ReaderParameters() {ReadWrite = true}; + if (assemblyResolver == null) + assemblyResolver = new DefaultAssemblyResolver(); + var helper = new AddSearchDirectoryHelper(assemblyResolver); + helper.AddSearchDirectory(Path.GetDirectoryName(assemblyPath)); + helper.AddSearchDirectory(Helpers.UnityEngineDLLDirectoryName()); + helper.AddSearchDirectory(Path.GetDirectoryName(unityEngineDLLPath)); + helper.AddSearchDirectory(Path.GetDirectoryName(unityUNetDLLPath)); + if (extraPaths != null) + { + foreach (var path in extraPaths) + helper.AddSearchDirectory(path); + } + parameters.AssemblyResolver = assemblyResolver; + parameters.SymbolReaderProvider = GetSymbolReaderProvider(assemblyPath); + return parameters; + } + + public static WriterParameters GetWriterParameters(ReaderParameters readParams) + { + var writeParams = new WriterParameters(); + if (readParams.SymbolReaderProvider is PdbReaderProvider) + { + //Log("Will export symbols of pdb format"); + writeParams.SymbolWriterProvider = new PdbWriterProvider(); + } + else if (readParams.SymbolReaderProvider is MdbReaderProvider) + { + //Log("Will export symbols of mdb format"); + writeParams.SymbolWriterProvider = new MdbWriterProvider(); + } + return writeParams; + } + + public static TypeReference MakeGenericType(TypeReference self, params TypeReference[] arguments) + { + if (self.GenericParameters.Count != arguments.Length) + throw new ArgumentException(); + + var instance = new GenericInstanceType(self); + foreach (var argument in arguments) + instance.GenericArguments.Add(argument); + + return instance; + } + + // used to get a specialized method on a generic class, such as SyncList::HandleMsg() + public static MethodReference MakeHostInstanceGeneric(MethodReference self, params TypeReference[] arguments) + { + var reference = new MethodReference(self.Name, self.ReturnType, MakeGenericType(self.DeclaringType, arguments)) + { + HasThis = self.HasThis, + ExplicitThis = self.ExplicitThis, + CallingConvention = self.CallingConvention + }; + + foreach (var parameter in self.Parameters) + reference.Parameters.Add(new ParameterDefinition(parameter.ParameterType)); + + foreach (var genericParameter in self.GenericParameters) + reference.GenericParameters.Add(new GenericParameter(genericParameter.Name, reference)); + + return reference; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/Tools/Weaver/MessageClassProcessor.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/Tools/Weaver/MessageClassProcessor.cs new file mode 100644 index 00000000..37c1867a --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/Tools/Weaver/MessageClassProcessor.cs @@ -0,0 +1,154 @@ +using System; +using Mono.Cecil; +using Mono.Cecil.Cil; + +namespace Unity.UNetWeaver +{ + class MessageClassProcessor + { + TypeDefinition m_td; + Weaver m_Weaver; + + public MessageClassProcessor(TypeDefinition td, Weaver weaver) + { + m_td = td; + m_Weaver = weaver; + m_Weaver.DLog(td, "MessageClassProcessor for " + td.Name); + } + + public void Process() + { + m_Weaver.DLog(m_td, "MessageClassProcessor Start"); + + m_Weaver.ResetRecursionCount(); + + GenerateSerialization(); + if (m_Weaver.fail) + { + return; + } + + GenerateDeSerialization(); + m_Weaver.DLog(m_td, "MessageClassProcessor Done"); + } + + void GenerateSerialization() + { + m_Weaver.DLog(m_td, " GenerateSerialization"); + foreach (var m in m_td.Methods) + { + if (m.Name == "Serialize") + return; + } + + if (m_td.Fields.Count == 0) + { + return; + } + + // check for self-referencing types + foreach (var field in m_td.Fields) + { + if (field.FieldType.FullName == m_td.FullName) + { + m_Weaver.fail = true; + Log.Error("GenerateSerialization for " + m_td.Name + " [" + field.FullName + "]. [MessageBase] member cannot be self referencing."); + return; + } + } + + MethodDefinition serializeFunc = new MethodDefinition("Serialize", MethodAttributes.Public | + MethodAttributes.Virtual | + MethodAttributes.HideBySig, + m_Weaver.voidType); + + serializeFunc.Parameters.Add(new ParameterDefinition("writer", ParameterAttributes.None, m_Weaver.m_ScriptDef.MainModule.ImportReference(m_Weaver.NetworkWriterType))); + ILProcessor serWorker = serializeFunc.Body.GetILProcessor(); + + foreach (var field in m_td.Fields) + { + if (field.IsStatic || field.IsPrivate || field.IsSpecialName) + continue; + + if (field.FieldType.Resolve().HasGenericParameters) + { + m_Weaver.fail = true; + Log.Error("GenerateSerialization for " + m_td.Name + " [" + field.FieldType + "/" + field.FieldType.FullName + "]. [MessageBase] member cannot have generic parameters."); + return; + } + + if (field.FieldType.Resolve().IsInterface) + { + m_Weaver.fail = true; + Log.Error("GenerateSerialization for " + m_td.Name + " [" + field.FieldType + "/" + field.FieldType.FullName + "]. [MessageBase] member cannot be an interface."); + return; + } + + MethodReference writeFunc = m_Weaver.GetWriteFunc(field.FieldType); + if (writeFunc != null) + { + serWorker.Append(serWorker.Create(OpCodes.Ldarg_1)); + serWorker.Append(serWorker.Create(OpCodes.Ldarg_0)); + serWorker.Append(serWorker.Create(OpCodes.Ldfld, field)); + serWorker.Append(serWorker.Create(OpCodes.Call, writeFunc)); + } + else + { + m_Weaver.fail = true; + Log.Error("GenerateSerialization for " + m_td.Name + " unknown type [" + field.FieldType + "/" + field.FieldType.FullName + "]. [MessageBase] member variables must be basic types."); + return; + } + } + serWorker.Append(serWorker.Create(OpCodes.Ret)); + + m_td.Methods.Add(serializeFunc); + } + + void GenerateDeSerialization() + { + m_Weaver.DLog(m_td, " GenerateDeserialization"); + foreach (var m in m_td.Methods) + { + if (m.Name == "Deserialize") + return; + } + + if (m_td.Fields.Count == 0) + { + return; + } + + MethodDefinition serializeFunc = new MethodDefinition("Deserialize", MethodAttributes.Public | + MethodAttributes.Virtual | + MethodAttributes.HideBySig, + m_Weaver.voidType); + + serializeFunc.Parameters.Add(new ParameterDefinition("reader", ParameterAttributes.None, m_Weaver.m_ScriptDef.MainModule.ImportReference(m_Weaver.NetworkReaderType))); + ILProcessor serWorker = serializeFunc.Body.GetILProcessor(); + + foreach (var field in m_td.Fields) + { + if (field.IsStatic || field.IsPrivate || field.IsSpecialName) + continue; + + MethodReference readerFunc = m_Weaver.GetReadFunc(field.FieldType); + if (readerFunc != null) + { + serWorker.Append(serWorker.Create(OpCodes.Ldarg_0)); + serWorker.Append(serWorker.Create(OpCodes.Ldarg_1)); + serWorker.Append(serWorker.Create(OpCodes.Call, readerFunc)); + serWorker.Append(serWorker.Create(OpCodes.Stfld, field)); + } + else + { + m_Weaver.fail = true; + Log.Error("GenerateDeSerialization for " + m_td.Name + " unknown type [" + field.FieldType + "]. [SyncVar] member variables must be basic types."); + return; + } + } + serWorker.Append(serWorker.Create(OpCodes.Ret)); + + m_td.Methods.Add(serializeFunc); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/Tools/Weaver/MonoBehaviourProcessor.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/Tools/Weaver/MonoBehaviourProcessor.cs new file mode 100644 index 00000000..e0770d42 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/Tools/Weaver/MonoBehaviourProcessor.cs @@ -0,0 +1,97 @@ +using System; +using System.Linq; +using Mono.Cecil; + +namespace Unity.UNetWeaver +{ + class MonoBehaviourProcessor + { + TypeDefinition m_td; + Weaver m_Weaver; + + public MonoBehaviourProcessor(TypeDefinition td, Weaver weaver) + { + m_td = td; + m_Weaver = weaver; + } + + public void Process() + { + ProcessSyncVars(); + ProcessMethods(); + } + + void ProcessSyncVars() + { + // find syncvars + foreach (FieldDefinition fd in m_td.Fields) + { + foreach (var ca in fd.CustomAttributes) + { + if (ca.AttributeType.FullName == m_Weaver.SyncVarType.FullName) + { + Log.Error("Script " + m_td.FullName + " uses [SyncVar] " + fd.Name + " but is not a NetworkBehaviour."); + m_Weaver.fail = true; + } + } + + if (Helpers.InheritsFromSyncList(fd.FieldType, m_Weaver)) + { + Log.Error(string.Format("Script {0} defines field {1} with type {2}, but it's not a NetworkBehaviour", m_td.FullName, fd.Name, Helpers.PrettyPrintType(fd.FieldType))); + m_Weaver.fail = true; + } + } + } + + void ProcessMethods() + { + // find command and RPC functions + foreach (MethodDefinition md in m_td.Methods) + { + foreach (var ca in md.CustomAttributes) + { + if (ca.AttributeType.FullName == m_Weaver.CommandType.FullName) + { + Log.Error("Script " + m_td.FullName + " uses [Command] " + md.Name + " but is not a NetworkBehaviour."); + m_Weaver.fail = true; + } + + if (ca.AttributeType.FullName == m_Weaver.ClientRpcType.FullName) + { + Log.Error("Script " + m_td.FullName + " uses [ClientRpc] " + md.Name + " but is not a NetworkBehaviour."); + m_Weaver.fail = true; + } + + if (ca.AttributeType.FullName == m_Weaver.TargetRpcType.FullName) + { + Log.Error("Script " + m_td.FullName + " uses [TargetRpc] " + md.Name + " but is not a NetworkBehaviour."); + m_Weaver.fail = true; + } + + var attrName = ca.Constructor.DeclaringType.ToString(); + + if (attrName == "UnityEngine.Networking.ServerAttribute") + { + Log.Error("Script " + m_td.FullName + " uses the attribute [Server] on the method " + md.Name + " but is not a NetworkBehaviour."); + m_Weaver.fail = true; + } + else if (attrName == "UnityEngine.Networking.ServerCallbackAttribute") + { + Log.Error("Script " + m_td.FullName + " uses the attribute [ServerCallback] on the method " + md.Name + " but is not a NetworkBehaviour."); + m_Weaver.fail = true; + } + else if (attrName == "UnityEngine.Networking.ClientAttribute") + { + Log.Error("Script " + m_td.FullName + " uses the attribute [Client] on the method " + md.Name + " but is not a NetworkBehaviour."); + m_Weaver.fail = true; + } + else if (attrName == "UnityEngine.Networking.ClientCallbackAttribute") + { + Log.Error("Script " + m_td.FullName + " uses the attribute [ClientCallback] on the method " + md.Name + " but is not a NetworkBehaviour."); + m_Weaver.fail = true; + } + } + } + } + }; +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/Tools/Weaver/Program.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/Tools/Weaver/Program.cs new file mode 100644 index 00000000..1ab0e63a --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/Tools/Weaver/Program.cs @@ -0,0 +1,62 @@ +using System; +using System.Collections.Generic; +using System.IO; +using Mono.Cecil; + +namespace Unity.UNetWeaver +{ + public static class Log + { + public static Action WarningMethod; + public static Action ErrorMethod; + + public static void Warning(string msg) + { + WarningMethod("UNetWeaver warning: " + msg); + } + + public static void Error(string msg) + { + ErrorMethod("UNetWeaver error: " + msg); + } + } + + public class Program + { + public static bool Process(string unityEngine, string unetDLL, string outputDirectory, string[] assemblies, string[] extraAssemblyPaths, Action printWarning, Action printError) + { + CheckDLLPath(unityEngine); + CheckDLLPath(unetDLL); + CheckOutputDirectory(outputDirectory); + CheckAssemblies(assemblies); + Log.WarningMethod = printWarning; + Log.ErrorMethod = printError; + Weaver weaver = new Weaver(); + return weaver.WeaveAssemblies(assemblies, extraAssemblyPaths, null, outputDirectory, unityEngine, unetDLL); + } + + private static void CheckDLLPath(string path) + { + if (!File.Exists(path)) + throw new Exception("dll could not be located at " + path + "!"); + } + + private static void CheckAssemblies(IEnumerable assemblyPaths) + { + foreach (var assemblyPath in assemblyPaths) + CheckAssemblyPath(assemblyPath); + } + + private static void CheckAssemblyPath(string assemblyPath) + { + if (!File.Exists(assemblyPath)) + throw new Exception("Assembly " + assemblyPath + " does not exist!"); + } + + private static void CheckOutputDirectory(string outputDir) + { + if (!Directory.Exists(outputDir)) + Directory.CreateDirectory(outputDir); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/Tools/Weaver/SyncListStructProcessor.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/Tools/Weaver/SyncListStructProcessor.cs new file mode 100644 index 00000000..81a457d5 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/Tools/Weaver/SyncListStructProcessor.cs @@ -0,0 +1,341 @@ +using System; +using Mono.Cecil; +using Mono.Cecil.Cil; + +namespace Unity.UNetWeaver +{ + class SyncListStructProcessor + { + TypeDefinition m_TypeDef; + TypeReference m_ItemType; + Weaver m_Weaver; + const MethodAttributes kPublicStaticHide = MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.HideBySig; + const MethodAttributes kPublicVirtualHide = MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig; + + public SyncListStructProcessor(TypeDefinition typeDef, Weaver weaver) + { + m_TypeDef = typeDef; + m_Weaver = weaver; + m_Weaver.DLog(typeDef, "SyncListStructProcessor for " + typeDef.Name); + } + + public void Process() + { + // find item type + var gt = (GenericInstanceType)m_TypeDef.BaseType; + if (gt.GenericArguments.Count == 0) + { + m_Weaver.fail = true; + Log.Error("SyncListStructProcessor no generic args"); + return; + } + m_ItemType = m_Weaver.m_ScriptDef.MainModule.ImportReference(gt.GenericArguments[0]); + + m_Weaver.DLog(m_TypeDef, "SyncListStructProcessor Start item:" + m_ItemType.FullName); + + m_Weaver.ResetRecursionCount(); + var writeItemFunc = GenerateSerialization(); + if (m_Weaver.fail) + { + return; + } + + var readItemFunc = GenerateDeserialization(); + + if (readItemFunc == null || writeItemFunc == null) + return; + + GenerateReadFunc(readItemFunc); + GenerateWriteFunc(writeItemFunc); + + m_Weaver.DLog(m_TypeDef, "SyncListStructProcessor Done"); + } + + /* deserialization of entire list. generates code like: + * + static public void ReadStructBuf(NetworkReader reader, SyncListBuf instance) + { + ushort count = reader.ReadUInt16(); + instance.Clear() + for (ushort i = 0; i < count; i++) + { + instance.AddInternal(instance.DeserializeItem(reader)); + } + } + */ + void GenerateReadFunc(MethodReference readItemFunc) + { + var functionName = "_ReadStruct" + m_TypeDef.Name + "_"; + if (m_TypeDef.DeclaringType != null) + { + functionName += m_TypeDef.DeclaringType.Name; + } + else + { + functionName += "None"; + } + + // create new reader for this type + MethodDefinition readerFunc = new MethodDefinition(functionName, kPublicStaticHide, m_Weaver.voidType); + + readerFunc.Parameters.Add(new ParameterDefinition("reader", ParameterAttributes.None, m_Weaver.m_ScriptDef.MainModule.ImportReference(m_Weaver.NetworkReaderType))); + readerFunc.Parameters.Add(new ParameterDefinition("instance", ParameterAttributes.None, m_TypeDef)); + + readerFunc.Body.Variables.Add(new VariableDefinition(m_Weaver.uint16Type)); + readerFunc.Body.Variables.Add(new VariableDefinition(m_Weaver.uint16Type)); + readerFunc.Body.InitLocals = true; + + ILProcessor worker = readerFunc.Body.GetILProcessor(); + + worker.Append(worker.Create(OpCodes.Ldarg_0)); + worker.Append(worker.Create(OpCodes.Callvirt, m_Weaver.NetworkReadUInt16)); + worker.Append(worker.Create(OpCodes.Stloc_0)); + + // Call Clear() from the base class + worker.Append(worker.Create(OpCodes.Ldarg_1)); + MethodReference genericClearMethod = Helpers.MakeHostInstanceGeneric(m_Weaver.SyncListClear, m_ItemType); + worker.Append(worker.Create(OpCodes.Callvirt, genericClearMethod)); + + worker.Append(worker.Create(OpCodes.Ldc_I4_0)); + worker.Append(worker.Create(OpCodes.Stloc_1)); + var loopCheckLabel = worker.Create(OpCodes.Nop); + worker.Append(worker.Create(OpCodes.Br, loopCheckLabel)); + + // loop body + var loopHeadLabel = worker.Create(OpCodes.Nop); + worker.Append(loopHeadLabel); + + worker.Append(worker.Create(OpCodes.Ldarg_1)); + worker.Append(worker.Create(OpCodes.Ldarg_1)); + + worker.Append(worker.Create(OpCodes.Ldarg_0)); + worker.Append(worker.Create(OpCodes.Callvirt, readItemFunc)); + + // call the generic AddInternal from the base class + var addInternal = m_Weaver.ResolveMethod(m_Weaver.SyncListStructType, "AddInternal"); + var addInternalTyped = Helpers.MakeHostInstanceGeneric(addInternal, m_ItemType); + worker.Append(worker.Create(OpCodes.Callvirt, addInternalTyped)); + + worker.Append(worker.Create(OpCodes.Ldloc_1)); + worker.Append(worker.Create(OpCodes.Ldc_I4_1)); + worker.Append(worker.Create(OpCodes.Add)); + worker.Append(worker.Create(OpCodes.Conv_U2)); + worker.Append(worker.Create(OpCodes.Stloc_1)); + + // loop check + worker.Append(loopCheckLabel); + worker.Append(worker.Create(OpCodes.Ldloc_1)); + worker.Append(worker.Create(OpCodes.Ldloc_0)); + worker.Append(worker.Create(OpCodes.Blt, loopHeadLabel)); + + // done + //worker.Append(worker.Create(OpCodes.Ldloc_1)); + worker.Append(worker.Create(OpCodes.Ret)); + + m_Weaver.RegisterReadByReferenceFunc(m_TypeDef.FullName, readerFunc); + } + + /*serialization of entire list. generates code like: + * + static public void WriteStructBuf(NetworkWriter writer, SyncListBuf items) + { + ushort count = (ushort)items.Count; + writer.Write(count); + for (ushort i=0; i < count; i++) + { + items.SerializeItem(writer, items.GetItem(i)); + } + } + */ + void GenerateWriteFunc(MethodReference writeItemFunc) + { + var functionName = "_WriteStruct" + m_TypeDef.GetElementType().Name + "_"; + if (m_TypeDef.DeclaringType != null) + { + functionName += m_TypeDef.DeclaringType.Name; + } + else + { + functionName += "None"; + } + + // create new writer for this type + MethodDefinition writerFunc = new MethodDefinition(functionName, kPublicStaticHide, m_Weaver.voidType); + + writerFunc.Parameters.Add(new ParameterDefinition("writer", ParameterAttributes.None, m_Weaver.m_ScriptDef.MainModule.ImportReference(m_Weaver.NetworkWriterType))); + writerFunc.Parameters.Add(new ParameterDefinition("value", ParameterAttributes.None, m_Weaver.m_ScriptDef.MainModule.ImportReference(m_TypeDef))); + + writerFunc.Body.Variables.Add(new VariableDefinition(m_Weaver.uint16Type)); + writerFunc.Body.Variables.Add(new VariableDefinition(m_Weaver.uint16Type)); + writerFunc.Body.InitLocals = true; + + ILProcessor worker = writerFunc.Body.GetILProcessor(); + + worker.Append(worker.Create(OpCodes.Ldarg_1)); + + // call the generic Count from the base class + var getCount = m_Weaver.ResolveMethod(m_Weaver.SyncListStructType, "get_Count"); + var getCountTyped = Helpers.MakeHostInstanceGeneric(getCount, m_ItemType); + worker.Append(worker.Create(OpCodes.Callvirt, getCountTyped)); + + worker.Append(worker.Create(OpCodes.Stloc_0)); + worker.Append(worker.Create(OpCodes.Ldarg_0)); + worker.Append(worker.Create(OpCodes.Ldloc_0)); + worker.Append(worker.Create(OpCodes.Callvirt, m_Weaver.NetworkWriteUInt16)); + worker.Append(worker.Create(OpCodes.Ldc_I4_0)); + worker.Append(worker.Create(OpCodes.Stloc_1)); + + var loopCheckLabel = worker.Create(OpCodes.Nop); + worker.Append(worker.Create(OpCodes.Br, loopCheckLabel)); + + //loop start + var loopStartLabel = worker.Create(OpCodes.Nop); + worker.Append(loopStartLabel); + + worker.Append(worker.Create(OpCodes.Ldarg_1)); + worker.Append(worker.Create(OpCodes.Ldarg_0)); + worker.Append(worker.Create(OpCodes.Ldarg_1)); + worker.Append(worker.Create(OpCodes.Ldloc_1)); + + // call the generic [] from the base class + var getItem = m_Weaver.ResolveMethod(m_Weaver.SyncListStructType, "GetItem"); + var getItemTyped = Helpers.MakeHostInstanceGeneric(getItem, m_ItemType); + worker.Append(worker.Create(OpCodes.Callvirt, getItemTyped)); + worker.Append(worker.Create(OpCodes.Callvirt, writeItemFunc)); + + worker.Append(worker.Create(OpCodes.Ldloc_1)); + worker.Append(worker.Create(OpCodes.Ldc_I4_1)); + worker.Append(worker.Create(OpCodes.Add)); + worker.Append(worker.Create(OpCodes.Conv_U2)); + worker.Append(worker.Create(OpCodes.Stloc_1)); + + worker.Append(loopCheckLabel); + worker.Append(worker.Create(OpCodes.Ldloc_1)); + worker.Append(worker.Create(OpCodes.Ldloc_0)); + worker.Append(worker.Create(OpCodes.Blt, loopStartLabel)); + + worker.Append(worker.Create(OpCodes.Ret)); + + m_Weaver.RegisterWriteFunc(m_TypeDef.FullName, writerFunc); + } + + // serialization of individual element + MethodReference GenerateSerialization() + { + m_Weaver.DLog(m_TypeDef, " GenerateSerialization"); + foreach (var m in m_TypeDef.Methods) + { + if (m.Name == "SerializeItem") + return m; + } + + MethodDefinition serializeFunc = new MethodDefinition("SerializeItem", kPublicVirtualHide, m_Weaver.voidType); + + serializeFunc.Parameters.Add(new ParameterDefinition("writer", ParameterAttributes.None, m_Weaver.m_ScriptDef.MainModule.ImportReference(m_Weaver.NetworkWriterType))); + serializeFunc.Parameters.Add(new ParameterDefinition("item", ParameterAttributes.None, m_ItemType)); + ILProcessor serWorker = serializeFunc.Body.GetILProcessor(); + + if (m_ItemType.IsGenericInstance) + { + m_Weaver.fail = true; + Log.Error("GenerateSerialization for " + Helpers.PrettyPrintType(m_ItemType) + " failed. Struct passed into SyncListStruct can't have generic parameters"); + return null; + } + + foreach (var field in m_ItemType.Resolve().Fields) + { + if (field.IsStatic || field.IsPrivate || field.IsSpecialName) + continue; + + var importedField = m_Weaver.m_ScriptDef.MainModule.ImportReference(field); + var ft = importedField.FieldType.Resolve(); + + if (ft.HasGenericParameters) + { + m_Weaver.fail = true; + Log.Error("GenerateSerialization for " + m_TypeDef.Name + " [" + ft + "/" + ft.FullName + "]. UNet [MessageBase] member cannot have generic parameters."); + return null; + } + + if (ft.IsInterface) + { + m_Weaver.fail = true; + Log.Error("GenerateSerialization for " + m_TypeDef.Name + " [" + ft + "/" + ft.FullName + "]. UNet [MessageBase] member cannot be an interface."); + return null; + } + + MethodReference writeFunc = m_Weaver.GetWriteFunc(field.FieldType); + if (writeFunc != null) + { + serWorker.Append(serWorker.Create(OpCodes.Ldarg_1)); + serWorker.Append(serWorker.Create(OpCodes.Ldarg_2)); + serWorker.Append(serWorker.Create(OpCodes.Ldfld, importedField)); + serWorker.Append(serWorker.Create(OpCodes.Call, writeFunc)); + } + else + { + m_Weaver.fail = true; + Log.Error("GenerateSerialization for " + m_TypeDef.Name + " unknown type [" + ft + "/" + ft.FullName + "]. UNet [MessageBase] member variables must be basic types."); + return null; + } + } + serWorker.Append(serWorker.Create(OpCodes.Ret)); + + m_TypeDef.Methods.Add(serializeFunc); + return serializeFunc; + } + + MethodReference GenerateDeserialization() + { + m_Weaver.DLog(m_TypeDef, " GenerateDeserialization"); + foreach (var m in m_TypeDef.Methods) + { + if (m.Name == "DeserializeItem") + return m; + } + + MethodDefinition serializeFunc = new MethodDefinition("DeserializeItem", kPublicVirtualHide, m_ItemType); + + serializeFunc.Parameters.Add(new ParameterDefinition("reader", ParameterAttributes.None, m_Weaver.m_ScriptDef.MainModule.ImportReference(m_Weaver.NetworkReaderType))); + + ILProcessor serWorker = serializeFunc.Body.GetILProcessor(); + + serWorker.Body.InitLocals = true; + serWorker.Body.Variables.Add(new VariableDefinition(m_ItemType)); + + // init item instance + serWorker.Append(serWorker.Create(OpCodes.Ldloca, 0)); + serWorker.Append(serWorker.Create(OpCodes.Initobj, m_ItemType)); + + + foreach (var field in m_ItemType.Resolve().Fields) + { + if (field.IsStatic || field.IsPrivate || field.IsSpecialName) + continue; + + var importedField = m_Weaver.m_ScriptDef.MainModule.ImportReference(field); + var ft = importedField.FieldType.Resolve(); + + MethodReference readerFunc = m_Weaver.GetReadFunc(field.FieldType); + if (readerFunc != null) + { + serWorker.Append(serWorker.Create(OpCodes.Ldloca, 0)); + serWorker.Append(serWorker.Create(OpCodes.Ldarg_1)); + serWorker.Append(serWorker.Create(OpCodes.Call, readerFunc)); + serWorker.Append(serWorker.Create(OpCodes.Stfld, importedField)); + } + else + { + m_Weaver.fail = true; + Log.Error("GenerateDeserialization for " + m_TypeDef.Name + " unknown type [" + ft + "]. UNet [SyncVar] member variables must be basic types."); + return null; + } + } + serWorker.Append(serWorker.Create(OpCodes.Ldloc_0)); + serWorker.Append(serWorker.Create(OpCodes.Ret)); + + m_TypeDef.Methods.Add(serializeFunc); + return serializeFunc; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/Tools/Weaver/UNetBehaviourProcessor.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/Tools/Weaver/UNetBehaviourProcessor.cs new file mode 100644 index 00000000..2c303b68 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/Tools/Weaver/UNetBehaviourProcessor.cs @@ -0,0 +1,2352 @@ +using System; +using System.Linq; +using System.Collections.Generic; +using Mono.Cecil; +using Mono.Cecil.Cil; + +namespace Unity.UNetWeaver +{ + class NetworkBehaviourProcessor + { + List m_SyncVars = new List(); + List m_SyncLists = new List(); + List m_SyncVarNetIds = new List(); + List m_Cmds = new List(); + List m_Rpcs = new List(); + List m_TargetRpcs = new List(); + List m_Events = new List(); + List m_SyncListStaticFields = new List(); + List m_CmdInvocationFuncs = new List(); + List m_SyncListInvocationFuncs = new List(); + List m_RpcInvocationFuncs = new List(); + List m_TargetRpcInvocationFuncs = new List(); + List m_EventInvocationFuncs = new List(); + + List m_CmdCallFuncs = new List(); + List m_RpcCallFuncs = new List(); + List m_TargetRpcCallFuncs = new List(); + + const int k_SyncVarLimit = 32; + int m_QosChannel; + + Weaver m_Weaver; + TypeDefinition m_td; + int m_NetIdFieldCounter; + + const string k_CmdPrefix = "InvokeCmd"; + const string k_RpcPrefix = "InvokeRpc"; + const string k_TargetRpcPrefix = "InvokeTargetRpc"; + + public NetworkBehaviourProcessor(TypeDefinition td, Weaver weaver) + { + m_td = td; + m_Weaver = weaver; + m_Weaver.DLog(td, "NetworkBehaviourProcessor"); + } + + public void Process() + { + if (m_td.HasGenericParameters) + { + m_Weaver.fail = true; + Log.Error("NetworkBehaviour " + m_td.Name + " cannot have generic parameters"); + return; + } + m_Weaver.DLog(m_td, "Process Start"); + ProcessVersion(); + ProcessSyncVars(); + m_Weaver.ResetRecursionCount(); + + ProcessMethods(); + + ProcessEvents(); + if (m_Weaver.fail) + { + return; + } + GenerateNetworkSettings(); + GenerateConstants(); + + m_Weaver.ResetRecursionCount(); + GenerateSerialization(); + if (m_Weaver.fail) + { + return; + } + + GenerateDeSerialization(); + GeneratePreStartClient(); + m_Weaver.DLog(m_td, "Process Done"); + } + + void WriteClientActiveCheck(ILProcessor worker, string mdName, Instruction label, string errString) + { + // client active check + worker.Append(worker.Create(OpCodes.Call, m_Weaver.NetworkClientGetActive)); + worker.Append(worker.Create(OpCodes.Brtrue, label)); + + worker.Append(worker.Create(OpCodes.Ldstr, errString + " " + mdName + " called on server.")); + worker.Append(worker.Create(OpCodes.Call, m_Weaver.logErrorReference)); + worker.Append(worker.Create(OpCodes.Ret)); + worker.Append(label); + } + + void WriteServerActiveCheck(ILProcessor worker, string mdName, Instruction label, string errString) + { + // server active check + worker.Append(worker.Create(OpCodes.Call, m_Weaver.NetworkServerGetActive)); + worker.Append(worker.Create(OpCodes.Brtrue, label)); + + worker.Append(worker.Create(OpCodes.Ldstr, errString + " " + mdName + " called on client.")); + worker.Append(worker.Create(OpCodes.Call, m_Weaver.logErrorReference)); + worker.Append(worker.Create(OpCodes.Ret)); + worker.Append(label); + } + + void WriteSetupLocals(ILProcessor worker) + { + worker.Body.InitLocals = true; + worker.Body.Variables.Add(new VariableDefinition(m_Weaver.m_ScriptDef.MainModule.ImportReference(m_Weaver.NetworkWriterType))); + } + + void WriteCreateWriter(ILProcessor worker) + { + // create writer + worker.Append(worker.Create(OpCodes.Newobj, m_Weaver.NetworkWriterCtor)); + worker.Append(worker.Create(OpCodes.Stloc_0)); + worker.Append(worker.Create(OpCodes.Ldloc_0)); + } + + void WriteMessageSize(ILProcessor worker) + { + //write size + worker.Append(worker.Create(OpCodes.Ldc_I4_0)); + worker.Append(worker.Create(OpCodes.Callvirt, m_Weaver.NetworkWriterWriteInt16)); + } + + void WriteMessageId(ILProcessor worker, int msgId) + { + // write msg id + worker.Append(worker.Create(OpCodes.Ldloc_0)); + worker.Append(worker.Create(OpCodes.Ldc_I4, msgId)); + worker.Append(worker.Create(OpCodes.Conv_U2)); + worker.Append(worker.Create(OpCodes.Callvirt, m_Weaver.NetworkWriterWriteInt16)); + } + + bool WriteArguments(ILProcessor worker, MethodDefinition md, string errString, bool skipFirst) + { + // write each argument + short argNum = 1; + foreach (ParameterDefinition pd in md.Parameters) + { + if (argNum == 1 && skipFirst) + { + argNum += 1; + continue; + } + + MethodReference writeFunc = m_Weaver.GetWriteFunc(pd.ParameterType); + if (writeFunc == null) + { + Log.Error("WriteArguments for " + md.Name + " type " + pd.ParameterType + " not supported"); + m_Weaver.fail = true; + return false; + } + // use built-in writer func on writer object + worker.Append(worker.Create(OpCodes.Ldloc_0)); // writer object + worker.Append(worker.Create(OpCodes.Ldarg, argNum)); // argument + worker.Append(worker.Create(OpCodes.Call, writeFunc));// call writer func on writer object + argNum += 1; + } + return true; + } + + void ProcessVersion() + { + foreach (MethodDefinition md in m_td.Methods) + { + if (md.Name == "UNetVersion") + { + return; + } + } + + MethodDefinition versionMethod = new MethodDefinition("UNetVersion", MethodAttributes.Private, m_Weaver.voidType); + ILProcessor worker = versionMethod.Body.GetILProcessor(); + worker.Append(worker.Create(OpCodes.Ret)); + m_td.Methods.Add(versionMethod); + } + + void GenerateConstants() + { + if (m_Cmds.Count == 0 && m_Rpcs.Count == 0 && m_TargetRpcs.Count == 0 && m_Events.Count == 0 && m_SyncLists.Count == 0) + return; + + m_Weaver.DLog(m_td, " GenerateConstants "); + + // find static constructor + MethodDefinition cctor = null; + bool cctorFound = false; + foreach (MethodDefinition md in m_td.Methods) + { + if (md.Name == ".cctor") + { + cctor = md; + cctorFound = true; + } + } + if (cctor != null) + { + // remove the return opcode from end of function. will add our own later. + if (cctor.Body.Instructions.Count != 0) + { + Instruction ret = cctor.Body.Instructions[cctor.Body.Instructions.Count - 1]; + if (ret.OpCode == OpCodes.Ret) + { + cctor.Body.Instructions.RemoveAt(cctor.Body.Instructions.Count - 1); + } + else + { + Log.Error("No cctor for " + m_td.Name); + m_Weaver.fail = true; + return; + } + } + } + else + { + // make one! + cctor = new MethodDefinition(".cctor", MethodAttributes.Private | + MethodAttributes.HideBySig | + MethodAttributes.SpecialName | + MethodAttributes.RTSpecialName | + MethodAttributes.Static, + m_Weaver.voidType); + } + + // find instance constructor + MethodDefinition ctor = null; + + foreach (MethodDefinition md in m_td.Methods) + { + if (md.Name == ".ctor") + { + ctor = md; + + var ret = ctor.Body.Instructions[ctor.Body.Instructions.Count - 1]; + if (ret.OpCode == OpCodes.Ret) + { + ctor.Body.Instructions.RemoveAt(ctor.Body.Instructions.Count - 1); + } + else + { + m_Weaver.fail = true; + Log.Error("No ctor for " + m_td.Name); + return; + } + + break; + } + } + + if (ctor == null) + { + m_Weaver.fail = true; + Log.Error("No ctor for " + m_td.Name); + return; + } + + ILProcessor ctorWorker = ctor.Body.GetILProcessor(); + ILProcessor cctorWorker = cctor.Body.GetILProcessor(); + + int cmdIndex = 0; + foreach (MethodDefinition md in m_Cmds) + { + FieldReference cmdConstant = m_Weaver.ResolveField(m_td, "kCmd" + md.Name); + + int cmdHash = GetHashCode(m_td.Name + ":Cmd:" + md.Name); + cctorWorker.Append(cctorWorker.Create(OpCodes.Ldc_I4, cmdHash)); + cctorWorker.Append(cctorWorker.Create(OpCodes.Stsfld, cmdConstant)); + //m_Weaver.DLog(m_td, " Constant " + m_td.Name + ":Cmd:" + md.Name); + + GenerateCommandDelegate(cctorWorker, m_Weaver.registerCommandDelegateReference, m_CmdInvocationFuncs[cmdIndex], cmdConstant); + cmdIndex += 1; + } + + int rpcIndex = 0; + foreach (MethodDefinition md in m_Rpcs) + { + FieldReference rpcConstant = m_Weaver.ResolveField(m_td, "kRpc" + md.Name); + + int rpcHash = GetHashCode(m_td.Name + ":Rpc:" + md.Name); + cctorWorker.Append(cctorWorker.Create(OpCodes.Ldc_I4, rpcHash)); + cctorWorker.Append(cctorWorker.Create(OpCodes.Stsfld, rpcConstant)); + //m_Weaver.DLog(m_td, " Constant " + m_td.Name + ":Rpc:" + md.Name); + + GenerateCommandDelegate(cctorWorker, m_Weaver.registerRpcDelegateReference, m_RpcInvocationFuncs[rpcIndex], rpcConstant); + rpcIndex += 1; + } + + int targetRpcIndex = 0; + foreach (MethodDefinition md in m_TargetRpcs) + { + FieldReference targetRpcConstant = m_Weaver.ResolveField(m_td, "kTargetRpc" + md.Name); + + int targetRpcHash = GetHashCode(m_td.Name + ":TargetRpc:" + md.Name); + cctorWorker.Append(cctorWorker.Create(OpCodes.Ldc_I4, targetRpcHash)); + cctorWorker.Append(cctorWorker.Create(OpCodes.Stsfld, targetRpcConstant)); + //m_Weaver.DLog(m_td, " Constant " + m_td.Name + ":Rpc:" + md.Name); + + GenerateCommandDelegate(cctorWorker, m_Weaver.registerRpcDelegateReference, m_TargetRpcInvocationFuncs[targetRpcIndex], targetRpcConstant); + targetRpcIndex += 1; + } + + int eventIndex = 0; + foreach (EventDefinition ed in m_Events) + { + FieldReference eventConstant = m_Weaver.ResolveField(m_td, "kEvent" + ed.Name); + + int eventHash = GetHashCode(m_td.Name + ":Event:" + ed.Name); + cctorWorker.Append(cctorWorker.Create(OpCodes.Ldc_I4, eventHash)); + cctorWorker.Append(cctorWorker.Create(OpCodes.Stsfld, eventConstant)); + //m_Weaver.DLog(m_td, " Constant " + m_td.Name + ":Event:" + ed.Name); + + GenerateCommandDelegate(cctorWorker, m_Weaver.registerEventDelegateReference, m_EventInvocationFuncs[eventIndex], eventConstant); + eventIndex += 1; + } + + int syncListIndex = 0; + foreach (FieldDefinition fd in m_SyncLists) + { + FieldReference listConstant = m_Weaver.ResolveField(m_td, "kList" + fd.Name); + + int listHash = GetHashCode(m_td.Name + ":List:" + fd.Name); + cctorWorker.Append(cctorWorker.Create(OpCodes.Ldc_I4, listHash)); + cctorWorker.Append(cctorWorker.Create(OpCodes.Stsfld, listConstant)); + //m_Weaver.DLog(m_td, " Constant " + m_td.Name + ":List:" + fd.Name); + + + GenerateSyncListInstanceInitializer(ctorWorker, fd); + + GenerateCommandDelegate(cctorWorker, m_Weaver.registerSyncListDelegateReference, m_SyncListInvocationFuncs[syncListIndex], listConstant); + syncListIndex += 1; + } + + // register CRC entry + // "NetworkCRC.RegisterBehaviour('MyScript', 2);" + cctorWorker.Append(cctorWorker.Create(OpCodes.Ldstr, m_td.Name)); + cctorWorker.Append(cctorWorker.Create(OpCodes.Ldc_I4, m_QosChannel)); + cctorWorker.Append(cctorWorker.Create(OpCodes.Call, m_Weaver.RegisterBehaviourReference)); + + cctorWorker.Append(cctorWorker.Create(OpCodes.Ret)); + if (!cctorFound) + { + m_td.Methods.Add(cctor); + } + + // finish ctor + ctorWorker.Append(ctorWorker.Create(OpCodes.Ret)); + + // in case class had no cctor, it might have BeforeFieldInit, so injected cctor would be called too late + m_td.Attributes = m_td.Attributes & ~TypeAttributes.BeforeFieldInit; + + if (m_SyncLists.Count == 0) + return; + + // find constructor + MethodDefinition awake = null; + bool awakeFound = false; + foreach (MethodDefinition md in m_td.Methods) + { + if (md.Name == "Awake") + { + awake = md; + awakeFound = true; + } + } + if (awake != null) + { + // remove the return opcode from end of function. will add our own later. + if (awake.Body.Instructions.Count != 0) + { + Instruction ret = awake.Body.Instructions[awake.Body.Instructions.Count - 1]; + if (ret.OpCode == OpCodes.Ret) + { + awake.Body.Instructions.RemoveAt(awake.Body.Instructions.Count - 1); + } + else + { + Log.Error("No awake for " + m_td.Name); + m_Weaver.fail = true; + return; + } + } + } + else + { + awake = new MethodDefinition("Awake", MethodAttributes.Private, m_Weaver.voidType); + } + + ILProcessor awakeWorker = awake.Body.GetILProcessor(); + + if (!awakeFound) + { + // if we're not directly inheriting from NetworkBehaviour, we have to + // go up the inheritance chain and check for awake calls that we are overriding by "mistake" + CheckForCustomBaseClassAwakeMethod(awakeWorker); + } + + int syncListFieldOffset = 0; + foreach (FieldDefinition fd in m_SyncLists) + { + GenerateSyncListInitializer(awakeWorker, fd, syncListFieldOffset); + syncListFieldOffset += 1; + } + awakeWorker.Append(awakeWorker.Create(OpCodes.Ret)); + if (!awakeFound) + { + m_td.Methods.Add(awake); + } + } + + void CheckForCustomBaseClassAwakeMethod(ILProcessor awakeWorker) + { + // start from base type + var t = m_td.BaseType; + + // as long as basetype is not NetworkBehaviour + while (t.FullName != m_Weaver.NetworkBehaviourType.FullName) + { + // check for the first Awake() method in the hierarchy + var awake = t.Resolve().Methods.FirstOrDefault(x => x.Name == "Awake" && !x.HasParameters); + if (awake != null) + { + // if found, invoke it so we don't loose the behaviour by implicitly overriding Awake + awakeWorker.Append(awakeWorker.Create(OpCodes.Ldarg_0)); + awakeWorker.Append(awakeWorker.Create(OpCodes.Call, awake)); + return; + } + t = t.Resolve().BaseType; + } + } + + void GenerateSyncListInstanceInitializer(ILProcessor ctorWorker, FieldDefinition fd) + { + // check the ctor's instructions for an Stfld op-code for this specific sync list field. + foreach (var ins in ctorWorker.Body.Instructions) + { + if (ins.OpCode.Code == Code.Stfld) + { + var field = (FieldDefinition)ins.Operand; + if (field.DeclaringType == fd.DeclaringType && field.Name == fd.Name) + { + // Already initialized by the user in the field definition, e.g: + // public SyncListInt Foo = new SyncListInt(); + return; + } + } + } + + // Not initialized by the user in the field definition, e.g: + // public SyncListInt Foo; + var listCtor = m_Weaver.m_ScriptDef.MainModule.ImportReference(fd.FieldType.Resolve().Methods.First(x => x.Name == ".ctor" && !x.HasParameters)); + + ctorWorker.Append(ctorWorker.Create(OpCodes.Ldarg_0)); + ctorWorker.Append(ctorWorker.Create(OpCodes.Newobj, listCtor)); + ctorWorker.Append(ctorWorker.Create(OpCodes.Stfld, fd)); + } + + /* + // This generates code like: + NetworkBehaviour.RegisterCommandDelegate(base.GetType(), ShipControl.kCmdCmdThrust, new NetworkBehaviour.CmdDelegate(ShipControl.InvokeCmdCmdThrust)); + */ + void GenerateCommandDelegate(ILProcessor awakeWorker, MethodReference registerMethod, MethodDefinition func, FieldReference field) + { + awakeWorker.Append(awakeWorker.Create(OpCodes.Ldtoken, m_td)); + awakeWorker.Append(awakeWorker.Create(OpCodes.Call, m_Weaver.getTypeFromHandleReference)); + awakeWorker.Append(awakeWorker.Create(OpCodes.Ldsfld, field)); + awakeWorker.Append(awakeWorker.Create(OpCodes.Ldnull)); + awakeWorker.Append(awakeWorker.Create(OpCodes.Ldftn, func)); + + awakeWorker.Append(awakeWorker.Create(OpCodes.Newobj, m_Weaver.CmdDelegateConstructor)); + awakeWorker.Append(awakeWorker.Create(OpCodes.Call, registerMethod)); + } + + /* + // generates code like: + m_sizes.InitializeBehaviour(this, km_sizesCmdHash); + */ + void GenerateSyncListInitializer(ILProcessor awakeWorker, FieldReference fd, int index) + { + awakeWorker.Append(awakeWorker.Create(OpCodes.Ldarg_0)); + awakeWorker.Append(awakeWorker.Create(OpCodes.Ldfld, fd)); + awakeWorker.Append(awakeWorker.Create(OpCodes.Ldarg_0)); + awakeWorker.Append(awakeWorker.Create(OpCodes.Ldsfld, m_SyncListStaticFields[index])); + + GenericInstanceType syncListGeneric = (GenericInstanceType)fd.FieldType.Resolve().BaseType; + syncListGeneric = (GenericInstanceType)m_Weaver.m_ScriptDef.MainModule.ImportReference(syncListGeneric); + + TypeReference listValueType = syncListGeneric.GenericArguments[0]; + MethodReference genericInitBehaviourMethod = Helpers.MakeHostInstanceGeneric(m_Weaver.SyncListInitBehaviourReference, listValueType); + awakeWorker.Append(awakeWorker.Create(OpCodes.Callvirt, genericInitBehaviourMethod)); + + m_Weaver.m_ScriptDef.MainModule.ImportReference(genericInitBehaviourMethod); + } + + void GenerateSerialization() + { + m_Weaver.DLog(m_td, " GenerateSerialization"); + + foreach (var m in m_td.Methods) + { + if (m.Name == "OnSerialize") + return; + } + + MethodDefinition serialize = new MethodDefinition("OnSerialize", MethodAttributes.Public | + MethodAttributes.Virtual | + MethodAttributes.HideBySig, + m_Weaver.boolType); + + serialize.Parameters.Add(new ParameterDefinition("writer", ParameterAttributes.None, m_Weaver.m_ScriptDef.MainModule.ImportReference(m_Weaver.NetworkWriterType))); + serialize.Parameters.Add(new ParameterDefinition("forceAll", ParameterAttributes.None, m_Weaver.boolType)); + ILProcessor serWorker = serialize.Body.GetILProcessor(); + + + serialize.Body.InitLocals = true; + VariableDefinition dirtyLocal = new VariableDefinition(m_Weaver.boolType); + + serialize.Body.Variables.Add(dirtyLocal); + + // call base class + bool baseClassSerialize = false; + if (m_td.BaseType.FullName != m_Weaver.NetworkBehaviourType.FullName) + { + MethodReference baseSerialize = m_Weaver.ResolveMethod(m_td.BaseType, "OnSerialize"); + if (baseSerialize != null) + { + VariableDefinition baseResult = new VariableDefinition(m_Weaver.boolType); + serialize.Body.Variables.Add(baseResult); + + serWorker.Append(serWorker.Create(OpCodes.Ldarg_0)); // base + serWorker.Append(serWorker.Create(OpCodes.Ldarg_1)); // writer + serWorker.Append(serWorker.Create(OpCodes.Ldarg_2)); // forceAll + serWorker.Append(serWorker.Create(OpCodes.Call, baseSerialize)); + serWorker.Append(serWorker.Create(OpCodes.Stloc_1)); // set baseResult to result of base.OnSerialize() + baseClassSerialize = true; + } + } + + if (m_SyncVars.Count == 0) + { + if (baseClassSerialize) + { + serWorker.Append(serWorker.Create(OpCodes.Ldloc_0)); + serWorker.Append(serWorker.Create(OpCodes.Ldloc_1)); + serWorker.Append(serWorker.Create(OpCodes.Or)); + } + else + { + serWorker.Append(serWorker.Create(OpCodes.Ldloc_0)); + } + serWorker.Append(serWorker.Create(OpCodes.Ret)); + m_td.Methods.Add(serialize); + return; + } + + // Generates: if (initialState); + Instruction initialStateLabel = serWorker.Create(OpCodes.Nop); + serWorker.Append(serWorker.Create(OpCodes.Ldarg_2)); + serWorker.Append(serWorker.Create(OpCodes.Brfalse, initialStateLabel)); + + foreach (FieldDefinition syncVar in m_SyncVars) + { + serWorker.Append(serWorker.Create(OpCodes.Ldarg_1)); + serWorker.Append(serWorker.Create(OpCodes.Ldarg_0)); + serWorker.Append(serWorker.Create(OpCodes.Ldfld, syncVar)); + MethodReference writeFunc = m_Weaver.GetWriteFunc(syncVar.FieldType); + if (writeFunc != null) + { + serWorker.Append(serWorker.Create(OpCodes.Call, writeFunc)); + } + else + { + m_Weaver.fail = true; + Log.Error("GenerateSerialization for " + m_td.Name + " unknown type [" + syncVar.FieldType + "]. UNet [SyncVar] member variables must be basic types."); + return; + } + } + + serWorker.Append(serWorker.Create(OpCodes.Ldc_I4_1)); + serWorker.Append(serWorker.Create(OpCodes.Ret)); + + // Generates: end if (initialState); + serWorker.Append(initialStateLabel); + + // Generates: dirty = 0; + serWorker.Append(serWorker.Create(OpCodes.Ldc_I4_0)); + serWorker.Append(serWorker.Create(OpCodes.Stloc_0)); + + // write syncvars + int dirtyBit = m_Weaver.GetSyncVarStart(m_td.BaseType.FullName); // start at number of syncvars in parent + foreach (FieldDefinition syncVar in m_SyncVars) + { + Instruction varLabel = serWorker.Create(OpCodes.Nop); + + serWorker.Append(serWorker.Create(OpCodes.Ldarg_0)); + serWorker.Append(serWorker.Create(OpCodes.Call, m_Weaver.NetworkBehaviourDirtyBitsReference)); + serWorker.Append(serWorker.Create(OpCodes.Ldc_I4, 1 << dirtyBit)); + serWorker.Append(serWorker.Create(OpCodes.And)); + serWorker.Append(serWorker.Create(OpCodes.Brfalse, varLabel)); + + WriteDirtyCheck(serWorker, true); + + serWorker.Append(serWorker.Create(OpCodes.Ldarg_1)); + serWorker.Append(serWorker.Create(OpCodes.Ldarg_0)); + serWorker.Append(serWorker.Create(OpCodes.Ldfld, syncVar)); + + MethodReference writeFunc = m_Weaver.GetWriteFunc(syncVar.FieldType); + if (writeFunc != null) + { + serWorker.Append(serWorker.Create(OpCodes.Call, writeFunc)); + } + else + { + Log.Error("GenerateSerialization for " + m_td.Name + " unknown type [" + syncVar.FieldType + "]. UNet [SyncVar] member variables must be basic types."); + m_Weaver.fail = true; + return; + } + serWorker.Append(varLabel); + dirtyBit += 1; + } + + WriteDirtyCheck(serWorker, false); + + if (m_Weaver.generateLogErrors) + { + serWorker.Append(serWorker.Create(OpCodes.Ldstr, "Injected Serialize " + m_td.Name)); + serWorker.Append(serWorker.Create(OpCodes.Call, m_Weaver.logErrorReference)); + } + + if (baseClassSerialize) + { + serWorker.Append(serWorker.Create(OpCodes.Ldloc_0)); + serWorker.Append(serWorker.Create(OpCodes.Ldloc_1)); + serWorker.Append(serWorker.Create(OpCodes.Or)); + } + else + { + serWorker.Append(serWorker.Create(OpCodes.Ldloc_0)); + } + serWorker.Append(serWorker.Create(OpCodes.Ret)); + m_td.Methods.Add(serialize); + } + + void WriteDirtyCheck(ILProcessor serWorker, bool reset) + { + //m_Weaver.DLog(m_td, " GenerateSerialization dirtyCheck"); + + // Generates: if (!dirty) { write dirty bits, set dirty bool } + Instruction dirtyLabel = serWorker.Create(OpCodes.Nop); + serWorker.Append(serWorker.Create(OpCodes.Ldloc_0)); + + serWorker.Append(serWorker.Create(OpCodes.Brtrue, dirtyLabel)); + + // write dirty bits + serWorker.Append(serWorker.Create(OpCodes.Ldarg_1)); + serWorker.Append(serWorker.Create(OpCodes.Ldarg_0)); + serWorker.Append(serWorker.Create(OpCodes.Call, m_Weaver.NetworkBehaviourDirtyBitsReference)); + serWorker.Append(serWorker.Create(OpCodes.Callvirt, m_Weaver.NetworkWriterWritePacked32)); + if (reset) + { + serWorker.Append(serWorker.Create(OpCodes.Ldc_I4_1)); + serWorker.Append(serWorker.Create(OpCodes.Stloc_0)); + } + + // Generates: end if (!dirty) + serWorker.Append(dirtyLabel); + } + + int GetChannelId(FieldDefinition field) + { + int channel = 0; + foreach (var ca in field.CustomAttributes) + { + if (ca.AttributeType.FullName == m_Weaver.SyncVarType.FullName) + { + foreach (CustomAttributeNamedArgument customField in ca.Fields) + { + if (customField.Name == "channel") + { + channel = (int)customField.Argument.Value; + break; + } + } + } + } + return channel; + } + + // returns false for error, not for no-hook-exists + bool CheckForHookFunction(FieldDefinition syncVar, out MethodDefinition foundMethod) + { + foundMethod = null; + foreach (var ca in syncVar.CustomAttributes) + { + if (ca.AttributeType.FullName == m_Weaver.SyncVarType.FullName) + { + foreach (CustomAttributeNamedArgument customField in ca.Fields) + { + if (customField.Name == "hook") + { + string hookFunctionName = customField.Argument.Value as string; + + foreach (var m in m_td.Methods) + { + if (m.Name == hookFunctionName) + { + if (m.Parameters.Count == 1) + { + if (m.Parameters[0].ParameterType != syncVar.FieldType) + { + Log.Error("SyncVar Hook function " + hookFunctionName + " has wrong type signature for " + m_td.Name); + m_Weaver.fail = true; + return false; + } + foundMethod = m; + return true; + } + Log.Error("SyncVar Hook function " + hookFunctionName + " must have one argument " + m_td.Name); + m_Weaver.fail = true; + return false; + } + } + Log.Error("SyncVar Hook function " + hookFunctionName + " not found for " + m_td.Name); + m_Weaver.fail = true; + return false; + } + } + } + } + return true; + } + + void GenerateNetworkChannelSetting(int channel) + { + MethodDefinition meth = new MethodDefinition("GetNetworkChannel", MethodAttributes.Public | + MethodAttributes.Virtual | + MethodAttributes.HideBySig, + m_Weaver.int32Type); + + ILProcessor worker = meth.Body.GetILProcessor(); + + worker.Append(worker.Create(OpCodes.Ldc_I4, channel)); + worker.Append(worker.Create(OpCodes.Ret)); + m_td.Methods.Add(meth); + } + + void GenerateNetworkIntervalSetting(float interval) + { + MethodDefinition meth = new MethodDefinition("GetNetworkSendInterval", MethodAttributes.Public | + MethodAttributes.Virtual | + MethodAttributes.HideBySig, + m_Weaver.singleType); + + ILProcessor worker = meth.Body.GetILProcessor(); + + worker.Append(worker.Create(OpCodes.Ldc_R4, interval)); + worker.Append(worker.Create(OpCodes.Ret)); + m_td.Methods.Add(meth); + } + + void GenerateNetworkSettings() + { + // look for custom attribute + foreach (var ca in m_td.CustomAttributes) + { + if (ca.AttributeType.FullName == m_Weaver.NetworkSettingsType.FullName) + { + // generate virtual functions + foreach (var field in ca.Fields) + { + if (field.Name == "channel") + { + // 0 is Channels.DefaultChannel + if ((int)field.Argument.Value == 0) + continue; + + if (HasMethod("GetNetworkChannel")) + { + Log.Error( + "GetNetworkChannel, is already implemented, please make sure you either use NetworkSettings or GetNetworkChannel"); + m_Weaver.fail = true; + return; + } + m_QosChannel = (int)field.Argument.Value; + GenerateNetworkChannelSetting(m_QosChannel); + } + if (field.Name == "sendInterval") + { + const float stdValue = 0.1f; + const float epsilon = 0.00001f; + + if ((Math.Abs((float)field.Argument.Value - stdValue) <= epsilon)) + continue; + + if (HasMethod("GetNetworkSendInterval")) + { + Log.Error( + "GetNetworkSendInterval, is already implemented, please make sure you either use NetworkSettings or GetNetworkSendInterval"); + m_Weaver.fail = true; + return; + } + GenerateNetworkIntervalSetting((float)field.Argument.Value); + } + } + } + } + } + + void GeneratePreStartClient() + { + m_NetIdFieldCounter = 0; + MethodDefinition preStartMethod = null; + ILProcessor serWorker = null; + + foreach (var m in m_td.Methods) + { + if (m.Name == "PreStartClient") + return; + } + + preStartMethod = new MethodDefinition("PreStartClient", MethodAttributes.Public | + MethodAttributes.Virtual | + MethodAttributes.HideBySig, + m_Weaver.voidType); + serWorker = preStartMethod.Body.GetILProcessor(); + //Add base class + if (m_td.BaseType.FullName != m_Weaver.NetworkBehaviourType.FullName) + { + MethodReference basePreStartMethod = m_Weaver.ResolveMethod(m_td.BaseType, "PreStartClient"); + if (basePreStartMethod != null) + { + serWorker.Append(serWorker.Create(OpCodes.Ldarg_0)); // base + + serWorker.Append(serWorker.Create(OpCodes.Call, basePreStartMethod)); + } + } + if (m_SyncVars.Count == 0) + { + serWorker.Append(serWorker.Create(OpCodes.Ret)); + m_td.Methods.Add(preStartMethod); + return; + } + + foreach (FieldDefinition syncVar in m_SyncVars) + { + if (syncVar.FieldType.FullName == m_Weaver.gameObjectType.FullName) + { + FieldDefinition netIdField = m_SyncVarNetIds[m_NetIdFieldCounter]; + m_NetIdFieldCounter += 1; + + // Generates: if (!_crateNetId.IsEmpty()) { crate = ClientScene.FindLocalObject(_crateNetId); } + Instruction nullLabel = serWorker.Create(OpCodes.Nop); + serWorker.Append(serWorker.Create(OpCodes.Ldarg_0)); + serWorker.Append(serWorker.Create(OpCodes.Ldflda, netIdField)); + serWorker.Append(serWorker.Create(OpCodes.Call, m_Weaver.NetworkInstanceIsEmpty)); + serWorker.Append(serWorker.Create(OpCodes.Brtrue, nullLabel)); + + serWorker.Append(serWorker.Create(OpCodes.Ldarg_0)); + serWorker.Append(serWorker.Create(OpCodes.Ldarg_0)); + serWorker.Append(serWorker.Create(OpCodes.Ldfld, netIdField)); + serWorker.Append(serWorker.Create(OpCodes.Call, m_Weaver.FindLocalObjectReference)); + + // return value of FindLocalObjectReference is on stack, assign it to the syncvar + serWorker.Append(serWorker.Create(OpCodes.Stfld, syncVar)); + + // Generates: end crateNetId != 0 + serWorker.Append(nullLabel); + } + } + if (preStartMethod != null) + { + serWorker.Append(serWorker.Create(OpCodes.Ret)); + m_td.Methods.Add(preStartMethod); + } + } + + void GenerateDeSerialization() + { + m_Weaver.DLog(m_td, " GenerateDeSerialization"); + m_NetIdFieldCounter = 0; + + foreach (var m in m_td.Methods) + { + if (m.Name == "OnDeserialize") + return; + } + + MethodDefinition serialize = new MethodDefinition("OnDeserialize", MethodAttributes.Public | + MethodAttributes.Virtual | + MethodAttributes.HideBySig, + m_Weaver.voidType); + + serialize.Parameters.Add(new ParameterDefinition("reader", ParameterAttributes.None, m_Weaver.m_ScriptDef.MainModule.ImportReference(m_Weaver.NetworkReaderType))); + serialize.Parameters.Add(new ParameterDefinition("initialState", ParameterAttributes.None, m_Weaver.boolType)); + ILProcessor serWorker = serialize.Body.GetILProcessor(); + + // call base class + if (m_td.BaseType.FullName != m_Weaver.NetworkBehaviourType.FullName) + { + MethodReference baseDeserialize = m_Weaver.ResolveMethod(m_td.BaseType, "OnDeserialize"); + if (baseDeserialize != null) + { + serWorker.Append(serWorker.Create(OpCodes.Ldarg_0)); // base + serWorker.Append(serWorker.Create(OpCodes.Ldarg_1)); // reader + serWorker.Append(serWorker.Create(OpCodes.Ldarg_2)); // initialState + serWorker.Append(serWorker.Create(OpCodes.Call, baseDeserialize)); + } + } + + if (m_SyncVars.Count == 0) + { + serWorker.Append(serWorker.Create(OpCodes.Ret)); + m_td.Methods.Add(serialize); + return; + } + + // Generates: if (initialState); + Instruction initialStateLabel = serWorker.Create(OpCodes.Nop); + + serWorker.Append(serWorker.Create(OpCodes.Ldarg_2)); + serWorker.Append(serWorker.Create(OpCodes.Brfalse, initialStateLabel)); + + foreach (var syncVar in m_SyncVars) + { + MethodReference readByReferenceFunc = m_Weaver.GetReadByReferenceFunc(syncVar.FieldType); + if (readByReferenceFunc != null) + { + serWorker.Append(serWorker.Create(OpCodes.Ldarg_1)); + serWorker.Append(serWorker.Create(OpCodes.Ldarg_0)); + serWorker.Append(serWorker.Create(OpCodes.Ldfld, syncVar)); + serWorker.Append(serWorker.Create(OpCodes.Call, readByReferenceFunc)); + } + else + { + // assign value + serWorker.Append(serWorker.Create(OpCodes.Ldarg_0)); + serWorker.Append(serWorker.Create(OpCodes.Ldarg_1)); + + if (syncVar.FieldType.FullName == m_Weaver.gameObjectType.FullName) + { + // GameObject SyncVar - assign to generated netId var + FieldDefinition netIdField = m_SyncVarNetIds[m_NetIdFieldCounter]; + m_NetIdFieldCounter += 1; + + serWorker.Append(serWorker.Create(OpCodes.Callvirt, m_Weaver.NetworkReaderReadNetworkInstanceId)); + serWorker.Append(serWorker.Create(OpCodes.Stfld, netIdField)); + } + else + { + MethodReference readFunc = m_Weaver.GetReadFunc(syncVar.FieldType); + if (readFunc != null) + { + serWorker.Append(serWorker.Create(OpCodes.Call, readFunc)); + } + else + { + Log.Error("GenerateDeSerialization for " + m_td.Name + " unknown type [" + syncVar.FieldType + "]. UNet [SyncVar] member variables must be basic types."); + m_Weaver.fail = true; + return; + } + serWorker.Append(serWorker.Create(OpCodes.Stfld, syncVar)); + } + } + } + + serWorker.Append(serWorker.Create(OpCodes.Ret)); + + // Generates: end if (initialState); + serWorker.Append(initialStateLabel); + + + // setup local for dirty bits + serialize.Body.InitLocals = true; + VariableDefinition dirtyBitsLocal = new VariableDefinition(m_Weaver.int32Type); + serialize.Body.Variables.Add(dirtyBitsLocal); + + // get dirty bits + serWorker.Append(serWorker.Create(OpCodes.Ldarg_1)); + serWorker.Append(serWorker.Create(OpCodes.Callvirt, m_Weaver.NetworkReaderReadPacked32)); + serWorker.Append(serWorker.Create(OpCodes.Stloc_0)); + + // conditionally read each syncvar + int dirtyBit = m_Weaver.GetSyncVarStart(m_td.BaseType.FullName); // start at number of syncvars in parent + foreach (FieldDefinition syncVar in m_SyncVars) + { + Instruction varLabel = serWorker.Create(OpCodes.Nop); + + // check if dirty bit is set + serWorker.Append(serWorker.Create(OpCodes.Ldloc_0)); + serWorker.Append(serWorker.Create(OpCodes.Ldc_I4, 1 << dirtyBit)); + serWorker.Append(serWorker.Create(OpCodes.And)); + serWorker.Append(serWorker.Create(OpCodes.Brfalse, varLabel)); + + MethodReference readByReferenceFunc = m_Weaver.GetReadByReferenceFunc(syncVar.FieldType); + if (readByReferenceFunc != null) + { + serWorker.Append(serWorker.Create(OpCodes.Ldarg_1)); + serWorker.Append(serWorker.Create(OpCodes.Ldarg_0)); + serWorker.Append(serWorker.Create(OpCodes.Ldfld, syncVar)); + serWorker.Append(serWorker.Create(OpCodes.Call, readByReferenceFunc)); + } + else + { + MethodReference readFunc = m_Weaver.GetReadFunc(syncVar.FieldType); + if (readFunc == null) + { + Log.Error("GenerateDeSerialization for " + m_td.Name + " unknown type [" + syncVar.FieldType + "]. UNet [SyncVar] member variables must be basic types."); + m_Weaver.fail = true; + return; + } + + // check for Hook function + MethodDefinition foundMethod; + if (!CheckForHookFunction(syncVar, out foundMethod)) + { + return; + } + + if (foundMethod == null) + { + // just assign value + serWorker.Append(serWorker.Create(OpCodes.Ldarg_0)); + serWorker.Append(serWorker.Create(OpCodes.Ldarg_1)); + serWorker.Append(serWorker.Create(OpCodes.Call, readFunc)); + serWorker.Append(serWorker.Create(OpCodes.Stfld, syncVar)); + } + else + { + // call hook instead + serWorker.Append(serWorker.Create(OpCodes.Ldarg_0)); + serWorker.Append(serWorker.Create(OpCodes.Ldarg_1)); + serWorker.Append(serWorker.Create(OpCodes.Call, readFunc)); + serWorker.Append(serWorker.Create(OpCodes.Call, foundMethod)); + } + } + serWorker.Append(varLabel); + dirtyBit += 1; + } + + if (m_Weaver.generateLogErrors) + { + serWorker.Append(serWorker.Create(OpCodes.Ldstr, "Injected Deserialize " + m_td.Name)); + serWorker.Append(serWorker.Create(OpCodes.Call, m_Weaver.logErrorReference)); + } + + serWorker.Append(serWorker.Create(OpCodes.Ret)); + m_td.Methods.Add(serialize); + } + + bool ProcessNetworkReaderParameters(MethodDefinition md, ILProcessor worker, bool skipFirst) + { + int count = 0; + + // read cmd args from NetworkReader + foreach (ParameterDefinition arg in md.Parameters) + { + if (count++ == 0 && skipFirst) + { + continue; + } + MethodReference readFunc = m_Weaver.GetReadFunc(arg.ParameterType); //? + + if (readFunc != null) + { + worker.Append(worker.Create(OpCodes.Ldarg_1)); + worker.Append(worker.Create(OpCodes.Call, readFunc)); + + // conversion.. is this needed? + if (arg.ParameterType.FullName == m_Weaver.singleType.FullName) + { + worker.Append(worker.Create(OpCodes.Conv_R4)); + } + else if (arg.ParameterType.FullName == m_Weaver.doubleType.FullName) + { + worker.Append(worker.Create(OpCodes.Conv_R8)); + } + } + else + { + Log.Error("ProcessNetworkReaderParameters for " + m_td.Name + ":" + md.Name + " type " + arg.ParameterType + " not supported"); + m_Weaver.fail = true; + return false; + } + } + return true; + } + + /* + // generates code like: + protected static void InvokeCmdCmdThrust(NetworkBehaviour obj, NetworkReader reader) + { + if (!NetworkServer.active) + { + return; + } + ((ShipControl)obj).CmdThrust(reader.ReadSingle(), (int)reader.ReadPackedUInt32()); + } + */ + MethodDefinition ProcessCommandInvoke(MethodDefinition md) + { + MethodDefinition cmd = new MethodDefinition(k_CmdPrefix + md.Name, MethodAttributes.Family | + MethodAttributes.Static | + MethodAttributes.HideBySig, + m_Weaver.voidType); + + ILProcessor cmdWorker = cmd.Body.GetILProcessor(); + Instruction label = cmdWorker.Create(OpCodes.Nop); + + WriteServerActiveCheck(cmdWorker, md.Name, label, "Command"); + + // setup for reader + cmdWorker.Append(cmdWorker.Create(OpCodes.Ldarg_0)); + cmdWorker.Append(cmdWorker.Create(OpCodes.Castclass, m_td)); + + if (!ProcessNetworkReaderParameters(md, cmdWorker, false)) + return null; + + // invoke actual command function + cmdWorker.Append(cmdWorker.Create(OpCodes.Callvirt, md)); + cmdWorker.Append(cmdWorker.Create(OpCodes.Ret)); + + AddInvokeParameters(cmd.Parameters); + + return cmd; + } + + void AddInvokeParameters(ICollection collection) + { + collection.Add(new ParameterDefinition("obj", ParameterAttributes.None, m_Weaver.NetworkBehaviourType2)); + collection.Add(new ParameterDefinition("reader", ParameterAttributes.None, m_Weaver.m_ScriptDef.MainModule.ImportReference(m_Weaver.NetworkReaderType))); + } + + /* + // generates code like: + public void CallCmdThrust(float thrusting, int spin) + { + Debug.LogError("Call Command function CmdThrust"); + if (!NetworkClient.active) + { + Debug.LogError("Command function CmdThrust called on server."); + return; + } + + if (isServer) + { + // we are ON the server, invoke directly + CmdThrust(thrusting, spin); + return; + } + + NetworkWriter networkWriter = new NetworkWriter(); + networkWriter.Write(0); + networkWriter.Write((ushort)MsgType.SYSTEM_COMMAND); + networkWriter.WritePackedUInt32((uint)ShipControl.kCmdCmdThrust); + networkWriter.WritePackedUInt32((uint)playerId); + networkWriter.Write(thrusting); + networkWriter.WritePackedUInt32((uint)spin); + base.SendCommandInternal(networkWriter); + } + */ + MethodDefinition ProcessCommandCall(MethodDefinition md, CustomAttribute ca) + { + MethodDefinition cmd = new MethodDefinition("Call" + md.Name, MethodAttributes.Public | + MethodAttributes.HideBySig, + m_Weaver.voidType); + + // add paramters + foreach (ParameterDefinition pd in md.Parameters) + { + cmd.Parameters.Add(new ParameterDefinition(pd.Name, ParameterAttributes.None, pd.ParameterType)); + } + + ILProcessor cmdWorker = cmd.Body.GetILProcessor(); + Instruction label = cmdWorker.Create(OpCodes.Nop); + + WriteSetupLocals(cmdWorker); + + if (m_Weaver.generateLogErrors) + { + cmdWorker.Append(cmdWorker.Create(OpCodes.Ldstr, "Call Command function " + md.Name)); + cmdWorker.Append(cmdWorker.Create(OpCodes.Call, m_Weaver.logErrorReference)); + } + + WriteClientActiveCheck(cmdWorker, md.Name, label, "Command function"); + + // local client check + + Instruction localClientLabel = cmdWorker.Create(OpCodes.Nop); + cmdWorker.Append(cmdWorker.Create(OpCodes.Ldarg_0)); + cmdWorker.Append(cmdWorker.Create(OpCodes.Call, m_Weaver.UBehaviourIsServer)); + cmdWorker.Append(cmdWorker.Create(OpCodes.Brfalse, localClientLabel)); + + // call the cmd function directly. + cmdWorker.Append(cmdWorker.Create(OpCodes.Ldarg_0)); + for (int i = 0; i < md.Parameters.Count; i++) + { + cmdWorker.Append(cmdWorker.Create(OpCodes.Ldarg, i + 1)); + } + cmdWorker.Append(cmdWorker.Create(OpCodes.Call, md)); + cmdWorker.Append(cmdWorker.Create(OpCodes.Ret)); + cmdWorker.Append(localClientLabel); + + WriteCreateWriter(cmdWorker); + + WriteMessageSize(cmdWorker); + + WriteMessageId(cmdWorker, 5); //UNetwork.SYSTEM_COMMAND + + // create the command id constant + FieldDefinition cmdConstant = new FieldDefinition("kCmd" + md.Name, + FieldAttributes.Static | FieldAttributes.Private, + m_Weaver.int32Type); + m_td.Fields.Add(cmdConstant); + + // write command constant + cmdWorker.Append(cmdWorker.Create(OpCodes.Ldloc_0)); + cmdWorker.Append(cmdWorker.Create(OpCodes.Ldsfld, cmdConstant)); + cmdWorker.Append(cmdWorker.Create(OpCodes.Callvirt, m_Weaver.NetworkWriterWritePacked32)); + + // write playerId from this NetworkBehaviour + cmdWorker.Append(cmdWorker.Create(OpCodes.Ldloc_0)); + cmdWorker.Append(cmdWorker.Create(OpCodes.Ldarg_0)); + // load unetviewfield + cmdWorker.Append(cmdWorker.Create(OpCodes.Call, m_Weaver.getComponentReference)); + // load and write netId field + cmdWorker.Append(cmdWorker.Create(OpCodes.Callvirt, m_Weaver.getUNetIdReference)); + + var writeFunc = m_Weaver.GetWriteFunc(m_Weaver.NetworkInstanceIdType); + cmdWorker.Append(cmdWorker.Create(OpCodes.Callvirt, writeFunc)); + + if (!WriteArguments(cmdWorker, md, "Command", false)) + return null; + + // find channel for Command + int channel = 0; + foreach (var field in ca.Fields) + { + if (field.Name == "channel") + { + channel = (int)field.Argument.Value; + } + } + + var cmdName = md.Name; + int index = cmdName.IndexOf(k_CmdPrefix); + if (index > -1) + { + cmdName = cmdName.Substring(k_CmdPrefix.Length); + } + + // invoke interal send and return + cmdWorker.Append(cmdWorker.Create(OpCodes.Ldarg_0)); + cmdWorker.Append(cmdWorker.Create(OpCodes.Ldloc_0)); + cmdWorker.Append(cmdWorker.Create(OpCodes.Ldc_I4, channel)); // QoS transport channel (reliable/unreliable) + cmdWorker.Append(cmdWorker.Create(OpCodes.Ldstr, cmdName)); + cmdWorker.Append(cmdWorker.Create(OpCodes.Call, m_Weaver.sendCommandInternal)); + + cmdWorker.Append(cmdWorker.Create(OpCodes.Ret)); + + return cmd; + } + + MethodDefinition ProcessTargetRpcInvoke(MethodDefinition md) + { + MethodDefinition rpc = new MethodDefinition(k_RpcPrefix + md.Name, MethodAttributes.Family | + MethodAttributes.Static | + MethodAttributes.HideBySig, + m_Weaver.voidType); + + ILProcessor rpcWorker = rpc.Body.GetILProcessor(); + Instruction label = rpcWorker.Create(OpCodes.Nop); + + WriteClientActiveCheck(rpcWorker, md.Name, label, "TargetRPC"); + + // setup for reader + rpcWorker.Append(rpcWorker.Create(OpCodes.Ldarg_0)); + rpcWorker.Append(rpcWorker.Create(OpCodes.Castclass, m_td)); + + //ClientScene.readyconnection + rpcWorker.Append(rpcWorker.Create(OpCodes.Call, m_Weaver.ReadyConnectionReference)); + + if (!ProcessNetworkReaderParameters(md, rpcWorker, true)) + return null; + + // invoke actual command function + rpcWorker.Append(rpcWorker.Create(OpCodes.Callvirt, md)); + rpcWorker.Append(rpcWorker.Create(OpCodes.Ret)); + + AddInvokeParameters(rpc.Parameters); + + return rpc; + } + + MethodDefinition ProcessRpcInvoke(MethodDefinition md) + { + MethodDefinition rpc = new MethodDefinition(k_RpcPrefix + md.Name, MethodAttributes.Family | + MethodAttributes.Static | + MethodAttributes.HideBySig, + m_Weaver.voidType); + + ILProcessor rpcWorker = rpc.Body.GetILProcessor(); + Instruction label = rpcWorker.Create(OpCodes.Nop); + + WriteClientActiveCheck(rpcWorker, md.Name, label, "RPC"); + + // setup for reader + rpcWorker.Append(rpcWorker.Create(OpCodes.Ldarg_0)); + rpcWorker.Append(rpcWorker.Create(OpCodes.Castclass, m_td)); + + if (!ProcessNetworkReaderParameters(md, rpcWorker, false)) + return null; + + // invoke actual command function + rpcWorker.Append(rpcWorker.Create(OpCodes.Callvirt, md)); + rpcWorker.Append(rpcWorker.Create(OpCodes.Ret)); + + AddInvokeParameters(rpc.Parameters); + + return rpc; + } + + MethodDefinition ProcessTargetRpcCall(MethodDefinition md, CustomAttribute ca) + { + MethodDefinition rpc = new MethodDefinition("Call" + md.Name, MethodAttributes.Public | + MethodAttributes.HideBySig, + m_Weaver.voidType); + + // add paramters + foreach (ParameterDefinition pd in md.Parameters) + { + rpc.Parameters.Add(new ParameterDefinition(pd.Name, ParameterAttributes.None, pd.ParameterType)); + } + + ILProcessor rpcWorker = rpc.Body.GetILProcessor(); + Instruction label = rpcWorker.Create(OpCodes.Nop); + + WriteSetupLocals(rpcWorker); + + WriteServerActiveCheck(rpcWorker, md.Name, label, "TargetRPC Function"); + + Instruction labelConnectionCheck = rpcWorker.Create(OpCodes.Nop); + + // check specifically for ULocalConnectionToServer so a host is not trying to send + // an TargetRPC to the "server" from it's local client. + rpcWorker.Append(rpcWorker.Create(OpCodes.Ldarg_1)); + rpcWorker.Append(rpcWorker.Create(OpCodes.Isinst, m_Weaver.ULocalConnectionToServerType)); + rpcWorker.Append(rpcWorker.Create(OpCodes.Brfalse, labelConnectionCheck)); + rpcWorker.Append(rpcWorker.Create(OpCodes.Ldstr, string.Format("TargetRPC Function {0} called on connection to server", md.Name))); + rpcWorker.Append(rpcWorker.Create(OpCodes.Call, m_Weaver.logErrorReference)); + rpcWorker.Append(rpcWorker.Create(OpCodes.Ret)); + rpcWorker.Append(labelConnectionCheck); + + WriteCreateWriter(rpcWorker); + + WriteMessageSize(rpcWorker); + + WriteMessageId(rpcWorker, 2); // UNetwork.SYSTEM_RPC + + // create the command id constant + FieldDefinition rpcConstant = new FieldDefinition("kTargetRpc" + md.Name, + FieldAttributes.Static | FieldAttributes.Private, + m_Weaver.int32Type); + m_td.Fields.Add(rpcConstant); + + // write command constant + rpcWorker.Append(rpcWorker.Create(OpCodes.Ldloc_0)); + rpcWorker.Append(rpcWorker.Create(OpCodes.Ldsfld, rpcConstant)); + rpcWorker.Append(rpcWorker.Create(OpCodes.Callvirt, m_Weaver.NetworkWriterWritePacked32)); + + // write this.unetView.netId + rpcWorker.Append(rpcWorker.Create(OpCodes.Ldloc_0)); + rpcWorker.Append(rpcWorker.Create(OpCodes.Ldarg_0)); + // load unetviewfield + rpcWorker.Append(rpcWorker.Create(OpCodes.Call, m_Weaver.getComponentReference)); + // load and write netId field + rpcWorker.Append(rpcWorker.Create(OpCodes.Callvirt, m_Weaver.getUNetIdReference)); + rpcWorker.Append(rpcWorker.Create(OpCodes.Callvirt, m_Weaver.NetworkWriterWriteNetworkInstanceId)); + + if (!WriteArguments(rpcWorker, md, "TargetRPC", true)) + return null; + + // find channel for SyncEvent + int channel = 0; + foreach (var field in ca.Fields) + { + if (field.Name == "channel") + { + channel = (int)field.Argument.Value; + } + } + + var rpcName = md.Name; + int index = rpcName.IndexOf(k_TargetRpcPrefix); + if (index > -1) + { + rpcName = rpcName.Substring(k_TargetRpcPrefix.Length); + } + + // invoke SendInternal and return + rpcWorker.Append(rpcWorker.Create(OpCodes.Ldarg_0)); // this + rpcWorker.Append(rpcWorker.Create(OpCodes.Ldarg_1)); // connection + rpcWorker.Append(rpcWorker.Create(OpCodes.Ldloc_0)); // writer + rpcWorker.Append(rpcWorker.Create(OpCodes.Ldc_I4, channel)); // QoS transport channel (reliable/unreliable) + rpcWorker.Append(rpcWorker.Create(OpCodes.Ldstr, rpcName)); + rpcWorker.Append(rpcWorker.Create(OpCodes.Callvirt, m_Weaver.sendTargetRpcInternal)); + + rpcWorker.Append(rpcWorker.Create(OpCodes.Ret)); + + return rpc; + } + + MethodDefinition ProcessRpcCall(MethodDefinition md, CustomAttribute ca) + { + MethodDefinition rpc = new MethodDefinition("Call" + md.Name, MethodAttributes.Public | + MethodAttributes.HideBySig, + m_Weaver.voidType); + + // add paramters + foreach (ParameterDefinition pd in md.Parameters) + { + rpc.Parameters.Add(new ParameterDefinition(pd.Name, ParameterAttributes.None, pd.ParameterType)); + } + + ILProcessor rpcWorker = rpc.Body.GetILProcessor(); + Instruction label = rpcWorker.Create(OpCodes.Nop); + + WriteSetupLocals(rpcWorker); + + WriteServerActiveCheck(rpcWorker, md.Name, label, "RPC Function"); + + WriteCreateWriter(rpcWorker); + + WriteMessageSize(rpcWorker); + + WriteMessageId(rpcWorker, 2); // UNetwork.SYSTEM_RPC + + // create the command id constant + FieldDefinition rpcConstant = new FieldDefinition("kRpc" + md.Name, + FieldAttributes.Static | FieldAttributes.Private, + m_Weaver.int32Type); + m_td.Fields.Add(rpcConstant); + + // write command constant + rpcWorker.Append(rpcWorker.Create(OpCodes.Ldloc_0)); + rpcWorker.Append(rpcWorker.Create(OpCodes.Ldsfld, rpcConstant)); + rpcWorker.Append(rpcWorker.Create(OpCodes.Callvirt, m_Weaver.NetworkWriterWritePacked32)); + + // write this.unetView.netId + rpcWorker.Append(rpcWorker.Create(OpCodes.Ldloc_0)); + rpcWorker.Append(rpcWorker.Create(OpCodes.Ldarg_0)); + // load unetviewfield + rpcWorker.Append(rpcWorker.Create(OpCodes.Call, m_Weaver.getComponentReference)); + // load and write netId field + rpcWorker.Append(rpcWorker.Create(OpCodes.Callvirt, m_Weaver.getUNetIdReference)); + rpcWorker.Append(rpcWorker.Create(OpCodes.Callvirt, m_Weaver.NetworkWriterWriteNetworkInstanceId)); + + if (!WriteArguments(rpcWorker, md, "RPC", false)) + return null; + + // find channel for SyncEvent + int channel = 0; + foreach (var field in ca.Fields) + { + if (field.Name == "channel") + { + channel = (int)field.Argument.Value; + } + } + + var rpcName = md.Name; + int index = rpcName.IndexOf(k_RpcPrefix); + if (index > -1) + { + rpcName = rpcName.Substring(k_RpcPrefix.Length); + } + + // invoke SendInternal and return + rpcWorker.Append(rpcWorker.Create(OpCodes.Ldarg_0)); // this + rpcWorker.Append(rpcWorker.Create(OpCodes.Ldloc_0)); // writer + rpcWorker.Append(rpcWorker.Create(OpCodes.Ldc_I4, channel)); // QoS transport channel (reliable/unreliable) + rpcWorker.Append(rpcWorker.Create(OpCodes.Ldstr, rpcName)); + rpcWorker.Append(rpcWorker.Create(OpCodes.Callvirt, m_Weaver.sendRpcInternal)); + + rpcWorker.Append(rpcWorker.Create(OpCodes.Ret)); + + return rpc; + } + + bool ProcessMethodsValidateFunction(MethodReference md, CustomAttribute ca, string actionType) + { + if (md.ReturnType.FullName == m_Weaver.IEnumeratorType.FullName) + { + Log.Error(actionType + " function [" + m_td.FullName + ":" + md.Name + "] cannot be a coroutine"); + m_Weaver.fail = true; + return false; + } + if (md.ReturnType.FullName != m_Weaver.voidType.FullName) + { + Log.Error(actionType + " function [" + m_td.FullName + ":" + md.Name + "] must have a void return type."); + m_Weaver.fail = true; + return false; + } + if (md.HasGenericParameters) + { + Log.Error(actionType + " [" + m_td.FullName + ":" + md.Name + "] cannot have generic parameters"); + m_Weaver.fail = true; + return false; + } + return true; + } + + bool ProcessMethodsValidateParameters(MethodReference md, CustomAttribute ca, string actionType) + { + for (int i = 0; i < md.Parameters.Count; ++i) + { + var p = md.Parameters[i]; + if (p.IsOut) + { + Log.Error(actionType + " function [" + m_td.FullName + ":" + md.Name + "] cannot have out parameters"); + m_Weaver.fail = true; + return false; + } + if (p.IsOptional) + { + Log.Error(actionType + "function [" + m_td.FullName + ":" + md.Name + "] cannot have optional parameters"); + m_Weaver.fail = true; + return false; + } + if (p.ParameterType.Resolve().IsAbstract) + { + Log.Error(actionType + " function [" + m_td.FullName + ":" + md.Name + "] cannot have abstract parameters"); + m_Weaver.fail = true; + return false; + } + if (p.ParameterType.IsByReference) + { + Log.Error(actionType + " function [" + m_td.FullName + ":" + md.Name + "] cannot have ref parameters"); + m_Weaver.fail = true; + return false; + } + // TargetRPC is an exception to this rule and can have a NetworkConnection as first parameter + if (p.ParameterType.FullName == m_Weaver.NetworkConnectionType.FullName && + !(ca.AttributeType.FullName == m_Weaver.TargetRpcType.FullName && i == 0)) + { + Log.Error(actionType + " [" + m_td.FullName + ":" + md.Name + "] cannot use a NetworkConnection as a parameter. To access a player object's connection on the server use connectionToClient"); + Log.Error("Name: " + ca.AttributeType.FullName + " parameter: " + md.Parameters[0].ParameterType.FullName); + m_Weaver.fail = true; + return false; + } + if (m_Weaver.IsDerivedFrom(p.ParameterType.Resolve(), m_Weaver.ComponentType)) + { + if (p.ParameterType.FullName != m_Weaver.NetworkIdentityType.FullName) + { + Log.Error(actionType + " function [" + m_td.FullName + ":" + md.Name + "] parameter [" + p.Name + + "] is of the type [" + + p.ParameterType.Name + + "] which is a Component. You cannot pass a Component to a remote call. Try passing data from within the component."); + m_Weaver.fail = true; + return false; + } + } + } + return true; + } + + private bool ProcessMethodsValidateCommand(MethodDefinition md, CustomAttribute ca) + { + if (md.Name.Length > 2 && md.Name.Substring(0, 3) != "Cmd") + { + Log.Error("Command function [" + m_td.FullName + ":" + md.Name + "] doesnt have 'Cmd' prefix"); + m_Weaver.fail = true; + return false; + } + + if (md.IsStatic) + { + Log.Error("Command function [" + m_td.FullName + ":" + md.Name + "] cant be a static method"); + m_Weaver.fail = true; + return false; + } + + if (!ProcessMethodsValidateFunction(md, ca, "Command")) + { + return false; + } + + if (!ProcessMethodsValidateParameters(md, ca, "Command")) + { + return false; + } + return true; + } + + bool ProcessMethodsValidateTargetRpc(MethodDefinition md, CustomAttribute ca) + { + const string targetPrefix = "Target"; + int prefixLen = targetPrefix.Length; + + if (md.Name.Length > prefixLen && md.Name.Substring(0, prefixLen) != targetPrefix) + { + Log.Error("Target Rpc function [" + m_td.FullName + ":" + md.Name + "] doesnt have 'Target' prefix"); + m_Weaver.fail = true; + return false; + } + + if (md.IsStatic) + { + Log.Error("TargetRpc function [" + m_td.FullName + ":" + md.Name + "] cant be a static method"); + m_Weaver.fail = true; + return false; + } + + if (!ProcessMethodsValidateFunction(md, ca, "Target Rpc")) + { + return false; + } + + if (md.Parameters.Count < 1) + { + Log.Error("Target Rpc function [" + m_td.FullName + ":" + md.Name + "] must have a NetworkConnection as the first parameter"); + m_Weaver.fail = true; + return false; + } + + if (md.Parameters[0].ParameterType.FullName != m_Weaver.NetworkConnectionType.FullName) + { + Log.Error("Target Rpc function [" + m_td.FullName + ":" + md.Name + "] first parameter must be a NetworkConnection"); + m_Weaver.fail = true; + return false; + } + + if (!ProcessMethodsValidateParameters(md, ca, "Target Rpc")) + { + return false; + } + return true; + } + + bool ProcessMethodsValidateRpc(MethodDefinition md, CustomAttribute ca) + { + if (md.Name.Length > 2 && md.Name.Substring(0, 3) != "Rpc") + { + Log.Error("Rpc function [" + m_td.FullName + ":" + md.Name + "] doesnt have 'Rpc' prefix"); + m_Weaver.fail = true; + return false; + } + + if (md.IsStatic) + { + Log.Error("ClientRpc function [" + m_td.FullName + ":" + md.Name + "] cant be a static method"); + m_Weaver.fail = true; + return false; + } + + if (!ProcessMethodsValidateFunction(md, ca, "Rpc")) + { + return false; + } + + if (!ProcessMethodsValidateParameters(md, ca, "Rpc")) + { + return false; + } + return true; + } + + void ProcessMethods() + { + HashSet names = new HashSet(); + + // find command and RPC functions + foreach (MethodDefinition md in m_td.Methods) + { + m_Weaver.ResetRecursionCount(); + foreach (var ca in md.CustomAttributes) + { + if (ca.AttributeType.FullName == m_Weaver.CommandType.FullName) + { + if (!ProcessMethodsValidateCommand(md, ca)) + return; + + if (names.Contains(md.Name)) + { + Log.Error("Duplicate Command name [" + m_td.FullName + ":" + md.Name + "]"); + m_Weaver.fail = true; + return; + } + names.Add(md.Name); + m_Cmds.Add(md); + + MethodDefinition cmdFunc = ProcessCommandInvoke(md); + if (cmdFunc != null) + { + m_CmdInvocationFuncs.Add(cmdFunc); + } + + MethodDefinition cmdCallFunc = ProcessCommandCall(md, ca); + if (cmdCallFunc != null) + { + m_CmdCallFuncs.Add(cmdCallFunc); + m_Weaver.lists.replacedMethods.Add(md); + m_Weaver.lists.replacementMethods.Add(cmdCallFunc); + } + break; + } + + if (ca.AttributeType.FullName == m_Weaver.TargetRpcType.FullName) + { + if (!ProcessMethodsValidateTargetRpc(md, ca)) + return; + + if (names.Contains(md.Name)) + { + Log.Error("Duplicate Target Rpc name [" + m_td.FullName + ":" + md.Name + "]"); + m_Weaver.fail = true; + return; + } + names.Add(md.Name); + m_TargetRpcs.Add(md); + + MethodDefinition rpcFunc = ProcessTargetRpcInvoke(md); + if (rpcFunc != null) + { + m_TargetRpcInvocationFuncs.Add(rpcFunc); + } + + MethodDefinition rpcCallFunc = ProcessTargetRpcCall(md, ca); + if (rpcCallFunc != null) + { + m_TargetRpcCallFuncs.Add(rpcCallFunc); + m_Weaver.lists.replacedMethods.Add(md); + m_Weaver.lists.replacementMethods.Add(rpcCallFunc); + } + break; + } + + if (ca.AttributeType.FullName == m_Weaver.ClientRpcType.FullName) + { + if (!ProcessMethodsValidateRpc(md, ca)) + return; + + if (names.Contains(md.Name)) + { + Log.Error("Duplicate ClientRpc name [" + m_td.FullName + ":" + md.Name + "]"); + m_Weaver.fail = true; + return; + } + names.Add(md.Name); + m_Rpcs.Add(md); + + MethodDefinition rpcFunc = ProcessRpcInvoke(md); + if (rpcFunc != null) + { + m_RpcInvocationFuncs.Add(rpcFunc); + } + + MethodDefinition rpcCallFunc = ProcessRpcCall(md, ca); + if (rpcCallFunc != null) + { + m_RpcCallFuncs.Add(rpcCallFunc); + m_Weaver.lists.replacedMethods.Add(md); + m_Weaver.lists.replacementMethods.Add(rpcCallFunc); + } + break; + } + } + } + + // cmds + foreach (MethodDefinition md in m_CmdInvocationFuncs) + { + m_td.Methods.Add(md); + } + foreach (MethodDefinition md in m_CmdCallFuncs) + { + m_td.Methods.Add(md); + } + + // rpcs + foreach (MethodDefinition md in m_RpcInvocationFuncs) + { + m_td.Methods.Add(md); + } + foreach (MethodDefinition md in m_TargetRpcInvocationFuncs) + { + m_td.Methods.Add(md); + } + foreach (MethodDefinition md in m_RpcCallFuncs) + { + m_td.Methods.Add(md); + } + foreach (MethodDefinition md in m_TargetRpcCallFuncs) + { + m_td.Methods.Add(md); + } + } + + MethodDefinition ProcessEventInvoke(EventDefinition ed) + { + // find the field that matches the event + FieldDefinition eventField = null; + foreach (FieldDefinition fd in m_td.Fields) + { + if (fd.FullName == ed.FullName) + { + eventField = fd; + break; + } + } + if (eventField == null) + { + m_Weaver.DLog(m_td, "ERROR: no event field?!"); + m_Weaver.fail = true; + return null; + } + + MethodDefinition cmd = new MethodDefinition("InvokeSyncEvent" + ed.Name, MethodAttributes.Family | + MethodAttributes.Static | + MethodAttributes.HideBySig, + m_Weaver.voidType); + + ILProcessor cmdWorker = cmd.Body.GetILProcessor(); + Instruction label1 = cmdWorker.Create(OpCodes.Nop); + Instruction label2 = cmdWorker.Create(OpCodes.Nop); + + WriteClientActiveCheck(cmdWorker, ed.Name, label1, "Event"); + + // null event check + cmdWorker.Append(cmdWorker.Create(OpCodes.Ldarg_0)); + cmdWorker.Append(cmdWorker.Create(OpCodes.Castclass, m_td)); + cmdWorker.Append(cmdWorker.Create(OpCodes.Ldfld, eventField)); + cmdWorker.Append(cmdWorker.Create(OpCodes.Brtrue, label2)); + cmdWorker.Append(cmdWorker.Create(OpCodes.Ret)); + cmdWorker.Append(label2); + + // setup reader + cmdWorker.Append(cmdWorker.Create(OpCodes.Ldarg_0)); + cmdWorker.Append(cmdWorker.Create(OpCodes.Castclass, m_td)); + cmdWorker.Append(cmdWorker.Create(OpCodes.Ldfld, eventField)); + + // read the event arguments + MethodReference invoke = m_Weaver.ResolveMethod(eventField.FieldType, "Invoke"); + if (!ProcessNetworkReaderParameters(invoke.Resolve(), cmdWorker, false)) + return null; + + // invoke actual event delegate function + cmdWorker.Append(cmdWorker.Create(OpCodes.Callvirt, invoke)); + cmdWorker.Append(cmdWorker.Create(OpCodes.Ret)); + + AddInvokeParameters(cmd.Parameters); + + return cmd; + } + + MethodDefinition ProcessEventCall(EventDefinition ed, CustomAttribute ca) + { + MethodReference invoke = m_Weaver.ResolveMethod(ed.EventType, "Invoke"); + MethodDefinition evt = new MethodDefinition("Call" + ed.Name, MethodAttributes.Public | + MethodAttributes.HideBySig, + m_Weaver.voidType); + // add paramters + foreach (ParameterDefinition pd in invoke.Parameters) + { + evt.Parameters.Add(new ParameterDefinition(pd.Name, ParameterAttributes.None, pd.ParameterType)); + } + + ILProcessor evtWorker = evt.Body.GetILProcessor(); + Instruction label = evtWorker.Create(OpCodes.Nop); + + WriteSetupLocals(evtWorker); + + WriteServerActiveCheck(evtWorker, ed.Name, label, "Event"); + + WriteCreateWriter(evtWorker); + + WriteMessageSize(evtWorker); + + WriteMessageId(evtWorker, 7); //UNetwork.SYSTEM_SYNCEVENT + + // create the command id constant + FieldDefinition evtConstant = new FieldDefinition("kEvent" + ed.Name, + FieldAttributes.Static | FieldAttributes.Private, + m_Weaver.int32Type); + m_td.Fields.Add(evtConstant); + + // write command constant + evtWorker.Append(evtWorker.Create(OpCodes.Ldloc_0)); // networkWriter + evtWorker.Append(evtWorker.Create(OpCodes.Ldsfld, evtConstant)); + evtWorker.Append(evtWorker.Create(OpCodes.Callvirt, m_Weaver.NetworkWriterWritePacked32)); + + // write this.unetView.netId + evtWorker.Append(evtWorker.Create(OpCodes.Ldloc_0)); // networkWriter + evtWorker.Append(evtWorker.Create(OpCodes.Ldarg_0)); // this + evtWorker.Append(evtWorker.Create(OpCodes.Call, m_Weaver.getComponentReference)); // unetView + // load and write netId field + evtWorker.Append(evtWorker.Create(OpCodes.Callvirt, m_Weaver.getUNetIdReference)); // netId + evtWorker.Append(evtWorker.Create(OpCodes.Callvirt, m_Weaver.NetworkWriterWriteNetworkInstanceId)); // networkWriter.Write(this.unetView.netId) + + if (!WriteArguments(evtWorker, invoke.Resolve(), "SyncEvent", false)) + return null; + + // find channel for ClientRpc + int channel = 0; + foreach (var field in ca.Fields) + { + if (field.Name == "channel") + { + channel = (int)field.Argument.Value; + } + } + + // invoke interal send and return + evtWorker.Append(evtWorker.Create(OpCodes.Ldarg_0)); // this + evtWorker.Append(evtWorker.Create(OpCodes.Ldloc_0)); // writer + evtWorker.Append(evtWorker.Create(OpCodes.Ldc_I4, channel)); // QoS transport channel (reliable/unreliable) + evtWorker.Append(evtWorker.Create(OpCodes.Ldstr, ed.Name)); + evtWorker.Append(evtWorker.Create(OpCodes.Call, m_Weaver.sendEventInternal)); + + evtWorker.Append(evtWorker.Create(OpCodes.Ret)); + + return evt; + } + + void ProcessEvents() + { + // find events + foreach (EventDefinition ed in m_td.Events) + { + foreach (var ca in ed.CustomAttributes) + { + if (ca.AttributeType.FullName == m_Weaver.SyncEventType.FullName) + { + if (ed.Name.Length > 4 && ed.Name.Substring(0, 5) != "Event") + { + Log.Error("Event [" + m_td.FullName + ":" + ed.FullName + "] doesnt have 'Event' prefix"); + m_Weaver.fail = true; + return; + } + + if (ed.EventType.Resolve().HasGenericParameters) + { + Log.Error("Event [" + m_td.FullName + ":" + ed.FullName + "] cannot have generic parameters"); + m_Weaver.fail = true; + return; + } + + m_Events.Add(ed); + MethodDefinition eventFunc = ProcessEventInvoke(ed); + if (eventFunc == null) + { + return; + } + + m_td.Methods.Add(eventFunc); + m_EventInvocationFuncs.Add(eventFunc); + + m_Weaver.DLog(m_td, "ProcessEvent " + ed); + + MethodDefinition eventCallFunc = ProcessEventCall(ed, ca); + m_td.Methods.Add(eventCallFunc); + + m_Weaver.lists.replacedEvents.Add(ed); + m_Weaver.lists.replacementEvents.Add(eventCallFunc); + + m_Weaver.DLog(m_td, " Event: " + ed.Name); + break; + } + } + } + } + + static MethodDefinition ProcessSyncVarGet(FieldDefinition fd, string originalName) + { + //Create the get method + MethodDefinition get = new MethodDefinition( + "get_Network" + originalName, MethodAttributes.Public | + MethodAttributes.SpecialName | + MethodAttributes.HideBySig, + fd.FieldType); + + ILProcessor getWorker = get.Body.GetILProcessor(); + + getWorker.Append(getWorker.Create(OpCodes.Ldarg_0)); + getWorker.Append(getWorker.Create(OpCodes.Ldfld, fd)); + getWorker.Append(getWorker.Create(OpCodes.Ret)); + + get.Body.Variables.Add(new VariableDefinition(fd.FieldType)); + get.Body.InitLocals = true; + get.SemanticsAttributes = MethodSemanticsAttributes.Getter; + + return get; + } + + MethodDefinition ProcessSyncVarSet(FieldDefinition fd, string originalName, int dirtyBit, FieldDefinition netFieldId) + { + //Create the set method + MethodDefinition set = new MethodDefinition("set_Network" + originalName, MethodAttributes.Public | + MethodAttributes.SpecialName | + MethodAttributes.HideBySig, + m_Weaver.voidType); + + ILProcessor setWorker = set.Body.GetILProcessor(); + + // this + setWorker.Append(setWorker.Create(OpCodes.Ldarg_0)); + + // new value to set + setWorker.Append(setWorker.Create(OpCodes.Ldarg_1)); + + // reference to field to set + setWorker.Append(setWorker.Create(OpCodes.Ldarg_0)); + setWorker.Append(setWorker.Create(OpCodes.Ldflda, fd)); + + // dirty bit + setWorker.Append(setWorker.Create(OpCodes.Ldc_I4, dirtyBit)); + + MethodDefinition hookFunctionMethod; + CheckForHookFunction(fd, out hookFunctionMethod); + + if (hookFunctionMethod != null) + { + //if (NetworkServer.localClientActive && !syncVarHookGuard) + Instruction label = setWorker.Create(OpCodes.Nop); + setWorker.Append(setWorker.Create(OpCodes.Call, m_Weaver.NetworkServerGetLocalClientActive)); + setWorker.Append(setWorker.Create(OpCodes.Brfalse, label)); + setWorker.Append(setWorker.Create(OpCodes.Ldarg_0)); + setWorker.Append(setWorker.Create(OpCodes.Call, m_Weaver.getSyncVarHookGuard)); + setWorker.Append(setWorker.Create(OpCodes.Brtrue, label)); + + // syncVarHookGuard = true; + setWorker.Append(setWorker.Create(OpCodes.Ldarg_0)); + setWorker.Append(setWorker.Create(OpCodes.Ldc_I4_1)); + setWorker.Append(setWorker.Create(OpCodes.Call, m_Weaver.setSyncVarHookGuard)); + + // call hook + setWorker.Append(setWorker.Create(OpCodes.Ldarg_0)); + setWorker.Append(setWorker.Create(OpCodes.Ldarg_1)); + setWorker.Append(setWorker.Create(OpCodes.Call, hookFunctionMethod)); + + // syncVarHookGuard = false; + setWorker.Append(setWorker.Create(OpCodes.Ldarg_0)); + setWorker.Append(setWorker.Create(OpCodes.Ldc_I4_0)); + setWorker.Append(setWorker.Create(OpCodes.Call, m_Weaver.setSyncVarHookGuard)); + + setWorker.Append(label); + } + + if (fd.FieldType.FullName == m_Weaver.gameObjectType.FullName) + { + // reference to netId Field to set + setWorker.Append(setWorker.Create(OpCodes.Ldarg_0)); + setWorker.Append(setWorker.Create(OpCodes.Ldflda, netFieldId)); + + setWorker.Append(setWorker.Create(OpCodes.Call, m_Weaver.setSyncVarGameObjectReference)); + } + else + { + // make generic version of SetSyncVar with field type + GenericInstanceMethod gm = new GenericInstanceMethod(m_Weaver.setSyncVarReference); + gm.GenericArguments.Add(fd.FieldType); + + // invoke SetSyncVar + setWorker.Append(setWorker.Create(OpCodes.Call, gm)); + } + + setWorker.Append(setWorker.Create(OpCodes.Ret)); + + set.Parameters.Add(new ParameterDefinition("value", ParameterAttributes.In, fd.FieldType)); + set.SemanticsAttributes = MethodSemanticsAttributes.Setter; + + return set; + } + + void ProcessSyncVar(FieldDefinition fd, int dirtyBit) + { + string originalName = fd.Name; + + m_Weaver.lists.replacedFields.Add(fd); + m_Weaver.DLog(m_td, "Sync Var " + fd.Name + " " + fd.FieldType + " " + m_Weaver.gameObjectType); + + // GameObject SyncVars have a new field for netId + FieldDefinition netFieldId = null; + if (fd.FieldType.FullName == m_Weaver.gameObjectType.FullName) + { + netFieldId = new FieldDefinition("___" + fd.Name + "NetId", + FieldAttributes.Private, + m_Weaver.NetworkInstanceIdType); + + m_SyncVarNetIds.Add(netFieldId); + m_Weaver.lists.netIdFields.Add(netFieldId); + } + + var get = ProcessSyncVarGet(fd, originalName); + var set = ProcessSyncVarSet(fd, originalName, dirtyBit, netFieldId); + + //NOTE: is property even needed? Could just use a setter function? + //create the property + PropertyDefinition propertyDefinition = new PropertyDefinition("Network" + originalName, PropertyAttributes.None, fd.FieldType) + { + GetMethod = get, SetMethod = set + }; + + //add the methods and property to the type. + m_td.Methods.Add(get); + m_td.Methods.Add(set); + m_td.Properties.Add(propertyDefinition); + m_Weaver.lists.replacementProperties.Add(set); + } + + /* + Generates code like: + // SyncListTestPlayerBehaviour + protected static void InvokeSyncListm_ints(NetworkBehaviour obj, NetworkReader reader) + { + if (!NetworkClient.active) + { + Debug.LogError("SyncList m_ints called on server."); + return; + } + ((SyncListTestPlayerBehaviour)obj).m_ints.HandleMsg(reader); + } + */ + MethodDefinition ProcessSyncListInvoke(FieldDefinition fd) + { + MethodDefinition cmd = new MethodDefinition("InvokeSyncList" + fd.Name, MethodAttributes.Family | + MethodAttributes.Static | + MethodAttributes.HideBySig, + m_Weaver.voidType); + + ILProcessor syncList = cmd.Body.GetILProcessor(); + Instruction label = syncList.Create(OpCodes.Nop); + + + WriteClientActiveCheck(syncList, fd.Name, label, "SyncList"); + + + syncList.Append(syncList.Create(OpCodes.Ldarg_0)); //this + syncList.Append(syncList.Create(OpCodes.Castclass, fd.DeclaringType)); + syncList.Append(syncList.Create(OpCodes.Ldfld, fd)); // list field + syncList.Append(syncList.Create(OpCodes.Ldarg_1)); // reader + + // make specialized version of HandleMsg + GenericInstanceType syncListGeneric = (GenericInstanceType)fd.FieldType.Resolve().BaseType; + syncListGeneric = (GenericInstanceType)m_Weaver.m_ScriptDef.MainModule.ImportReference(syncListGeneric); + TypeReference listValueType = syncListGeneric.GenericArguments[0]; + MethodReference genericHandleMsgMethod = Helpers.MakeHostInstanceGeneric(m_Weaver.SyncListInitHandleMsg, listValueType); + syncList.Append(syncList.Create(OpCodes.Callvirt, genericHandleMsgMethod)); + + syncList.Append(syncList.Create(OpCodes.Ret)); + + AddInvokeParameters(cmd.Parameters); + + return cmd; + } + + FieldDefinition ProcessSyncList(FieldDefinition fd, int dirtyBit) + { + MethodDefinition syncListFunc = ProcessSyncListInvoke(fd); + m_SyncListInvocationFuncs.Add(syncListFunc); + + // create the command id constant + return new FieldDefinition("kList" + fd.Name, + FieldAttributes.Static | FieldAttributes.Private, + m_Weaver.int32Type); + } + + void ProcessSyncVars() + { + int numSyncVars = 0; + + // the mapping of dirtybits to sync-vars is implicit in the order of the fields here. this order is recorded in m_replacementProperties. + // start assigning syncvars at the place the base class stopped, if any + int dirtyBitCounter = m_Weaver.GetSyncVarStart(m_td.BaseType.FullName); + + m_SyncVarNetIds.Clear(); + List listFields = new List(); + + // find syncvars + foreach (FieldDefinition fd in m_td.Fields) + { + foreach (var ca in fd.CustomAttributes) + { + if (ca.AttributeType.FullName == m_Weaver.SyncVarType.FullName) + { + var resolvedField = fd.FieldType.Resolve(); + + if (m_Weaver.IsDerivedFrom(resolvedField, m_Weaver.NetworkBehaviourType)) + { + Log.Error("SyncVar [" + fd.FullName + "] cannot be derived from NetworkBehaviour."); + m_Weaver.fail = true; + return; + } + + if (m_Weaver.IsDerivedFrom(resolvedField, m_Weaver.ScriptableObjectType)) + { + Log.Error("SyncVar [" + fd.FullName + "] cannot be derived from ScriptableObject."); + m_Weaver.fail = true; + return; + } + + if ((fd.Attributes & FieldAttributes.Static) != 0) + { + Log.Error("SyncVar [" + fd.FullName + "] cannot be static."); + m_Weaver.fail = true; + return; + } + + if (resolvedField.HasGenericParameters) + { + Log.Error("SyncVar [" + fd.FullName + "] cannot have generic parameters."); + m_Weaver.fail = true; + return; + } + + if (resolvedField.IsInterface) + { + Log.Error("SyncVar [" + fd.FullName + "] cannot be an interface."); + m_Weaver.fail = true; + return; + } + + var fieldModuleName = resolvedField.Module.Name; + if (fieldModuleName != m_Weaver.m_ScriptDef.MainModule.Name && + fieldModuleName != m_Weaver.m_UnityAssemblyDefinition.MainModule.Name && + fieldModuleName != m_Weaver.m_UNetAssemblyDefinition.MainModule.Name && + fieldModuleName != m_Weaver.m_CorLib.Name && + fieldModuleName != "netstandard.dll" && + fieldModuleName != "System.Runtime.dll" // this is only for Metro, built-in types are not in corlib on metro + ) + { + Log.Error("SyncVar [" + fd.FullName + "] from " + resolvedField.Module.ToString() + " cannot be a different module."); + m_Weaver.fail = true; + return; + } + + if (fd.FieldType.IsArray) + { + Log.Error("SyncVar [" + fd.FullName + "] cannot be an array. Use a SyncList instead."); + m_Weaver.fail = true; + return; + } + + if (Helpers.InheritsFromSyncList(fd.FieldType, m_Weaver)) + { + Log.Warning(string.Format("Script class [{0}] has [SyncVar] attribute on SyncList field {1}, SyncLists should not be marked with SyncVar.", m_td.FullName, fd.Name)); + break; + } + + m_SyncVars.Add(fd); + + ProcessSyncVar(fd, 1 << dirtyBitCounter); + dirtyBitCounter += 1; + numSyncVars += 1; + + if (dirtyBitCounter == k_SyncVarLimit) + { + Log.Error("Script class [" + m_td.FullName + "] has too many SyncVars (" + k_SyncVarLimit + "). (This could include base classes)"); + m_Weaver.fail = true; + return; + } + break; + } + } + + if (fd.FieldType.FullName.Contains("UnityEngine.Networking.SyncListStruct")) + { + Log.Error("SyncListStruct member variable [" + fd.FullName + "] must use a dervied class, like \"class MySyncList : SyncListStruct {}\"."); + m_Weaver.fail = true; + return; + } + + if (m_Weaver.IsDerivedFrom(fd.FieldType.Resolve(), m_Weaver.SyncListType)) + { + if (fd.IsStatic) + { + Log.Error("SyncList [" + m_td.FullName + ":" + fd.FullName + "] cannot be a static"); + m_Weaver.fail = true; + return; + } + + m_SyncVars.Add(fd); + m_SyncLists.Add(fd); + listFields.Add(ProcessSyncList(fd, 1 << dirtyBitCounter)); + dirtyBitCounter += 1; + numSyncVars += 1; + + if (dirtyBitCounter == k_SyncVarLimit) + { + Log.Error("Script class [" + m_td.FullName + "] has too many SyncVars (" + k_SyncVarLimit + "). (This could include base classes)"); + m_Weaver.fail = true; + return; + } + } + } + + foreach (FieldDefinition fd in listFields) + { + m_td.Fields.Add(fd); + m_SyncListStaticFields.Add(fd); + } + + foreach (FieldDefinition fd in m_SyncVarNetIds) + { + m_td.Fields.Add(fd); + } + + foreach (var func in m_SyncListInvocationFuncs) + { + m_td.Methods.Add(func); + } + + m_Weaver.SetNumSyncVars(m_td.FullName, numSyncVars); + } + + // Copy of Mono string.GetHashCode(), so that we generate same hashes regardless of runtime (mono/MS .NET) + private static int GetHashCode(string s) + { + unsafe + { + int length = s.Length; + fixed(char* c = s) + { + char* cc = c; + char* end = cc + length - 1; + int h = 0; + for (; cc < end; cc += 2) + { + h = (h << 5) - h + *cc; + h = (h << 5) - h + cc[1]; + } + ++end; + if (cc < end) + h = (h << 5) - h + *cc; + return h; + } + } + } + + bool HasMethod(string name) + { + foreach (var method in m_td.Methods) + { + if (method.Name == name) + { + return true; + } + } + return false; + } + }; +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/Tools/Weaver/UNetWeaver.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/Tools/Weaver/UNetWeaver.cs new file mode 100644 index 00000000..61e2d234 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/Tools/Weaver/UNetWeaver.cs @@ -0,0 +1,1906 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using Mono.Cecil; +using Mono.Cecil.Cil; +using System.Linq; +using Mono.Cecil.Pdb; +using Mono.Cecil.Mdb; + +namespace Unity.UNetWeaver +{ + public enum OutSymbolsFormat + { + None, + Pdb, + Mdb + } + + // This data is flushed each time - if we are run multiple times in the same process/domain + class WeaverLists + { + // [SyncVar] member variables that should be replaced + public List replacedFields = new List(); + // setter functions that replace [SyncVar] member variable references + public List replacementProperties = new List(); + // GameObject SyncVar generated netId fields + public List netIdFields = new List(); + + // [Command]/[ClientRpc] functions that should be replaced + public List replacedMethods = new List(); + // remote call functions that replace [Command]/[ClientRpc] references + public List replacementMethods = new List(); + + public HashSet replacementMethodNames = new HashSet(); + + // [SyncEvent] invoke functions that should be replaced + public List replacedEvents = new List(); + // remote call functions that replace [SyncEvent] references + public List replacementEvents = new List(); + + public Dictionary readFuncs; + public Dictionary readByReferenceFuncs; + public Dictionary writeFuncs; + + public List generatedReadFunctions = new List(); + public List generatedWriteFunctions = new List(); + + public TypeDefinition generateContainerClass; + public Dictionary numSyncVars = new Dictionary(); + } + + class Weaver + { + // UNetwork types + public TypeReference NetworkBehaviourType; + public TypeReference NetworkBehaviourType2; + public TypeReference MonoBehaviourType; + public TypeReference ScriptableObjectType; + public TypeReference NetworkConnectionType; + public TypeReference ULocalConnectionToServerType; + public TypeReference ULocalConnectionToClientType; + + public TypeReference MessageBaseType; + public TypeReference SyncListStructType; + + public MethodReference NetworkBehaviourDirtyBitsReference; + public TypeReference NetworkClientType; + public TypeReference NetworkServerType; + public TypeReference NetworkCRCType; + + public TypeReference NetworkReaderType; + public TypeDefinition NetworkReaderDef; + + public TypeReference NetworkWriterType; + public TypeDefinition NetworkWriterDef; + + public MethodReference NetworkWriterCtor; + public MethodReference NetworkReaderCtor; + public TypeReference MemoryStreamType; + public MethodReference MemoryStreamCtor; + public MethodReference getComponentReference; + public MethodReference getUNetIdReference; + public MethodReference getPlayerIdReference; + public TypeReference NetworkIdentityType; + public TypeReference NetworkInstanceIdType; + public TypeReference NetworkSceneIdType; + public TypeReference IEnumeratorType; + + public TypeReference ClientSceneType; + public MethodReference FindLocalObjectReference; + public MethodReference RegisterBehaviourReference; + public MethodReference ReadyConnectionReference; + + public TypeReference ComponentType; + + public TypeReference CmdDelegateReference; + public MethodReference CmdDelegateConstructor; + + public MethodReference NetworkReaderReadInt32; + + public MethodReference NetworkWriterWriteInt32; + public MethodReference NetworkWriterWriteInt16; + + public MethodReference NetworkServerGetActive; + public MethodReference NetworkServerGetLocalClientActive; + public MethodReference NetworkClientGetActive; + public MethodReference UBehaviourIsServer; + public MethodReference NetworkReaderReadPacked32; + public MethodReference NetworkReaderReadPacked64; + public MethodReference NetworkReaderReadByte; + public MethodReference NetworkWriterWritePacked32; + public MethodReference NetworkWriterWritePacked64; + + public MethodReference NetworkWriterWriteNetworkInstanceId; + public MethodReference NetworkWriterWriteNetworkSceneId; + + public MethodReference NetworkReaderReadNetworkInstanceId; + public MethodReference NetworkReaderReadNetworkSceneId; + public MethodReference NetworkInstanceIsEmpty; + + public MethodReference NetworkReadUInt16; + public MethodReference NetworkWriteUInt16; + + // custom attribute types + public TypeReference SyncVarType; + public TypeReference CommandType; + public TypeReference ClientRpcType; + public TypeReference TargetRpcType; + public TypeReference SyncEventType; + public TypeReference SyncListType; + public MethodReference SyncListInitBehaviourReference; + public MethodReference SyncListInitHandleMsg; + public MethodReference SyncListClear; + public TypeReference NetworkSettingsType; + + // sync list types + public TypeReference SyncListFloatType; + public TypeReference SyncListIntType; + public TypeReference SyncListUIntType; + public TypeReference SyncListBoolType; + public TypeReference SyncListStringType; + + public MethodReference SyncListFloatReadType; + public MethodReference SyncListIntReadType; + public MethodReference SyncListUIntReadType; + public MethodReference SyncListStringReadType; + public MethodReference SyncListBoolReadType; + + public MethodReference SyncListFloatWriteType; + public MethodReference SyncListIntWriteType; + public MethodReference SyncListUIntWriteType; + public MethodReference SyncListBoolWriteType; + public MethodReference SyncListStringWriteType; + + // system types + public TypeReference voidType; + public TypeReference singleType; + public TypeReference doubleType; + public TypeReference decimalType; + public TypeReference boolType; + public TypeReference stringType; + public TypeReference int64Type; + public TypeReference uint64Type; + public TypeReference int32Type; + public TypeReference uint32Type; + public TypeReference int16Type; + public TypeReference uint16Type; + public TypeReference byteType; + public TypeReference sbyteType; + public TypeReference charType; + public TypeReference objectType; + public TypeReference valueTypeType; + public TypeReference vector2Type; + public TypeReference vector3Type; + public TypeReference vector4Type; + public TypeReference colorType; + public TypeReference color32Type; + public TypeReference quaternionType; + public TypeReference rectType; + public TypeReference rayType; + public TypeReference planeType; + public TypeReference matrixType; + public TypeReference hashType; + public TypeReference typeType; + public TypeReference gameObjectType; + public TypeReference transformType; + public TypeReference unityObjectType; + public MethodReference gameObjectInequality; + + public MethodReference setSyncVarReference; + public MethodReference setSyncVarHookGuard; + public MethodReference getSyncVarHookGuard; + public MethodReference setSyncVarGameObjectReference; + public MethodReference registerCommandDelegateReference; + public MethodReference registerRpcDelegateReference; + public MethodReference registerEventDelegateReference; + public MethodReference registerSyncListDelegateReference; + public MethodReference getTypeReference; + public MethodReference getTypeFromHandleReference; + public MethodReference logErrorReference; + public MethodReference logWarningReference; + public MethodReference sendCommandInternal; + public MethodReference sendRpcInternal; + public MethodReference sendTargetRpcInternal; + public MethodReference sendEventInternal; + + public WeaverLists lists; + + public AssemblyDefinition m_ScriptDef; + public ModuleDefinition m_CorLib; + public AssemblyDefinition m_UnityAssemblyDefinition; + public AssemblyDefinition m_UNetAssemblyDefinition; + + bool m_DebugFlag = true; + + public bool fail; + public bool generateLogErrors = false; + + // this is used to prevent stack overflows when generating serialization code when there are self-referencing types. + // All the utility classes use GetWriteFunc() to generate serialization code, so the recursion check is implemented there instead of in each utility class. + // A NetworkBehaviour with the max SyncVars (32) can legitimately increment this value to 65 - so max must be higher than that + const int MaxRecursionCount = 128; + int s_RecursionCount; + + public Weaver() { } + public void ResetRecursionCount() + { + s_RecursionCount = 0; + } + + public bool CanBeResolved(TypeReference parent) + { + while (parent != null) + { + if (parent.Scope.Name == "Windows") + { + return false; + } + + if (parent.Scope.Name == "mscorlib") + { + var resolved = parent.Resolve(); + return resolved != null; + } + + try + { + parent = parent.Resolve().BaseType; + } + catch + { + return false; + } + } + return true; + } + + public bool IsArrayType(TypeReference variable) + { + if ((variable.IsArray && ((ArrayType)variable).ElementType.IsArray) || // jagged array + (variable.IsArray && ((ArrayType)variable).Rank > 1)) // multidimensional array + return false; + return true; + } + + public void DLog(TypeDefinition td, string fmt, params object[] args) + { + if (!m_DebugFlag) + return; + + Console.WriteLine("[" + td.Name + "] " + String.Format(fmt, args)); + } + + public int GetSyncVarStart(string className) + { + if (lists.numSyncVars.ContainsKey(className)) + { + int num = lists.numSyncVars[className]; + return num; + } + // start at zero + return 0; + } + + public void SetNumSyncVars(string className, int num) + { + lists.numSyncVars[className] = num; + } + + public MethodReference GetWriteFunc(TypeReference variable) + { + if (s_RecursionCount++ > MaxRecursionCount) + { + Log.Error("GetWriteFunc recursion depth exceeded for " + variable.Name + ". Check for self-referencing member variables."); + fail = true; + return null; + } + + if (lists.writeFuncs.ContainsKey(variable.FullName)) + { + var foundFunc = lists.writeFuncs[variable.FullName]; + if (foundFunc.Parameters[0].ParameterType.IsArray == variable.IsArray) + { + return foundFunc; + } + } + + if (variable.IsByReference) + { + // error?? + Log.Error("GetWriteFunc variable.IsByReference error."); + return null; + } + + MethodDefinition newWriterFunc; + + if (variable.IsArray) + { + var elementType = variable.GetElementType(); + var elemenWriteFunc = GetWriteFunc(elementType); + if (elemenWriteFunc == null) + { + return null; + } + newWriterFunc = GenerateArrayWriteFunc(variable, elemenWriteFunc); + } + else + { + if (variable.Resolve().IsEnum) + { + return NetworkWriterWriteInt32; + } + + newWriterFunc = GenerateWriterFunction(variable); + } + + if (newWriterFunc == null) + { + return null; + } + + RegisterWriteFunc(variable.FullName, newWriterFunc); + return newWriterFunc; + } + + public void RegisterWriteFunc(string name, MethodDefinition newWriterFunc) + { + lists.writeFuncs[name] = newWriterFunc; + lists.generatedWriteFunctions.Add(newWriterFunc); + + ConfirmGeneratedCodeClass(m_ScriptDef.MainModule); + lists.generateContainerClass.Methods.Add(newWriterFunc); + } + + public MethodReference GetReadByReferenceFunc(TypeReference variable) + { + if (lists.readByReferenceFuncs.ContainsKey(variable.FullName)) + { + return lists.readByReferenceFuncs[variable.FullName]; + } + return null; + } + + public MethodReference GetReadFunc(TypeReference variable) + { + if (lists.readFuncs.ContainsKey(variable.FullName)) + { + var foundFunc = lists.readFuncs[variable.FullName]; + if (foundFunc.ReturnType.IsArray == variable.IsArray) + { + return foundFunc; + } + } + + var td = variable.Resolve(); + if (td == null) + { + Log.Error("GetReadFunc unsupported type " + variable.FullName); + return null; + } + + if (variable.IsByReference) + { + // error?? + Log.Error("GetReadFunc variable.IsByReference error."); + return null; + } + + MethodDefinition newReaderFunc; + + if (variable.IsArray) + { + var elementType = variable.GetElementType(); + var elementReadFunc = GetReadFunc(elementType); + if (elementReadFunc == null) + { + return null; + } + newReaderFunc = GenerateArrayReadFunc(variable, elementReadFunc); + } + else + { + if (td.IsEnum) + { + return NetworkReaderReadInt32; + } + + newReaderFunc = GenerateReadFunction(variable); + } + + if (newReaderFunc == null) + { + Log.Error("GetReadFunc unable to generate function for:" + variable.FullName); + return null; + } + RegisterReadFunc(variable.FullName, newReaderFunc); + return newReaderFunc; + } + + public void RegisterReadByReferenceFunc(string name, MethodDefinition newReaderFunc) + { + lists.readByReferenceFuncs[name] = newReaderFunc; + lists.generatedReadFunctions.Add(newReaderFunc); + + ConfirmGeneratedCodeClass(m_ScriptDef.MainModule); + lists.generateContainerClass.Methods.Add(newReaderFunc); + } + + public void RegisterReadFunc(string name, MethodDefinition newReaderFunc) + { + lists.readFuncs[name] = newReaderFunc; + lists.generatedReadFunctions.Add(newReaderFunc); + + ConfirmGeneratedCodeClass(m_ScriptDef.MainModule); + lists.generateContainerClass.Methods.Add(newReaderFunc); + } + + MethodDefinition GenerateArrayReadFunc(TypeReference variable, MethodReference elementReadFunc) + { + if (!IsArrayType(variable)) + { + Log.Error(variable.FullName + " is an unsupported array type. Jagged and multidimensional arrays are not supported"); + return null; + } + var functionName = "_ReadArray" + variable.GetElementType().Name + "_"; + if (variable.DeclaringType != null) + { + functionName += variable.DeclaringType.Name; + } + else + { + functionName += "None"; + } + + // create new reader for this type + MethodDefinition readerFunc = new MethodDefinition(functionName, + MethodAttributes.Public | + MethodAttributes.Static | + MethodAttributes.HideBySig, + variable); + + readerFunc.Parameters.Add(new ParameterDefinition("reader", ParameterAttributes.None, m_ScriptDef.MainModule.ImportReference(NetworkReaderType))); + + readerFunc.Body.Variables.Add(new VariableDefinition(int32Type)); + readerFunc.Body.Variables.Add(new VariableDefinition(variable)); + readerFunc.Body.Variables.Add(new VariableDefinition(int32Type)); + readerFunc.Body.InitLocals = true; + + ILProcessor worker = readerFunc.Body.GetILProcessor(); + + worker.Append(worker.Create(OpCodes.Ldarg_0)); + worker.Append(worker.Create(OpCodes.Call, NetworkReadUInt16)); + worker.Append(worker.Create(OpCodes.Stloc_0)); + worker.Append(worker.Create(OpCodes.Ldloc_0)); + + Instruction labelEmptyArray = worker.Create(OpCodes.Nop); + worker.Append(worker.Create(OpCodes.Brtrue, labelEmptyArray)); + + // return empty array + worker.Append(worker.Create(OpCodes.Ldc_I4_0)); + worker.Append(worker.Create(OpCodes.Newarr, variable.GetElementType())); + worker.Append(worker.Create(OpCodes.Ret)); + + // create the actual array + worker.Append(labelEmptyArray); + worker.Append(worker.Create(OpCodes.Ldloc_0)); + worker.Append(worker.Create(OpCodes.Newarr, variable.GetElementType())); + worker.Append(worker.Create(OpCodes.Stloc_1)); + worker.Append(worker.Create(OpCodes.Ldc_I4_0)); + worker.Append(worker.Create(OpCodes.Stloc_2)); + + // loop start + Instruction labelHead = worker.Create(OpCodes.Nop); + worker.Append(worker.Create(OpCodes.Br, labelHead)); + + // loop body + Instruction labelBody = worker.Create(OpCodes.Nop); + worker.Append(labelBody); + worker.Append(worker.Create(OpCodes.Ldloc_1)); + worker.Append(worker.Create(OpCodes.Ldloc_2)); + worker.Append(worker.Create(OpCodes.Ldelema, variable.GetElementType())); + worker.Append(worker.Create(OpCodes.Ldarg_0)); + worker.Append(worker.Create(OpCodes.Call, elementReadFunc)); + worker.Append(worker.Create(OpCodes.Stobj, variable.GetElementType())); + worker.Append(worker.Create(OpCodes.Ldloc_2)); + worker.Append(worker.Create(OpCodes.Ldc_I4_1)); + worker.Append(worker.Create(OpCodes.Add)); + worker.Append(worker.Create(OpCodes.Stloc_2)); + + // loop while check + worker.Append(labelHead); + worker.Append(worker.Create(OpCodes.Ldloc_2)); + worker.Append(worker.Create(OpCodes.Ldloc_0)); + worker.Append(worker.Create(OpCodes.Blt, labelBody)); + + worker.Append(worker.Create(OpCodes.Ldloc_1)); + worker.Append(worker.Create(OpCodes.Ret)); + return readerFunc; + } + + MethodDefinition GenerateArrayWriteFunc(TypeReference variable, MethodReference elementWriteFunc) + { + if (!IsArrayType(variable)) + { + Log.Error(variable.FullName + " is an unsupported array type. Jagged and multidimensional arrays are not supported"); + return null; + } + var functionName = "_WriteArray" + variable.GetElementType().Name + "_"; + if (variable.DeclaringType != null) + { + functionName += variable.DeclaringType.Name; + } + else + { + functionName += "None"; + } + + // create new writer for this type + MethodDefinition writerFunc = new MethodDefinition(functionName, + MethodAttributes.Public | + MethodAttributes.Static | + MethodAttributes.HideBySig, + voidType); + + writerFunc.Parameters.Add(new ParameterDefinition("writer", ParameterAttributes.None, m_ScriptDef.MainModule.ImportReference(NetworkWriterType))); + writerFunc.Parameters.Add(new ParameterDefinition("value", ParameterAttributes.None, m_ScriptDef.MainModule.ImportReference(variable))); + + writerFunc.Body.Variables.Add(new VariableDefinition(uint16Type)); + writerFunc.Body.Variables.Add(new VariableDefinition(uint16Type)); + writerFunc.Body.InitLocals = true; + + ILProcessor worker = writerFunc.Body.GetILProcessor(); + + // null check + Instruction labelNull = worker.Create(OpCodes.Nop); + worker.Append(worker.Create(OpCodes.Ldarg_1)); + worker.Append(worker.Create(OpCodes.Brtrue, labelNull)); + + worker.Append(worker.Create(OpCodes.Ldarg_0)); + worker.Append(worker.Create(OpCodes.Ldc_I4_0)); + worker.Append(worker.Create(OpCodes.Call, NetworkWriteUInt16)); + worker.Append(worker.Create(OpCodes.Ret)); + + // setup array length local variable + worker.Append(labelNull); + worker.Append(worker.Create(OpCodes.Ldarg_1)); + worker.Append(worker.Create(OpCodes.Ldlen)); + worker.Append(worker.Create(OpCodes.Conv_I4)); + worker.Append(worker.Create(OpCodes.Conv_U2)); + worker.Append(worker.Create(OpCodes.Stloc_0)); + + //write length + worker.Append(worker.Create(OpCodes.Ldarg_0)); + worker.Append(worker.Create(OpCodes.Ldloc_0)); + worker.Append(worker.Create(OpCodes.Call, NetworkWriteUInt16)); + + // start loop + worker.Append(worker.Create(OpCodes.Ldc_I4_0)); + worker.Append(worker.Create(OpCodes.Stloc_1)); + Instruction labelHead = worker.Create(OpCodes.Nop); + worker.Append(worker.Create(OpCodes.Br, labelHead)); + + // loop body + Instruction labelBody = worker.Create(OpCodes.Nop); + worker.Append(labelBody); + worker.Append(worker.Create(OpCodes.Ldarg_0)); + worker.Append(worker.Create(OpCodes.Ldarg_1)); + worker.Append(worker.Create(OpCodes.Ldloc_1)); + worker.Append(worker.Create(OpCodes.Ldelema, variable.GetElementType())); + worker.Append(worker.Create(OpCodes.Ldobj, variable.GetElementType())); + worker.Append(worker.Create(OpCodes.Call, elementWriteFunc)); + worker.Append(worker.Create(OpCodes.Ldloc_1)); + worker.Append(worker.Create(OpCodes.Ldc_I4_1)); + worker.Append(worker.Create(OpCodes.Add)); + worker.Append(worker.Create(OpCodes.Conv_U2)); + worker.Append(worker.Create(OpCodes.Stloc_1)); + + // loop while check + worker.Append(labelHead); + worker.Append(worker.Create(OpCodes.Ldloc_1)); + worker.Append(worker.Create(OpCodes.Ldarg_1)); + worker.Append(worker.Create(OpCodes.Ldlen)); + worker.Append(worker.Create(OpCodes.Conv_I4)); + worker.Append(worker.Create(OpCodes.Blt, labelBody)); + + worker.Append(worker.Create(OpCodes.Ret)); + return writerFunc; + } + + MethodDefinition GenerateWriterFunction(TypeReference variable) + { + if (!IsValidTypeToGenerate(variable.Resolve())) + { + return null; + } + + var functionName = "_Write" + variable.Name + "_"; + if (variable.DeclaringType != null) + { + functionName += variable.DeclaringType.Name; + } + else + { + functionName += "None"; + } + // create new writer for this type + MethodDefinition writerFunc = new MethodDefinition(functionName, + MethodAttributes.Public | + MethodAttributes.Static | + MethodAttributes.HideBySig, + voidType); + + writerFunc.Parameters.Add(new ParameterDefinition("writer", ParameterAttributes.None, m_ScriptDef.MainModule.ImportReference(NetworkWriterType))); + writerFunc.Parameters.Add(new ParameterDefinition("value", ParameterAttributes.None, m_ScriptDef.MainModule.ImportReference(variable))); + + ILProcessor worker = writerFunc.Body.GetILProcessor(); + + uint fields = 0; + foreach (var field in variable.Resolve().Fields) + { + if (field.IsStatic || field.IsPrivate) + continue; + + if (field.FieldType.Resolve().HasGenericParameters) + { + fail = true; + Log.Error("WriteReadFunc for " + field.Name + " [" + field.FieldType + "/" + field.FieldType.FullName + "]. Cannot have generic parameters."); + return null; + } + + if (field.FieldType.Resolve().IsInterface) + { + fail = true; + Log.Error("WriteReadFunc for " + field.Name + " [" + field.FieldType + "/" + field.FieldType.FullName + "]. Cannot be an interface."); + return null; + } + + var writeFunc = GetWriteFunc(field.FieldType); + if (writeFunc != null) + { + fields++; + worker.Append(worker.Create(OpCodes.Ldarg_0)); + worker.Append(worker.Create(OpCodes.Ldarg_1)); + worker.Append(worker.Create(OpCodes.Ldfld, field)); + worker.Append(worker.Create(OpCodes.Call, writeFunc)); + } + else + { + Log.Error("WriteReadFunc for " + field.Name + " type " + field.FieldType + " no supported"); + fail = true; + return null; + } + } + if (fields == 0) + { + Log.Warning("The class / struct " + variable.Name + " has no public or non-fields to serialize"); + } + worker.Append(worker.Create(OpCodes.Ret)); + return writerFunc; + } + + MethodDefinition GenerateReadFunction(TypeReference variable) + { + if (!IsValidTypeToGenerate(variable.Resolve())) + { + return null; + } + + var functionName = "_Read" + variable.Name + "_"; + if (variable.DeclaringType != null) + { + functionName += variable.DeclaringType.Name; + } + else + { + functionName += "None"; + } + + // create new reader for this type + MethodDefinition readerFunc = new MethodDefinition(functionName, + MethodAttributes.Public | + MethodAttributes.Static | + MethodAttributes.HideBySig, + variable); + + // create local for return value + readerFunc.Body.Variables.Add(new VariableDefinition(variable)); + readerFunc.Body.InitLocals = true; + + readerFunc.Parameters.Add(new ParameterDefinition("reader", ParameterAttributes.None, m_ScriptDef.MainModule.ImportReference(NetworkReaderType))); + + ILProcessor worker = readerFunc.Body.GetILProcessor(); + + if (variable.IsValueType) + { + // structs are created with Initobj + worker.Append(worker.Create(OpCodes.Ldloca, 0)); + worker.Append(worker.Create(OpCodes.Initobj, variable)); + } + else + { + // classes are created with their constructor + + var ctor = ResolveDefaultPublicCtor(variable); + if (ctor == null) + { + Log.Error("The class " + variable.Name + " has no default constructor or it's private, aborting."); + return null; + } + + worker.Append(worker.Create(OpCodes.Newobj, ctor)); + worker.Append(worker.Create(OpCodes.Stloc_0)); + } + + uint fields = 0; + foreach (var field in variable.Resolve().Fields) + { + if (field.IsStatic || field.IsPrivate) + continue; + + // mismatched ldloca/ldloc for struct/class combinations is invalid IL, which causes crash at runtime + if (variable.IsValueType) + { + worker.Append(worker.Create(OpCodes.Ldloca, 0)); + } + else + { + worker.Append(worker.Create(OpCodes.Ldloc, 0)); + } + + var readFunc = GetReadFunc(field.FieldType); + if (readFunc != null) + { + worker.Append(worker.Create(OpCodes.Ldarg_0)); + worker.Append(worker.Create(OpCodes.Call, readFunc)); + } + else + { + Log.Error("GetReadFunc for " + field.Name + " type " + field.FieldType + " no supported"); + fail = true; + return null; + } + + worker.Append(worker.Create(OpCodes.Stfld, field)); + fields++; + } + if (fields == 0) + { + Log.Warning("The class / struct " + variable.Name + " has no public or non-fields to serialize"); + } + + worker.Append(worker.Create(OpCodes.Ldloc_0)); + worker.Append(worker.Create(OpCodes.Ret)); + return readerFunc; + } + + Instruction GetEventLoadInstruction(ModuleDefinition moduleDef, TypeDefinition td, MethodDefinition md, int iCount, FieldReference foundEventField) + { + // go backwards until find a ldfld instruction for this event field + while (iCount > 0) + { + iCount -= 1; + Instruction inst = md.Body.Instructions[iCount]; + if (inst.OpCode == OpCodes.Ldfld) + { + if (inst.Operand == foundEventField) + { + DLog(td, " " + inst.Operand); + return inst; + } + } + } + return null; + } + + void ProcessInstructionMethod(ModuleDefinition moduleDef, TypeDefinition td, MethodDefinition md, Instruction instr, MethodReference opMethodRef, int iCount) + { + //DLog(td, "ProcessInstructionMethod " + opMethod.Name); + if (opMethodRef.Name == "Invoke") + { + // Events use an "Invoke" method to call the delegate. + // this code replaces the "Invoke" instruction with the generated "Call***" instruction which send the event to the server. + // but the "Invoke" instruction is called on the event field - where the "call" instruction is not. + // so the earlier instruction that loads the event field is replaced with a Noop. + + // go backwards until find a ldfld instruction that matches ANY event + bool found = false; + while (iCount > 0 && !found) + { + iCount -= 1; + Instruction inst = md.Body.Instructions[iCount]; + if (inst.OpCode == OpCodes.Ldfld) + { + var opField = inst.Operand as FieldReference; + + // find replaceEvent with matching name + for (int n = 0; n < lists.replacedEvents.Count; n++) + { + EventDefinition foundEvent = lists.replacedEvents[n]; + if (foundEvent.Name == opField.Name) + { + instr.Operand = lists.replacementEvents[n]; + inst.OpCode = OpCodes.Nop; + found = true; + break; + } + } + } + } + } + else + { + if (lists.replacementMethodNames.Contains(opMethodRef.FullName)) + { + for (int n = 0; n < lists.replacedMethods.Count; n++) + { + MethodDefinition foundMethod = lists.replacedMethods[n]; + if (opMethodRef.FullName == foundMethod.FullName) + { + //DLog(td, " replacing " + md.Name + ":" + i); + instr.Operand = lists.replacementMethods[n]; + //DLog(td, " replaced " + md.Name + ":" + i); + break; + } + } + } + } + } + + void ConfirmGeneratedCodeClass(ModuleDefinition moduleDef) + { + if (lists.generateContainerClass == null) + { + lists.generateContainerClass = new TypeDefinition("Unity", "GeneratedNetworkCode", + TypeAttributes.BeforeFieldInit | TypeAttributes.Class | TypeAttributes.AnsiClass | TypeAttributes.Public | TypeAttributes.AutoClass, + objectType); + + const MethodAttributes methodAttributes = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName; + var method = new MethodDefinition(".ctor", methodAttributes, voidType); + method.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0)); + method.Body.Instructions.Add(Instruction.Create(OpCodes.Call, ResolveMethod(objectType, ".ctor"))); + method.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); + + lists.generateContainerClass.Methods.Add(method); + } + } + + void ProcessInstructionField(TypeDefinition td, MethodDefinition md, Instruction i, FieldDefinition opField) + { + // dont replace property call sites in constructors or deserialize + if (md.Name == ".ctor" || md.Name == "OnDeserialize") + return; + + // does it set a field that we replaced? + for (int n = 0; n < lists.replacedFields.Count; n++) + { + FieldDefinition fd = lists.replacedFields[n]; + if (opField == fd) + { + //replace with property + //DLog(td, " replacing " + md.Name + ":" + i); + i.OpCode = OpCodes.Call; + i.Operand = lists.replacementProperties[n]; + //DLog(td, " replaced " + md.Name + ":" + i); + break; + } + } + } + + void ProcessInstruction(ModuleDefinition moduleDef, TypeDefinition td, MethodDefinition md, Instruction i, int iCount) + { + if (i.OpCode == OpCodes.Call || i.OpCode == OpCodes.Callvirt) + { + MethodReference opMethod = i.Operand as MethodReference; + if (opMethod != null) + { + ProcessInstructionMethod(moduleDef, td, md, i, opMethod, iCount); + } + } + + if (i.OpCode == OpCodes.Stfld) + { + // this instruction sets the value of a field. cache the field reference. + FieldDefinition opField = i.Operand as FieldDefinition; + if (opField != null) + { + ProcessInstructionField(td, md, i, opField); + } + } + } + + // this is required to early-out from a function with "ref" or "out" parameters + void InjectGuardParameters(MethodDefinition md, ILProcessor worker, Instruction top) + { + int offset = md.Resolve().IsStatic ? 0 : 1; + for (int index = 0; index < md.Parameters.Count; index++) + { + var param = md.Parameters[index]; + if (param.IsOut) + { + var elementType = param.ParameterType.GetElementType(); + if (elementType.IsPrimitive) + { + worker.InsertBefore(top, worker.Create(OpCodes.Ldarg, index + offset)); + worker.InsertBefore(top, worker.Create(OpCodes.Ldc_I4_0)); + worker.InsertBefore(top, worker.Create(OpCodes.Stind_I4)); + } + else + { + md.Body.Variables.Add(new VariableDefinition(elementType)); + md.Body.InitLocals = true; + + worker.InsertBefore(top, worker.Create(OpCodes.Ldarg, index + offset)); + worker.InsertBefore(top, worker.Create(OpCodes.Ldloca_S, (byte)(md.Body.Variables.Count - 1))); + worker.InsertBefore(top, worker.Create(OpCodes.Initobj, elementType)); + worker.InsertBefore(top, worker.Create(OpCodes.Ldloc, md.Body.Variables.Count - 1)); + worker.InsertBefore(top, worker.Create(OpCodes.Stobj, elementType)); + } + } + } + } + + // this is required to early-out from a function with a return value. + void InjectGuardReturnValue(MethodDefinition md, ILProcessor worker, Instruction top) + { + if (md.ReturnType.FullName != voidType.FullName) + { + if (md.ReturnType.IsPrimitive) + { + worker.InsertBefore(top, worker.Create(OpCodes.Ldc_I4_0)); + } + else + { + md.Body.Variables.Add(new VariableDefinition(md.ReturnType)); + md.Body.InitLocals = true; + + worker.InsertBefore(top, worker.Create(OpCodes.Ldloca_S, (byte)(md.Body.Variables.Count - 1))); + worker.InsertBefore(top, worker.Create(OpCodes.Initobj, md.ReturnType)); + worker.InsertBefore(top, worker.Create(OpCodes.Ldloc, md.Body.Variables.Count - 1)); + } + } + } + + void InjectServerGuard(ModuleDefinition moduleDef, TypeDefinition td, MethodDefinition md, bool logWarning) + { + if (!IsNetworkBehaviour(td)) + { + Log.Error("[Server] guard on non-NetworkBehaviour script at [" + md.FullName + "]"); + return; + } + ILProcessor worker = md.Body.GetILProcessor(); + Instruction top = md.Body.Instructions[0]; + + worker.InsertBefore(top, worker.Create(OpCodes.Call, NetworkServerGetActive)); + worker.InsertBefore(top, worker.Create(OpCodes.Brtrue, top)); + if (logWarning) + { + worker.InsertBefore(top, worker.Create(OpCodes.Ldstr, "[Server] function '" + md.FullName + "' called on client")); + worker.InsertBefore(top, worker.Create(OpCodes.Call, logWarningReference)); + } + InjectGuardParameters(md, worker, top); + InjectGuardReturnValue(md, worker, top); + worker.InsertBefore(top, worker.Create(OpCodes.Ret)); + } + + void InjectClientGuard(ModuleDefinition moduleDef, TypeDefinition td, MethodDefinition md, bool logWarning) + { + if (!IsNetworkBehaviour(td)) + { + Log.Error("[Client] guard on non-NetworkBehaviour script at [" + md.FullName + "]"); + return; + } + ILProcessor worker = md.Body.GetILProcessor(); + Instruction top = md.Body.Instructions[0]; + + worker.InsertBefore(top, worker.Create(OpCodes.Call, NetworkClientGetActive)); + worker.InsertBefore(top, worker.Create(OpCodes.Brtrue, top)); + if (logWarning) + { + worker.InsertBefore(top, worker.Create(OpCodes.Ldstr, "[Client] function '" + md.FullName + "' called on server")); + worker.InsertBefore(top, worker.Create(OpCodes.Call, logWarningReference)); + } + + InjectGuardParameters(md, worker, top); + InjectGuardReturnValue(md, worker, top); + worker.InsertBefore(top, worker.Create(OpCodes.Ret)); + } + + void ProcessSiteMethod(ModuleDefinition moduleDef, TypeDefinition td, MethodDefinition md) + { + // process all references to replaced members with properties + //Weaver.DLog(td, " ProcessSiteMethod " + md); + + if (md.Name == ".cctor" || md.Name == "OnUnserializeVars") + return; + + string prefix = md.Name.Substring(0, Math.Min(md.Name.Length, 4)); + + if (prefix == "UNet") + return; + + prefix = md.Name.Substring(0, Math.Min(md.Name.Length, 7)); + if (prefix == "CallCmd") + return; + + prefix = md.Name.Substring(0, Math.Min(md.Name.Length, 9)); + if (prefix == "InvokeCmd" || prefix == "InvokeRpc" || prefix == "InvokeSyn") + return; + + if (md.Body != null && md.Body.Instructions != null) + { + foreach (CustomAttribute attr in md.CustomAttributes) + { + if (attr.Constructor.DeclaringType.ToString() == "UnityEngine.Networking.ServerAttribute") + { + InjectServerGuard(moduleDef, td, md, true); + } + else if (attr.Constructor.DeclaringType.ToString() == "UnityEngine.Networking.ServerCallbackAttribute") + { + InjectServerGuard(moduleDef, td, md, false); + } + else if (attr.Constructor.DeclaringType.ToString() == "UnityEngine.Networking.ClientAttribute") + { + InjectClientGuard(moduleDef, td, md, true); + } + else if (attr.Constructor.DeclaringType.ToString() == "UnityEngine.Networking.ClientCallbackAttribute") + { + InjectClientGuard(moduleDef, td, md, false); + } + } + + int iCount = 0; + foreach (Instruction i in md.Body.Instructions) + { + ProcessInstruction(moduleDef, td, md, i, iCount); + iCount += 1; + } + } + } + + void ProcessSiteClass(ModuleDefinition moduleDef, TypeDefinition td) + { + //Console.WriteLine(" ProcessSiteClass " + td); + foreach (MethodDefinition md in td.Methods) + { + ProcessSiteMethod(moduleDef, td, md); + } + + foreach (var nested in td.NestedTypes) + { + ProcessSiteClass(moduleDef, nested); + } + } + + void ProcessSitesModule(ModuleDefinition moduleDef) + { + var startTime = System.DateTime.Now; + + //Search through the types + foreach (TypeDefinition td in moduleDef.Types) + { + if (td.IsClass) + { + ProcessSiteClass(moduleDef, td); + } + } + if (lists.generateContainerClass != null) + { + moduleDef.Types.Add(lists.generateContainerClass); + m_ScriptDef.MainModule.ImportReference(lists.generateContainerClass); + + foreach (var f in lists.generatedReadFunctions) + { + m_ScriptDef.MainModule.ImportReference(f); + } + + foreach (var f in lists.generatedWriteFunctions) + { + m_ScriptDef.MainModule.ImportReference(f); + } + } + Console.WriteLine(" ProcessSitesModule " + moduleDef.Name + " elapsed time:" + (System.DateTime.Now - startTime)); + } + + void ProcessPropertySites() + { + ProcessSitesModule(m_ScriptDef.MainModule); + } + + bool ProcessMessageType(TypeDefinition td) + { + var proc = new MessageClassProcessor(td, this); + proc.Process(); + return true; + } + + bool ProcessSyncListStructType(TypeDefinition td) + { + var proc = new SyncListStructProcessor(td, this); + proc.Process(); + return true; + } + + void ProcessMonoBehaviourType(TypeDefinition td) + { + var proc = new MonoBehaviourProcessor(td, this); + proc.Process(); + } + + bool ProcessNetworkBehaviourType(TypeDefinition td) + { + foreach (var md in td.Resolve().Methods) + { + if (md.Name == "UNetVersion") + { + DLog(td, " Already processed"); + return false; // did no work + } + } + DLog(td, "Found NetworkBehaviour " + td.FullName); + + NetworkBehaviourProcessor proc = new NetworkBehaviourProcessor(td, this); + proc.Process(); + return true; + } + + public MethodReference ResolveMethod(TypeReference t, string name) + { + //Console.WriteLine("ResolveMethod " + t.ToString () + " " + name); + if (t == null) + { + Log.Error("Type missing for " + name); + fail = true; + return null; + } + foreach (var methodRef in t.Resolve().Methods) + { + if (methodRef.Name == name) + { + return m_ScriptDef.MainModule.ImportReference(methodRef); + } + } + Log.Error("ResolveMethod failed " + t.Name + "::" + name + " " + t.Resolve()); + + // why did it fail!? + foreach (var methodRef in t.Resolve().Methods) + { + Log.Error("Method " + methodRef.Name); + } + + fail = true; + return null; + } + + MethodReference ResolveMethodWithArg(TypeReference t, string name, TypeReference argType) + { + foreach (var methodRef in t.Resolve().Methods) + { + if (methodRef.Name == name) + { + if (methodRef.Parameters.Count == 1) + { + if (methodRef.Parameters[0].ParameterType.FullName == argType.FullName) + { + return m_ScriptDef.MainModule.ImportReference(methodRef); + } + } + } + } + Log.Error("ResolveMethodWithArg failed " + t.Name + "::" + name + " " + argType); + fail = true; + return null; + } + + MethodDefinition ResolveDefaultPublicCtor(TypeReference variable) + { + foreach (MethodDefinition methodRef in variable.Resolve().Methods) + { + if (methodRef.Name == ".ctor" && + methodRef.Resolve().IsPublic && + methodRef.Parameters.Count == 0) + { + return methodRef; + } + } + return null; + } + + GenericInstanceMethod ResolveMethodGeneric(TypeReference t, string name, TypeReference genericType) + { + foreach (var methodRef in t.Resolve().Methods) + { + if (methodRef.Name == name) + { + if (methodRef.Parameters.Count == 0) + { + if (methodRef.GenericParameters.Count == 1) + { + MethodReference tmp = m_ScriptDef.MainModule.ImportReference(methodRef); + GenericInstanceMethod gm = new GenericInstanceMethod(tmp); + gm.GenericArguments.Add(genericType); + if (gm.GenericArguments[0].FullName == genericType.FullName) + { + return gm; + } + } + } + } + } + + Log.Error("ResolveMethodGeneric failed " + t.Name + "::" + name + " " + genericType); + fail = true; + return null; + } + + public FieldReference ResolveField(TypeReference t, string name) + { + foreach (FieldDefinition fd in t.Resolve().Fields) + { + if (fd.Name == name) + { + return m_ScriptDef.MainModule.ImportReference(fd); + } + } + return null; + } + + public MethodReference ResolveProperty(TypeReference t, string name) + { + foreach (var fd in t.Resolve().Properties) + { + if (fd.Name == name) + { + return m_ScriptDef.MainModule.ImportReference(fd.GetMethod); + } + } + return null; + } + + void SetupUnityTypes() + { + vector2Type = m_UnityAssemblyDefinition.MainModule.GetType("UnityEngine.Vector2"); + vector3Type = m_UnityAssemblyDefinition.MainModule.GetType("UnityEngine.Vector3"); + vector4Type = m_UnityAssemblyDefinition.MainModule.GetType("UnityEngine.Vector4"); + colorType = m_UnityAssemblyDefinition.MainModule.GetType("UnityEngine.Color"); + color32Type = m_UnityAssemblyDefinition.MainModule.GetType("UnityEngine.Color32"); + quaternionType = m_UnityAssemblyDefinition.MainModule.GetType("UnityEngine.Quaternion"); + rectType = m_UnityAssemblyDefinition.MainModule.GetType("UnityEngine.Rect"); + planeType = m_UnityAssemblyDefinition.MainModule.GetType("UnityEngine.Plane"); + rayType = m_UnityAssemblyDefinition.MainModule.GetType("UnityEngine.Ray"); + matrixType = m_UnityAssemblyDefinition.MainModule.GetType("UnityEngine.Matrix4x4"); + gameObjectType = m_UnityAssemblyDefinition.MainModule.GetType("UnityEngine.GameObject"); + transformType = m_UnityAssemblyDefinition.MainModule.GetType("UnityEngine.Transform"); + unityObjectType = m_UnityAssemblyDefinition.MainModule.GetType("UnityEngine.Object"); + + hashType = m_UNetAssemblyDefinition.MainModule.GetType("UnityEngine.Networking.NetworkHash128"); + NetworkClientType = m_UNetAssemblyDefinition.MainModule.GetType("UnityEngine.Networking.NetworkClient"); + NetworkServerType = m_UNetAssemblyDefinition.MainModule.GetType("UnityEngine.Networking.NetworkServer"); + NetworkCRCType = m_UNetAssemblyDefinition.MainModule.GetType("UnityEngine.Networking.NetworkCRC"); + + SyncVarType = m_UNetAssemblyDefinition.MainModule.GetType("UnityEngine.Networking.SyncVarAttribute"); + CommandType = m_UNetAssemblyDefinition.MainModule.GetType("UnityEngine.Networking.CommandAttribute"); + ClientRpcType = m_UNetAssemblyDefinition.MainModule.GetType("UnityEngine.Networking.ClientRpcAttribute"); + TargetRpcType = m_UNetAssemblyDefinition.MainModule.GetType("UnityEngine.Networking.TargetRpcAttribute"); + SyncEventType = m_UNetAssemblyDefinition.MainModule.GetType("UnityEngine.Networking.SyncEventAttribute"); + SyncListType = m_UNetAssemblyDefinition.MainModule.GetType("UnityEngine.Networking.SyncList`1"); + NetworkSettingsType = m_UNetAssemblyDefinition.MainModule.GetType("UnityEngine.Networking.NetworkSettingsAttribute"); + + SyncListFloatType = m_UNetAssemblyDefinition.MainModule.GetType("UnityEngine.Networking.SyncListFloat"); + SyncListIntType = m_UNetAssemblyDefinition.MainModule.GetType("UnityEngine.Networking.SyncListInt"); + SyncListUIntType = m_UNetAssemblyDefinition.MainModule.GetType("UnityEngine.Networking.SyncListUInt"); + SyncListBoolType = m_UNetAssemblyDefinition.MainModule.GetType("UnityEngine.Networking.SyncListBool"); + SyncListStringType = m_UNetAssemblyDefinition.MainModule.GetType("UnityEngine.Networking.SyncListString"); + } + + void SetupCorLib() + { + var name = AssemblyNameReference.Parse("mscorlib"); + var parameters = new ReaderParameters + { + AssemblyResolver = m_ScriptDef.MainModule.AssemblyResolver, + }; + m_CorLib = m_ScriptDef.MainModule.AssemblyResolver.Resolve(name, parameters).MainModule; + } + + TypeReference ImportCorLibType(string fullName) + { + var type = m_CorLib.GetType(fullName) ?? m_CorLib.ExportedTypes.First(t => t.FullName == fullName).Resolve(); + return m_ScriptDef.MainModule.ImportReference(type); + } + + void SetupTargetTypes() + { + // system types + SetupCorLib(); + voidType = ImportCorLibType("System.Void"); + singleType = ImportCorLibType("System.Single"); + doubleType = ImportCorLibType("System.Double"); + decimalType = ImportCorLibType("System.Decimal"); + boolType = ImportCorLibType("System.Boolean"); + stringType = ImportCorLibType("System.String"); + int64Type = ImportCorLibType("System.Int64"); + uint64Type = ImportCorLibType("System.UInt64"); + int32Type = ImportCorLibType("System.Int32"); + uint32Type = ImportCorLibType("System.UInt32"); + int16Type = ImportCorLibType("System.Int16"); + uint16Type = ImportCorLibType("System.UInt16"); + byteType = ImportCorLibType("System.Byte"); + sbyteType = ImportCorLibType("System.SByte"); + charType = ImportCorLibType("System.Char"); + objectType = ImportCorLibType("System.Object"); + valueTypeType = ImportCorLibType("System.ValueType"); + typeType = ImportCorLibType("System.Type"); + IEnumeratorType = ImportCorLibType("System.Collections.IEnumerator"); + MemoryStreamType = ImportCorLibType("System.IO.MemoryStream"); + + NetworkReaderType = m_UNetAssemblyDefinition.MainModule.GetType("UnityEngine.Networking.NetworkReader"); + NetworkReaderDef = NetworkReaderType.Resolve(); + + NetworkReaderCtor = ResolveMethod(NetworkReaderDef, ".ctor"); + + NetworkWriterType = m_UNetAssemblyDefinition.MainModule.GetType("UnityEngine.Networking.NetworkWriter"); + NetworkWriterDef = NetworkWriterType.Resolve(); + + NetworkWriterCtor = ResolveMethod(NetworkWriterDef, ".ctor"); + + MemoryStreamCtor = ResolveMethod(MemoryStreamType, ".ctor"); + + NetworkInstanceIdType = m_UNetAssemblyDefinition.MainModule.GetType("UnityEngine.Networking.NetworkInstanceId"); + NetworkSceneIdType = m_UNetAssemblyDefinition.MainModule.GetType("UnityEngine.Networking.NetworkSceneId"); + + NetworkInstanceIdType = m_UNetAssemblyDefinition.MainModule.GetType("UnityEngine.Networking.NetworkInstanceId"); + NetworkSceneIdType = m_UNetAssemblyDefinition.MainModule.GetType("UnityEngine.Networking.NetworkSceneId"); + + NetworkServerGetActive = ResolveMethod(NetworkServerType, "get_active"); + NetworkServerGetLocalClientActive = ResolveMethod(NetworkServerType, "get_localClientActive"); + NetworkClientGetActive = ResolveMethod(NetworkClientType, "get_active"); + + NetworkReaderReadInt32 = ResolveMethod(NetworkReaderType, "ReadInt32"); + + NetworkWriterWriteInt32 = ResolveMethodWithArg(NetworkWriterType, "Write", int32Type); + NetworkWriterWriteInt16 = ResolveMethodWithArg(NetworkWriterType, "Write", int16Type); + + NetworkReaderReadPacked32 = ResolveMethod(NetworkReaderType, "ReadPackedUInt32"); + NetworkReaderReadPacked64 = ResolveMethod(NetworkReaderType, "ReadPackedUInt64"); + NetworkReaderReadByte = ResolveMethod(NetworkReaderType, "ReadByte"); + + NetworkWriterWritePacked32 = ResolveMethod(NetworkWriterType, "WritePackedUInt32"); + NetworkWriterWritePacked64 = ResolveMethod(NetworkWriterType, "WritePackedUInt64"); + + NetworkWriterWriteNetworkInstanceId = ResolveMethodWithArg(NetworkWriterType, "Write", NetworkInstanceIdType); + NetworkWriterWriteNetworkSceneId = ResolveMethodWithArg(NetworkWriterType, "Write", NetworkSceneIdType); + + NetworkReaderReadNetworkInstanceId = ResolveMethod(NetworkReaderType, "ReadNetworkId"); + NetworkReaderReadNetworkSceneId = ResolveMethod(NetworkReaderType, "ReadSceneId"); + NetworkInstanceIsEmpty = ResolveMethod(NetworkInstanceIdType, "IsEmpty"); + + NetworkReadUInt16 = ResolveMethod(NetworkReaderType, "ReadUInt16"); + NetworkWriteUInt16 = ResolveMethodWithArg(NetworkWriterType, "Write", uint16Type); + + CmdDelegateReference = m_UNetAssemblyDefinition.MainModule.GetType("UnityEngine.Networking.NetworkBehaviour/CmdDelegate"); + CmdDelegateConstructor = ResolveMethod(CmdDelegateReference, ".ctor"); + m_ScriptDef.MainModule.ImportReference(gameObjectType); + m_ScriptDef.MainModule.ImportReference(transformType); + + TypeReference unetViewTmp = m_UNetAssemblyDefinition.MainModule.GetType("UnityEngine.Networking.NetworkIdentity"); + NetworkIdentityType = m_ScriptDef.MainModule.ImportReference(unetViewTmp); + + NetworkInstanceIdType = m_ScriptDef.MainModule.ImportReference(NetworkInstanceIdType); + + SyncListFloatReadType = ResolveMethod(SyncListFloatType, "ReadReference"); + SyncListIntReadType = ResolveMethod(SyncListIntType, "ReadReference"); + SyncListUIntReadType = ResolveMethod(SyncListUIntType, "ReadReference"); + SyncListBoolReadType = ResolveMethod(SyncListBoolType, "ReadReference"); + SyncListStringReadType = ResolveMethod(SyncListStringType, "ReadReference"); + + SyncListFloatWriteType = ResolveMethod(SyncListFloatType, "WriteInstance"); + SyncListIntWriteType = ResolveMethod(SyncListIntType, "WriteInstance"); + SyncListUIntWriteType = ResolveMethod(SyncListUIntType, "WriteInstance"); + SyncListBoolWriteType = ResolveMethod(SyncListBoolType, "WriteInstance"); + SyncListStringWriteType = ResolveMethod(SyncListStringType, "WriteInstance"); + + + NetworkBehaviourType = m_UNetAssemblyDefinition.MainModule.GetType("UnityEngine.Networking.NetworkBehaviour"); + NetworkBehaviourType2 = m_ScriptDef.MainModule.ImportReference(NetworkBehaviourType); + NetworkConnectionType = m_UNetAssemblyDefinition.MainModule.GetType("UnityEngine.Networking.NetworkConnection"); + + MonoBehaviourType = m_UnityAssemblyDefinition.MainModule.GetType("UnityEngine.MonoBehaviour"); + ScriptableObjectType = m_UnityAssemblyDefinition.MainModule.GetType("UnityEngine.ScriptableObject"); + + NetworkConnectionType = m_UNetAssemblyDefinition.MainModule.GetType("UnityEngine.Networking.NetworkConnection"); + NetworkConnectionType = m_ScriptDef.MainModule.ImportReference(NetworkConnectionType); + + ULocalConnectionToServerType = m_UNetAssemblyDefinition.MainModule.GetType("UnityEngine.Networking.ULocalConnectionToServer"); + ULocalConnectionToServerType = m_ScriptDef.MainModule.ImportReference(ULocalConnectionToServerType); + + ULocalConnectionToClientType = m_UNetAssemblyDefinition.MainModule.GetType("UnityEngine.Networking.ULocalConnectionToClient"); + ULocalConnectionToClientType = m_ScriptDef.MainModule.ImportReference(ULocalConnectionToClientType); + + MessageBaseType = m_UNetAssemblyDefinition.MainModule.GetType("UnityEngine.Networking.MessageBase"); + SyncListStructType = m_UNetAssemblyDefinition.MainModule.GetType("UnityEngine.Networking.SyncListStruct`1"); + + NetworkBehaviourDirtyBitsReference = ResolveProperty(NetworkBehaviourType, "syncVarDirtyBits"); + + ComponentType = m_UnityAssemblyDefinition.MainModule.GetType("UnityEngine.Component"); + ClientSceneType = m_UNetAssemblyDefinition.MainModule.GetType("UnityEngine.Networking.ClientScene"); + FindLocalObjectReference = ResolveMethod(ClientSceneType, "FindLocalObject"); + RegisterBehaviourReference = ResolveMethod(NetworkCRCType, "RegisterBehaviour"); + ReadyConnectionReference = ResolveMethod(ClientSceneType, "get_readyConnection"); + + // get specialized GetComponent() + getComponentReference = ResolveMethodGeneric(ComponentType, "GetComponent", NetworkIdentityType); + + getUNetIdReference = ResolveMethod(unetViewTmp, "get_netId"); + + gameObjectInequality = ResolveMethod(unityObjectType, "op_Inequality"); + + UBehaviourIsServer = ResolveMethod(NetworkBehaviourType, "get_isServer"); + getPlayerIdReference = ResolveMethod(NetworkBehaviourType, "get_playerControllerId"); + setSyncVarReference = ResolveMethod(NetworkBehaviourType, "SetSyncVar"); + setSyncVarHookGuard = ResolveMethod(NetworkBehaviourType, "set_syncVarHookGuard"); + getSyncVarHookGuard = ResolveMethod(NetworkBehaviourType, "get_syncVarHookGuard"); + + setSyncVarGameObjectReference = ResolveMethod(NetworkBehaviourType, "SetSyncVarGameObject"); + registerCommandDelegateReference = ResolveMethod(NetworkBehaviourType, "RegisterCommandDelegate"); + registerRpcDelegateReference = ResolveMethod(NetworkBehaviourType, "RegisterRpcDelegate"); + registerEventDelegateReference = ResolveMethod(NetworkBehaviourType, "RegisterEventDelegate"); + registerSyncListDelegateReference = ResolveMethod(NetworkBehaviourType, "RegisterSyncListDelegate"); + getTypeReference = ResolveMethod(objectType, "GetType"); + getTypeFromHandleReference = ResolveMethod(typeType, "GetTypeFromHandle"); + logErrorReference = ResolveMethod(m_UnityAssemblyDefinition.MainModule.GetType("UnityEngine.Debug"), "LogError"); + logWarningReference = ResolveMethod(m_UnityAssemblyDefinition.MainModule.GetType("UnityEngine.Debug"), "LogWarning"); + sendCommandInternal = ResolveMethod(NetworkBehaviourType, "SendCommandInternal"); + sendRpcInternal = ResolveMethod(NetworkBehaviourType, "SendRPCInternal"); + sendTargetRpcInternal = ResolveMethod(NetworkBehaviourType, "SendTargetRPCInternal"); + sendEventInternal = ResolveMethod(NetworkBehaviourType, "SendEventInternal"); + + SyncListType = m_ScriptDef.MainModule.ImportReference(SyncListType); + SyncListInitBehaviourReference = ResolveMethod(SyncListType, "InitializeBehaviour"); + SyncListInitHandleMsg = ResolveMethod(SyncListType, "HandleMsg"); + SyncListClear = ResolveMethod(SyncListType, "Clear"); + } + + void SetupReadFunctions() + { + lists.readFuncs = new Dictionary + { + { singleType.FullName, ResolveMethod(NetworkReaderType, "ReadSingle") }, + { doubleType.FullName, ResolveMethod(NetworkReaderType, "ReadDouble") }, + { boolType.FullName, ResolveMethod(NetworkReaderType, "ReadBoolean") }, + { stringType.FullName, ResolveMethod(NetworkReaderType, "ReadString") }, + { int64Type.FullName, NetworkReaderReadPacked64 }, + { uint64Type.FullName, NetworkReaderReadPacked64 }, + { int32Type.FullName, NetworkReaderReadPacked32 }, + { uint32Type.FullName, NetworkReaderReadPacked32 }, + { int16Type.FullName, NetworkReaderReadPacked32 }, + { uint16Type.FullName, NetworkReaderReadPacked32 }, + { byteType.FullName, NetworkReaderReadPacked32 }, + { sbyteType.FullName, NetworkReaderReadPacked32 }, + { charType.FullName, NetworkReaderReadPacked32 }, + { decimalType.FullName, ResolveMethod(NetworkReaderType, "ReadDecimal") }, + { vector2Type.FullName, ResolveMethod(NetworkReaderType, "ReadVector2") }, + { vector3Type.FullName, ResolveMethod(NetworkReaderType, "ReadVector3") }, + { vector4Type.FullName, ResolveMethod(NetworkReaderType, "ReadVector4") }, + { colorType.FullName, ResolveMethod(NetworkReaderType, "ReadColor") }, + { color32Type.FullName, ResolveMethod(NetworkReaderType, "ReadColor32") }, + { quaternionType.FullName, ResolveMethod(NetworkReaderType, "ReadQuaternion") }, + { rectType.FullName, ResolveMethod(NetworkReaderType, "ReadRect") }, + { planeType.FullName, ResolveMethod(NetworkReaderType, "ReadPlane") }, + { rayType.FullName, ResolveMethod(NetworkReaderType, "ReadRay") }, + { matrixType.FullName, ResolveMethod(NetworkReaderType, "ReadMatrix4x4") }, + { hashType.FullName, ResolveMethod(NetworkReaderType, "ReadNetworkHash128") }, + { gameObjectType.FullName, ResolveMethod(NetworkReaderType, "ReadGameObject") }, + { NetworkIdentityType.FullName, ResolveMethod(NetworkReaderType, "ReadNetworkIdentity") }, + { NetworkInstanceIdType.FullName, NetworkReaderReadNetworkInstanceId }, + { NetworkSceneIdType.FullName, NetworkReaderReadNetworkSceneId }, + { transformType.FullName, ResolveMethod(NetworkReaderType, "ReadTransform") }, + { "System.Byte[]", ResolveMethod(NetworkReaderType, "ReadBytesAndSize") }, + }; + + lists.readByReferenceFuncs = new Dictionary + { + {SyncListFloatType.FullName, SyncListFloatReadType}, + {SyncListIntType.FullName, SyncListIntReadType}, + {SyncListUIntType.FullName, SyncListUIntReadType}, + {SyncListBoolType.FullName, SyncListBoolReadType}, + {SyncListStringType.FullName, SyncListStringReadType} + }; + } + + void SetupWriteFunctions() + { + lists.writeFuncs = new Dictionary + { + { singleType.FullName, ResolveMethodWithArg(NetworkWriterType, "Write", singleType) }, + { doubleType.FullName, ResolveMethodWithArg(NetworkWriterType, "Write", doubleType) }, + { boolType.FullName, ResolveMethodWithArg(NetworkWriterType, "Write", boolType) }, + { stringType.FullName, ResolveMethodWithArg(NetworkWriterType, "Write", stringType) }, + { int64Type.FullName, NetworkWriterWritePacked64 }, + { uint64Type.FullName, NetworkWriterWritePacked64 }, + { int32Type.FullName, NetworkWriterWritePacked32 }, + { uint32Type.FullName, NetworkWriterWritePacked32 }, + { int16Type.FullName, NetworkWriterWritePacked32 }, + { uint16Type.FullName, NetworkWriterWritePacked32 }, + { byteType.FullName, NetworkWriterWritePacked32 }, + { sbyteType.FullName, NetworkWriterWritePacked32 }, + { charType.FullName, NetworkWriterWritePacked32 }, + { decimalType.FullName, ResolveMethodWithArg(NetworkWriterType, "Write", decimalType) }, + { vector2Type.FullName, ResolveMethodWithArg(NetworkWriterType, "Write", vector2Type) }, + { vector3Type.FullName, ResolveMethodWithArg(NetworkWriterType, "Write", vector3Type) }, + { vector4Type.FullName, ResolveMethodWithArg(NetworkWriterType, "Write", vector4Type) }, + { colorType.FullName, ResolveMethodWithArg(NetworkWriterType, "Write", colorType) }, + { color32Type.FullName, ResolveMethodWithArg(NetworkWriterType, "Write", color32Type) }, + { quaternionType.FullName, ResolveMethodWithArg(NetworkWriterType, "Write", quaternionType) }, + { rectType.FullName, ResolveMethodWithArg(NetworkWriterType, "Write", rectType) }, + { planeType.FullName, ResolveMethodWithArg(NetworkWriterType, "Write", planeType) }, + { rayType.FullName, ResolveMethodWithArg(NetworkWriterType, "Write", rayType) }, + { matrixType.FullName, ResolveMethodWithArg(NetworkWriterType, "Write", matrixType) }, + { hashType.FullName, ResolveMethodWithArg(NetworkWriterType, "Write", hashType) }, + { gameObjectType.FullName, ResolveMethodWithArg(NetworkWriterType, "Write", gameObjectType) }, + { NetworkIdentityType.FullName, ResolveMethodWithArg(NetworkWriterType, "Write", NetworkIdentityType) }, + { NetworkInstanceIdType.FullName, NetworkWriterWriteNetworkInstanceId }, + { NetworkSceneIdType.FullName, NetworkWriterWriteNetworkSceneId }, + { transformType.FullName, ResolveMethodWithArg(NetworkWriterType, "Write", transformType) }, + { "System.Byte[]", ResolveMethod(NetworkWriterType, "WriteBytesFull") }, + { SyncListFloatType.FullName, SyncListFloatWriteType }, + { SyncListIntType.FullName, SyncListIntWriteType }, + { SyncListUIntType.FullName, SyncListUIntWriteType }, + { SyncListBoolType.FullName, SyncListBoolWriteType }, + { SyncListStringType.FullName, SyncListStringWriteType } + }; + } + + bool IsNetworkBehaviour(TypeDefinition td) + { + if (!td.IsClass) + return false; + + // are ANY parent clasess unetbehaviours + TypeReference parent = td.BaseType; + while (parent != null) + { + if (parent.FullName == NetworkBehaviourType.FullName) + { + return true; + } + try + { + parent = parent.Resolve().BaseType; + } + catch (AssemblyResolutionException) + { + // this can happen for pluins. + //Console.WriteLine("AssemblyResolutionException: "+ ex.ToString()); + break; + } + } + return false; + } + + public bool IsDerivedFrom(TypeDefinition td, TypeReference baseClass) + { + if (!td.IsClass) + return false; + + // are ANY parent clasess unetbehaviours + TypeReference parent = td.BaseType; + while (parent != null) + { + var parentName = parent.FullName; + + // strip generic parameters + int index = parentName.IndexOf('<'); + if (index != -1) + { + parentName = parentName.Substring(0, index); + } + + if (parentName == baseClass.FullName) + { + return true; + } + try + { + parent = parent.Resolve().BaseType; + } + catch (AssemblyResolutionException) + { + // this can happen for pluins. + //Console.WriteLine("AssemblyResolutionException: "+ ex.ToString()); + break; + } + } + return false; + } + + public bool IsValidTypeToGenerate(TypeDefinition variable) + { + // a valid type is a simple class or struct. so we generate only code for types we dont know, and if they are not inside + // this assembly it must mean that we are trying to serialize a variable outside our scope. and this will fail. + + string assembly = m_ScriptDef.MainModule.Name; + if (variable.Module.Name == assembly) + return true; + + Log.Error("parameter [" + variable.Name + + "] is of the type [" + + variable.FullName + + "] is not a valid type, please make sure to use a valid type."); + fail = true; + return false; + } + + void CheckMonoBehaviour(TypeDefinition td) + { + if (IsDerivedFrom(td, MonoBehaviourType)) + { + ProcessMonoBehaviourType(td); + } + } + + bool CheckNetworkBehaviour(TypeDefinition td) + { + if (!td.IsClass) + return false; + + if (!IsNetworkBehaviour(td)) + { + CheckMonoBehaviour(td); + return false; + } + + // process this and base classes from parent to child order + + List behClasses = new List(); + + TypeDefinition parent = td; + while (parent != null) + { + if (parent.FullName == NetworkBehaviourType.FullName) + { + break; + } + try + { + behClasses.Insert(0, parent); + parent = parent.BaseType.Resolve(); + } + catch (AssemblyResolutionException) + { + // this can happen for pluins. + //Console.WriteLine("AssemblyResolutionException: "+ ex.ToString()); + break; + } + } + + bool didWork = false; + foreach (var beh in behClasses) + { + didWork |= ProcessNetworkBehaviourType(beh); + } + return didWork; + } + + bool CheckMessageBase(TypeDefinition td) + { + if (!td.IsClass) + return false; + + bool didWork = false; + + // are ANY parent clasess MessageBase + TypeReference parent = td.BaseType; + while (parent != null) + { + if (parent.FullName == MessageBaseType.FullName) + { + didWork |= ProcessMessageType(td); + break; + } + try + { + parent = parent.Resolve().BaseType; + } + catch (AssemblyResolutionException) + { + // this can happen for pluins. + //Console.WriteLine("AssemblyResolutionException: "+ ex.ToString()); + break; + } + } + + // check for embedded types + foreach (var embedded in td.NestedTypes) + { + didWork |= CheckMessageBase(embedded); + } + + return didWork; + } + + bool CheckSyncListStruct(TypeDefinition td) + { + if (!td.IsClass) + return false; + + bool didWork = false; + + // are ANY parent clasess SyncListStruct + TypeReference parent = td.BaseType; + while (parent != null) + { + if (parent.FullName.Contains("SyncListStruct")) + { + didWork |= ProcessSyncListStructType(td); + break; + } + try + { + parent = parent.Resolve().BaseType; + } + catch (AssemblyResolutionException) + { + // this can happen for pluins. + //Console.WriteLine("AssemblyResolutionException: "+ ex.ToString()); + break; + } + } + + // check for embedded types + foreach (var embedded in td.NestedTypes) + { + didWork |= CheckSyncListStruct(embedded); + } + + return didWork; + } + + bool Weave(string assName, IEnumerable dependencies, IAssemblyResolver assemblyResolver, string unityEngineDLLPath, string unityUNetDLLPath, string outputDir) + { + var readParams = Helpers.ReaderParameters(assName, dependencies, assemblyResolver, unityEngineDLLPath, unityUNetDLLPath); + + string pdbToDelete = null; + using (m_UnityAssemblyDefinition = AssemblyDefinition.ReadAssembly(unityEngineDLLPath)) + using (m_ScriptDef = AssemblyDefinition.ReadAssembly(assName, readParams)) + using (m_UNetAssemblyDefinition = AssemblyDefinition.ReadAssembly(unityUNetDLLPath)) + { + SetupUnityTypes(); + SetupTargetTypes(); + SetupReadFunctions(); + SetupWriteFunctions(); + + ModuleDefinition moduleDefinition = m_ScriptDef.MainModule; + Console.WriteLine("Script Module: {0}", moduleDefinition.Name); + + // Process each NetworkBehaviour + bool didWork = false; + + // We need to do 2 passes, because SyncListStructs might be referenced from other modules, so we must make sure we generate them first. + for (int pass = 0; pass < 2; pass++) + { + var watch = System.Diagnostics.Stopwatch.StartNew(); + foreach (TypeDefinition td in moduleDefinition.Types) + { + if (td.IsClass && CanBeResolved(td.BaseType)) + { + try + { + if (pass == 0) + { + didWork |= CheckSyncListStruct(td); + } + else + { + didWork |= CheckNetworkBehaviour(td); + didWork |= CheckMessageBase(td); + } + } + catch (Exception ex) + { + if (m_ScriptDef.MainModule.SymbolReader != null) + m_ScriptDef.MainModule.SymbolReader.Dispose(); + fail = true; + throw ex; + } + } + + if (fail) + { + if (m_ScriptDef.MainModule.SymbolReader != null) + m_ScriptDef.MainModule.SymbolReader.Dispose(); + return false; + } + } + + watch.Stop(); + Console.WriteLine("Pass: " + pass + " took " + watch.ElapsedMilliseconds + " milliseconds"); + } + + if (didWork) + { + // build replacementMethods hash to speed up code site scan + foreach (var m in lists.replacedMethods) + { + lists.replacementMethodNames.Add(m.FullName); + } + + // this must be done for ALL code, not just NetworkBehaviours + try + { + ProcessPropertySites(); + } + catch (Exception e) + { + Log.Error("ProcessPropertySites exception: " + e); + if (m_ScriptDef.MainModule.SymbolReader != null) + m_ScriptDef.MainModule.SymbolReader.Dispose(); + return false; + } + + + if (fail) + { + //Log.Error("Failed phase II."); + if (m_ScriptDef.MainModule.SymbolReader != null) + m_ScriptDef.MainModule.SymbolReader.Dispose(); + return false; + } + + //Console.WriteLine ("Output:" + dest); + //Console.WriteLine ("Output:" + options.OutSymbolsFormat); + + var writeParams = Helpers.GetWriterParameters(readParams); + + // PdbWriterProvider uses ISymUnmanagedWriter2 COM interface but Mono can't invoke a method on it and crashes (actually it first throws the following exception and then crashes). + // One solution would be to convert UNetWeaver to exe file and run it on .NET on Windows (I have tested that and it works). + // However it's much more simple to just write mdb file. + // System.NullReferenceException: Object reference not set to an instance of an object + // at(wrapper cominterop - invoke) Mono.Cecil.Pdb.ISymUnmanagedWriter2:DefineDocument(string, System.Guid &, System.Guid &, System.Guid &, Mono.Cecil.Pdb.ISymUnmanagedDocumentWriter &) + // at Mono.Cecil.Pdb.SymWriter.DefineDocument(System.String url, Guid language, Guid languageVendor, Guid documentType)[0x00000] in < filename unknown >:0 + if (writeParams.SymbolWriterProvider is PdbWriterProvider) + { + writeParams.SymbolWriterProvider = new MdbWriterProvider(); + // old pdb file is out of date so delete it. symbols will be stored in mdb + pdbToDelete = Path.ChangeExtension(assName, ".pdb"); + } + + m_ScriptDef.Write(writeParams); + } + + if (m_ScriptDef.MainModule.SymbolReader != null) + m_ScriptDef.MainModule.SymbolReader.Dispose(); + } + + if (pdbToDelete != null) + File.Delete(pdbToDelete); + + return true; + } + + public bool WeaveAssemblies(IEnumerable assemblies, IEnumerable dependencies, IAssemblyResolver assemblyResolver, string outputDir, string unityEngineDLLPath, string unityUNetDLLPath) + { + fail = false; + lists = new WeaverLists(); + + try + { + foreach (string ass in assemblies) + { + if (!Weave(ass, dependencies, assemblyResolver, unityEngineDLLPath, unityUNetDLLPath, outputDir)) + { + return false; + } + } + } + catch (Exception e) + { + Log.Error("Exception :" + e); + return false; + } + //corLib = null; + return true; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/Tools/Weaver/com.unity.multiplayer-weaver.Editor.asmdef b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/Tools/Weaver/com.unity.multiplayer-weaver.Editor.asmdef new file mode 100644 index 00000000..1088cc3c --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/Tools/Weaver/com.unity.multiplayer-weaver.Editor.asmdef @@ -0,0 +1,16 @@ +{ + "name": "com.unity.multiplayer-weaver.Editor", + "references": [], + "includePlatforms": [ + "Editor" + ], + "excludePlatforms": [], + "allowUnsafeCode" : true, + "overrideReferences": true, + "precompiledReferences": [ + "Mono.Cecil.dll", + "Mono.Cecil.Mdb.dll", + "Mono.Cecil.Pdb.dll", + "Mono.Cecil.Rocks.dll" + ] +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/WeaverRunner.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/WeaverRunner.cs new file mode 100644 index 00000000..6d1383a1 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/WeaverRunner.cs @@ -0,0 +1,132 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using UnityEditor.Compilation; +using UnityEngine; +using Assembly = System.Reflection.Assembly; + +namespace UnityEditor.Networking +{ + internal class WeaverRunner + { + [InitializeOnLoadMethod] + static void OnInitializeOnLoad() + { + CompilationPipeline.assemblyCompilationFinished += OnCompilationFinished; + } + + static void OnCompilationFinished(string targetAssembly, CompilerMessage[] messages) + { + const string k_HlapiRuntimeAssemblyName = "com.unity.multiplayer-hlapi.Runtime"; + + // Do nothing if there were compile errors on the target + if (messages.Length > 0) + { + foreach (var msg in messages) + { + if (msg.type == CompilerMessageType.Error) + { + return; + } + } + } + + // Should not run on the editor only assemblies + if (targetAssembly.Contains("-Editor") || targetAssembly.Contains(".Editor")) + { + return; + } + + // Should not run on own assembly + if (targetAssembly.Contains(k_HlapiRuntimeAssemblyName)) + { + return; + } + + var scriptAssembliesPath = Application.dataPath + "/../" + Path.GetDirectoryName(targetAssembly); + + string unityEngine = ""; + string unetAssemblyPath = ""; + var outputDirectory = scriptAssembliesPath; + var assemblyPath = targetAssembly; + + var assemblies = AppDomain.CurrentDomain.GetAssemblies(); + bool usesUnet = false; + bool foundThisAssembly = false; + HashSet depenencyPaths = new HashSet(); + foreach (var assembly in assemblies) + { + // Find the assembly currently being compiled from domain assembly list and check if it's using unet + if (assembly.GetName().Name == Path.GetFileNameWithoutExtension(targetAssembly)) + { + foundThisAssembly = true; + foreach (var dependency in assembly.GetReferencedAssemblies()) + { + // Since this assembly is already loaded in the domain this is a no-op and retuns the + // already loaded assembly + var location = Assembly.Load(dependency).Location; + depenencyPaths.Add(Path.GetDirectoryName(location)); + if (dependency.Name.Contains(k_HlapiRuntimeAssemblyName)) + { + usesUnet = true; + } + } + } + try + { + if (assembly.Location.Contains("UnityEngine.CoreModule")) + { + unityEngine = assembly.Location; + } + if (assembly.Location.Contains(k_HlapiRuntimeAssemblyName)) + { + unetAssemblyPath = assembly.Location; + } + } + catch (NotSupportedException) + { + // in memory assembly, can't get location + } + } + + if (!foundThisAssembly) + { + // Target assembly not found in current domain, trying to load it to check references + // will lead to trouble in the build pipeline, so lets assume it should go to weaver. + // Add all assemblies in current domain to dependency list since there could be a + // dependency lurking there (there might be generated assemblies so ignore file not found exceptions). + // (can happen in runtime test framework on editor platform and when doing full library reimport) + foreach (var assembly in assemblies) + { + try + { + if (!(assembly.ManifestModule is System.Reflection.Emit.ModuleBuilder)) + depenencyPaths.Add(Path.GetDirectoryName(Assembly.Load(assembly.GetName().Name).Location)); + } + catch (FileNotFoundException) { } + } + usesUnet = true; + } + + if (!usesUnet) + { + return; + } + + if (string.IsNullOrEmpty(unityEngine)) + { + Debug.LogError("Failed to find UnityEngine assembly"); + return; + } + + if (string.IsNullOrEmpty(unetAssemblyPath)) + { + Debug.LogError("Failed to find hlapi runtime assembly"); + return; + } + + Unity.UNetWeaver.Program.Process(unityEngine, unetAssemblyPath, outputDirectory, new[] { assemblyPath }, depenencyPaths.ToArray(), (value) => { Debug.LogWarning(value); }, (value) => { Debug.LogError(value); }); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/com.unity.multiplayer-hlapi.Editor.asmdef b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/com.unity.multiplayer-hlapi.Editor.asmdef new file mode 100644 index 00000000..6114bda9 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Editor/com.unity.multiplayer-hlapi.Editor.asmdef @@ -0,0 +1,11 @@ +{ + "name": "com.unity.multiplayer-hlapi.Editor", + "references": [ + "com.unity.multiplayer-hlapi.Runtime", + "com.unity.multiplayer-weaver.Editor" + ], + "includePlatforms": [ + "Editor" + ], + "excludePlatforms": [] +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/LICENSE.md b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/LICENSE.md new file mode 100644 index 00000000..b2c40499 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2018, Unity Technologies + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/README.md b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/README.md new file mode 100644 index 00000000..16713854 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/README.md @@ -0,0 +1,50 @@ +# README # + +The Unity Multiplayer High Level API is the open source component of the Unity Multiplayer system, this was formerly a Unity extension DLL with some parts in the engine itself, now it all exist in a package. In this package we have the whole networking system except the NetworkTransport related APIs and classes. This is all the high level classes and components which make up the user friendly system of creating multiplayer games. This document details how you can enable or embed the package and use it in your games and applications. + +### What license is the Unity Multiplayer HLAPI package shipped under? ### +Unity Multiplayer HLAPI package is released under an MIT/X11 license; see the LICENSE.md file. + +This means that you pretty much can customize and embed it in any software under any license without any other constraints than preserving the copyright and license information while adding your own copyright and license information. + +You can keep the source to yourself or share your customized version under the same MIT license or a compatible license. + +If you want to contribute patches back, please keep it under the unmodified MIT license so it can be integrated in future versions and shared under the same license. + +### How do I get started? ### +* Go to the Package Manager UI in the Unity editor (found under the Window menu). +* Make sure "Show preview packages" is enabled in the Advanced menu in the package manager UI. +* The HLAPI package should appear in the list of packages, select it and click the Install button + +or + +* Add the package to your project manifest.json file, located in the Packages folder. Under dependencies add the line _"com.unity.multiplayer-hlapi": "0.2.6-preview"_ to the list of packages. A specific version needs to be chosen. + +or + +* Clone this repository into the Packages folder. + +### Running tests ### + +When the package files are directly included in the Packages folder of the projects (or somewhere in the Assets folder), the tests will appear and can be executed. + +When including the package via the manifest.json file the `testable` field needs to be added: + +``` +{ + "dependencies": { + "com.unity.multiplayer-hlapi": "0.2.6-preview", + ... more stuff... + }, + "testables": [ + "com.unity.multiplayer-hlapi" + ] +} +``` + +where there referenced package number should be the latest or whatever version is being tested. + +When the package is included for the first time, it will be compiled, and some of the test will fail to run since the weaver has not had a chance to run yet. Triggering a recompile should fix that, for example by reimporting some script or triggering a build. + +### Will you be taking pull requests? ### +We'll consider all incoming pull requests that we get. It's likely we'll take bug fixes this way but anything else will be handled on a case by case basis. Changes will not be applied directly to this repository but to an internal package repository which will be periodically synchronized with this one. \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/ChannelBuffer.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/ChannelBuffer.cs new file mode 100644 index 00000000..5f5ebc34 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/ChannelBuffer.cs @@ -0,0 +1,403 @@ +#if ENABLE_UNET +using System; +using System.Collections.Generic; + +#pragma warning disable 618 +namespace UnityEngine.Networking +{ + class ChannelBuffer : IDisposable + { + NetworkConnection m_Connection; + + ChannelPacket m_CurrentPacket; + + float m_LastFlushTime; + + byte m_ChannelId; + int m_MaxPacketSize; + bool m_IsReliable; + bool m_AllowFragmentation; + bool m_IsBroken; + int m_MaxPendingPacketCount; + + const int k_MaxFreePacketCount = 512; // this is for all connections. maybe make this configurable + public const int MaxPendingPacketCount = 16; // this is per connection. each is around 1400 bytes (MTU) + public const int MaxBufferedPackets = 512; + + Queue m_PendingPackets; + static List s_FreePackets; + static internal int pendingPacketCount; // this is across all connections. only used for profiler metrics. + + // config + public float maxDelay = 0.01f; + + // stats + float m_LastBufferedMessageCountTimer = Time.realtimeSinceStartup; + + public int numMsgsOut { get; private set; } + public int numBufferedMsgsOut { get; private set; } + public int numBytesOut { get; private set; } + + public int numMsgsIn { get; private set; } + public int numBytesIn { get; private set; } + + public int numBufferedPerSecond { get; private set; } + public int lastBufferedPerSecond { get; private set; } + + static NetworkWriter s_SendWriter = new NetworkWriter(); + static NetworkWriter s_FragmentWriter = new NetworkWriter(); + + // We need to reserve some space for header information, this will be taken off the total channel buffer size + const int k_PacketHeaderReserveSize = 100; + + public ChannelBuffer(NetworkConnection conn, int bufferSize, byte cid, bool isReliable, bool isSequenced) + { + m_Connection = conn; + m_MaxPacketSize = bufferSize - k_PacketHeaderReserveSize; + m_CurrentPacket = new ChannelPacket(m_MaxPacketSize, isReliable); + + m_ChannelId = cid; + m_MaxPendingPacketCount = MaxPendingPacketCount; + m_IsReliable = isReliable; + m_AllowFragmentation = (isReliable && isSequenced); + if (isReliable) + { + m_PendingPackets = new Queue(); + if (s_FreePackets == null) + { + s_FreePackets = new List(); + } + } + } + + // Track whether Dispose has been called. + bool m_Disposed; + + public void Dispose() + { + Dispose(true); + // Take yourself off the Finalization queue + // to prevent finalization code for this object + // from executing a second time. + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing) + { + // Check to see if Dispose has already been called. + if (!m_Disposed) + { + if (disposing) + { + if (m_PendingPackets != null) + { + while (m_PendingPackets.Count > 0) + { + pendingPacketCount -= 1; + + ChannelPacket packet = m_PendingPackets.Dequeue(); + if (s_FreePackets.Count < k_MaxFreePacketCount) + { + s_FreePackets.Add(packet); + } + } + m_PendingPackets.Clear(); + } + } + } + m_Disposed = true; + } + + public bool SetOption(ChannelOption option, int value) + { + switch (option) + { + case ChannelOption.MaxPendingBuffers: + { + if (!m_IsReliable) + { + // not an error + //if (LogFilter.logError) { Debug.LogError("Cannot set MaxPendingBuffers on unreliable channel " + m_ChannelId); } + return false; + } + if (value < 0 || value >= MaxBufferedPackets) + { + if (LogFilter.logError) { Debug.LogError("Invalid MaxPendingBuffers for channel " + m_ChannelId + ". Must be greater than zero and less than " + k_MaxFreePacketCount); } + return false; + } + m_MaxPendingPacketCount = value; + return true; + } + + case ChannelOption.AllowFragmentation: + { + m_AllowFragmentation = (value != 0); + return true; + } + + case ChannelOption.MaxPacketSize: + { + if (!m_CurrentPacket.IsEmpty() || m_PendingPackets.Count > 0) + { + if (LogFilter.logError) { Debug.LogError("Cannot set MaxPacketSize after sending data."); } + return false; + } + + if (value <= 0) + { + if (LogFilter.logError) { Debug.LogError("Cannot set MaxPacketSize less than one."); } + return false; + } + + if (value > m_MaxPacketSize) + { + if (LogFilter.logError) { Debug.LogError("Cannot set MaxPacketSize to greater than the existing maximum (" + m_MaxPacketSize + ")."); } + return false; + } + // rebuild the packet with the new size. the packets doesn't store a size variable, just has the size of the internal buffer + m_CurrentPacket = new ChannelPacket(value, m_IsReliable); + m_MaxPacketSize = value; + return true; + } + } + return false; + } + + public void CheckInternalBuffer() + { + if (Time.realtimeSinceStartup - m_LastFlushTime > maxDelay && !m_CurrentPacket.IsEmpty()) + { + SendInternalBuffer(); + m_LastFlushTime = Time.realtimeSinceStartup; + } + + if (Time.realtimeSinceStartup - m_LastBufferedMessageCountTimer > 1.0f) + { + lastBufferedPerSecond = numBufferedPerSecond; + numBufferedPerSecond = 0; + m_LastBufferedMessageCountTimer = Time.realtimeSinceStartup; + } + } + + public bool SendWriter(NetworkWriter writer) + { + return SendBytes(writer.AsArraySegment().Array, writer.AsArraySegment().Count); + } + + public bool Send(short msgType, MessageBase msg) + { + // build the stream + s_SendWriter.StartMessage(msgType); + msg.Serialize(s_SendWriter); + s_SendWriter.FinishMessage(); + + numMsgsOut += 1; + return SendWriter(s_SendWriter); + } + + internal NetBuffer fragmentBuffer = new NetBuffer(); + bool readingFragment = false; + + internal bool HandleFragment(NetworkReader reader) + { + int state = reader.ReadByte(); + if (state == 0) + { + if (readingFragment == false) + { + fragmentBuffer.SeekZero(); + readingFragment = true; + } + + byte[] data = reader.ReadBytesAndSize(); + fragmentBuffer.WriteBytes(data, (ushort)data.Length); + return false; + } + else + { + readingFragment = false; + return true; + } + } + + internal bool SendFragmentBytes(byte[] bytes, int bytesToSend) + { + const int fragmentHeaderSize = 32; + int pos = 0; + while (bytesToSend > 0) + { + int diff = Math.Min(bytesToSend, m_MaxPacketSize - fragmentHeaderSize); + byte[] buffer = new byte[diff]; + Array.Copy(bytes, pos, buffer, 0, diff); + + s_FragmentWriter.StartMessage(MsgType.Fragment); + s_FragmentWriter.Write((byte)0); + s_FragmentWriter.WriteBytesFull(buffer); + s_FragmentWriter.FinishMessage(); + SendWriter(s_FragmentWriter); + + pos += diff; + bytesToSend -= diff; + } + + // send finish + s_FragmentWriter.StartMessage(MsgType.Fragment); + s_FragmentWriter.Write((byte)1); + s_FragmentWriter.FinishMessage(); + SendWriter(s_FragmentWriter); + + return true; + } + + internal bool SendBytes(byte[] bytes, int bytesToSend) + { +#if UNITY_EDITOR + Profiler.IncrementStatOutgoing(MsgType.HLAPIMsg); +#endif + if (bytesToSend >= UInt16.MaxValue) + { + if (LogFilter.logError) { Debug.LogError("ChannelBuffer:SendBytes cannot send packet larger than " + UInt16.MaxValue + " bytes"); } + return false; + } + + if (bytesToSend <= 0) + { + // zero length packets getting into the packet queues are bad. + if (LogFilter.logError) { Debug.LogError("ChannelBuffer:SendBytes cannot send zero bytes"); } + return false; + } + + if (bytesToSend > m_MaxPacketSize) + { + if (m_AllowFragmentation) + { + return SendFragmentBytes(bytes, bytesToSend); + } + else + { + // cannot do HLAPI fragmentation on this channel + if (LogFilter.logError) { Debug.LogError("Failed to send big message of " + bytesToSend + " bytes. The maximum is " + m_MaxPacketSize + " bytes on channel:" + m_ChannelId); } + return false; + } + } + + if (!m_CurrentPacket.HasSpace(bytesToSend)) + { + if (m_IsReliable) + { + if (m_PendingPackets.Count == 0) + { + // nothing in the pending queue yet, just flush and write + if (!m_CurrentPacket.SendToTransport(m_Connection, m_ChannelId)) + { + QueuePacket(); + } + m_CurrentPacket.Write(bytes, bytesToSend); + return true; + } + + if (m_PendingPackets.Count >= m_MaxPendingPacketCount) + { + if (!m_IsBroken) + { + // only log this once, or it will spam the log constantly + if (LogFilter.logError) { Debug.LogError("ChannelBuffer buffer limit of " + m_PendingPackets.Count + " packets reached."); } + } + m_IsBroken = true; + return false; + } + + // calling SendToTransport here would write out-of-order data to the stream. just queue + QueuePacket(); + m_CurrentPacket.Write(bytes, bytesToSend); + return true; + } + + if (!m_CurrentPacket.SendToTransport(m_Connection, m_ChannelId)) + { + if (LogFilter.logError) { Debug.Log("ChannelBuffer SendBytes no space on unreliable channel " + m_ChannelId); } + return false; + } + + m_CurrentPacket.Write(bytes, bytesToSend); + return true; + } + + m_CurrentPacket.Write(bytes, bytesToSend); + if (maxDelay == 0.0f) + { + return SendInternalBuffer(); + } + return true; + } + + void QueuePacket() + { + pendingPacketCount += 1; + m_PendingPackets.Enqueue(m_CurrentPacket); + m_CurrentPacket = AllocPacket(); + } + + ChannelPacket AllocPacket() + { +#if UNITY_EDITOR + Profiler.SetStatOutgoing(MsgType.HLAPIPending, pendingPacketCount); +#endif + if (s_FreePackets.Count == 0) + { + return new ChannelPacket(m_MaxPacketSize, m_IsReliable); + } + + var packet = s_FreePackets[s_FreePackets.Count - 1]; + s_FreePackets.RemoveAt(s_FreePackets.Count - 1); + + packet.Reset(); + return packet; + } + + static void FreePacket(ChannelPacket packet) + { +#if UNITY_EDITOR + Profiler.SetStatOutgoing(MsgType.HLAPIPending, pendingPacketCount); +#endif + if (s_FreePackets.Count >= k_MaxFreePacketCount) + { + // just discard this packet, already tracking too many free packets + return; + } + s_FreePackets.Add(packet); + } + + public bool SendInternalBuffer() + { +#if UNITY_EDITOR + Profiler.IncrementStatOutgoing(MsgType.LLAPIMsg); +#endif + if (m_IsReliable && m_PendingPackets.Count > 0) + { + // send until transport can take no more + while (m_PendingPackets.Count > 0) + { + var packet = m_PendingPackets.Dequeue(); + if (!packet.SendToTransport(m_Connection, m_ChannelId)) + { + m_PendingPackets.Enqueue(packet); + break; + } + pendingPacketCount -= 1; + FreePacket(packet); + + if (m_IsBroken && m_PendingPackets.Count < (m_MaxPendingPacketCount / 2)) + { + if (LogFilter.logWarn) { Debug.LogWarning("ChannelBuffer recovered from overflow but data was lost."); } + m_IsBroken = false; + } + } + return true; + } + return m_CurrentPacket.SendToTransport(m_Connection, m_ChannelId); + } + } +} +#pragma warning restore 618 +#endif //ENABLE_UNET diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/ChannelPacket.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/ChannelPacket.cs new file mode 100644 index 00000000..ffc1841e --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/ChannelPacket.cs @@ -0,0 +1,81 @@ +#if ENABLE_UNET +using System; + +#pragma warning disable 618 +namespace UnityEngine.Networking +{ + // This is used by the ChannelBuffer when buffering traffic. + // Unreliable channels have a single ChannelPacket, Reliable channels have single "current" packet and a list of buffered ChannelPackets + struct ChannelPacket + { + public ChannelPacket(int packetSize, bool isReliable) + { + m_Position = 0; + m_Buffer = new byte[packetSize]; + m_IsReliable = isReliable; + } + + public void Reset() + { + m_Position = 0; + } + + public bool IsEmpty() + { + return m_Position == 0; + } + + public void Write(byte[] bytes, int numBytes) + { + Array.Copy(bytes, 0, m_Buffer, m_Position, numBytes); + m_Position += numBytes; + } + + public bool HasSpace(int numBytes) + { + return m_Position + numBytes <= m_Buffer.Length; + } + + public bool SendToTransport(NetworkConnection conn, int channelId) + { + byte error; + + bool result = true; + if (!conn.TransportSend(m_Buffer, (ushort)m_Position, channelId, out error)) + { + if (m_IsReliable && error == (int)NetworkError.NoResources) + { + // handled below + } + else + { + if (LogFilter.logError) { Debug.LogError("Failed to send internal buffer channel:" + channelId + " bytesToSend:" + m_Position); } + result = false; + } + } + if (error != 0) + { + if (m_IsReliable && error == (int)NetworkError.NoResources) + { + // this packet will be buffered by the containing ChannelBuffer, so this is not an error + +#if UNITY_EDITOR + Profiler.IncrementStatOutgoing(MsgType.HLAPIResend); +#endif + return false; + } + + if (LogFilter.logError) { Debug.LogError("Send Error: " + (NetworkError)error + " channel:" + channelId + " bytesToSend:" + m_Position); } + result = false; + } + m_Position = 0; + return result; + } + + int m_Position; + byte[] m_Buffer; + bool m_IsReliable; + } +} +#pragma warning restore 618 +#endif //ENABLE_UNET diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/ClientScene.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/ClientScene.cs new file mode 100644 index 00000000..7c109d02 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/ClientScene.cs @@ -0,0 +1,1135 @@ +using System; +using System.Collections.Generic; +using UnityEngine.Networking.NetworkSystem; + +namespace UnityEngine.Networking +{ + /// + /// A client manager which contains static client information and functions. + /// This manager contains references to tracked static local objects such as spawner registrations. It also has the default message handlers used by clients when they registered none themselves. The manager handles adding/removing player objects to the game after a client connection has been set as ready. + /// The ClientScene is a singleton, and it has static convenience methods such as ClientScene.Ready(). + /// The ClientScene is used by the NetworkManager, but it can be used by itself. + /// As the ClientScene manages player objects on the client, it is where clients request to add players. The NetworkManager does this via the ClientScene automatically when auto-add-players is set, but it can be done through code using the function ClientScene.AddPlayer(). This sends an AddPlayer message to the server and will cause a player object to be created for this client. + /// Like NetworkServer, the ClientScene understands the concept of the local client. The function ClientScene.ConnectLocalServer() is used to become a host by starting a local client (when a server is already running). + /// + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class ClientScene + { + static List s_LocalPlayers = new List(); + static NetworkConnection s_ReadyConnection; + static Dictionary s_SpawnableObjects; + + static bool s_IsReady; + static bool s_IsSpawnFinished; + static NetworkScene s_NetworkScene = new NetworkScene(); + + // static message objects to avoid runtime-allocations + static ObjectSpawnSceneMessage s_ObjectSpawnSceneMessage = new ObjectSpawnSceneMessage(); + static ObjectSpawnFinishedMessage s_ObjectSpawnFinishedMessage = new ObjectSpawnFinishedMessage(); + static ObjectDestroyMessage s_ObjectDestroyMessage = new ObjectDestroyMessage(); + static ObjectSpawnMessage s_ObjectSpawnMessage = new ObjectSpawnMessage(); + static OwnerMessage s_OwnerMessage = new OwnerMessage(); + static ClientAuthorityMessage s_ClientAuthorityMessage = new ClientAuthorityMessage(); + + /// + /// An invalid reconnect Id. + /// + public const int ReconnectIdInvalid = -1; + /// + /// A constant ID used by the old host when it reconnects to the new host. + /// + public const int ReconnectIdHost = 0; + static int s_ReconnectId = ReconnectIdInvalid; + static PeerInfoMessage[] s_Peers; + static bool hasMigrationPending() { return s_ReconnectId != ReconnectIdInvalid; } + + /// + /// Sets the Id that the ClientScene will use when reconnecting to a new host after host migration. + /// + /// The Id to use when reconnecting to a game. + /// The set of known peers in the game. This may be null. + static public void SetReconnectId(int newReconnectId, PeerInfoMessage[] peers) + { + s_ReconnectId = newReconnectId; + s_Peers = peers; + + if (LogFilter.logDebug) { Debug.Log("ClientScene::SetReconnectId: " + newReconnectId); } + } + + static internal void SetNotReady() + { + s_IsReady = false; + } + + struct PendingOwner + { + public NetworkInstanceId netId; + public short playerControllerId; + } + static List s_PendingOwnerIds = new List(); + + /// + /// A list of all players added to the game. + /// These are the players on this client, not all of the players in the game on the server. The client has no explicit knowledge of the player objects of other clients. + /// + public static List localPlayers { get { return s_LocalPlayers; } } + /// + /// Returns true when a client's connection has been set to ready. + /// A client that is ready recieves state updates from the server, while a client that is not ready does not. This useful when the state of the game is not normal, such as a scene change or end-of-game. + /// This is read-only. To change the ready state of a client, use ClientScene.Ready(). The server is able to set the ready state of clients using NetworkServer.SetClientReady(), NetworkServer.SetClientNotReady() and NetworkServer.SetAllClientsNotReady(). + /// This is done when changing scenes so that clients don't receive state update messages during scene loading. + /// + public static bool ready { get { return s_IsReady; } } + /// + /// The NetworkConnection object that is currently "ready". This is the connection to the server where objects are spawned from. + /// This connection can be used to send messages to the server. There can only be one ready connection at a time. There can be multiple NetworkClient instances in existence, each with their own NetworkConnections, but there is only one ClientScene instance and corresponding ready connection. + /// + public static NetworkConnection readyConnection { get { return s_ReadyConnection; }} + + /// + /// The reconnectId to use when a client reconnects to the new host of a game after the old host was lost. + /// This will be ClientScene.ReconnectIdInvalid by default (-1), and will be ClientScene.ReconnectIdHost when the old host is reconnecting to the host of the new game. + /// + public static int reconnectId { get { return s_ReconnectId; }} + + /// + /// This is a dictionary of networked objects that have been spawned on the client. + /// The key of the dictionary is the NetworkIdentity netId of the objects. + /// + //NOTE: spawn handlers, prefabs and local objects now live in NetworkScene + public static Dictionary objects { get { return s_NetworkScene.localObjects; } } + /// + /// This is a dictionary of the prefabs that are registered on the client with ClientScene.RegisterPrefab(). + /// The key to the dictionary is the prefab asset Id. + /// + public static Dictionary prefabs { get { return NetworkScene.guidToPrefab; } } + /// + /// This is dictionary of the disabled NetworkIdentity objects in the scene that could be spawned by messages from the server. + /// The key to the dictionary is the NetworkIdentity sceneId. + /// + public static Dictionary spawnableObjects { get { return s_SpawnableObjects; } } + + internal static void Shutdown() + { + s_NetworkScene.Shutdown(); + s_LocalPlayers = new List(); + s_PendingOwnerIds = new List(); + s_SpawnableObjects = null; + s_ReadyConnection = null; + s_IsReady = false; + s_IsSpawnFinished = false; + s_ReconnectId = ReconnectIdInvalid; + NetworkManager.activeTransport.Shutdown(); + NetworkManager.activeTransport.Init(); + } + + internal static bool GetPlayerController(short playerControllerId, out PlayerController player) + { + player = null; + if (playerControllerId >= localPlayers.Count) + { + if (LogFilter.logWarn) { Debug.Log("ClientScene::GetPlayer: no local player found for: " + playerControllerId); } + return false; + } + + if (localPlayers[playerControllerId] == null) + { + if (LogFilter.logWarn) { Debug.LogWarning("ClientScene::GetPlayer: local player is null for: " + playerControllerId); } + return false; + } + player = localPlayers[playerControllerId]; + return player.gameObject != null; + } + + // this is called from message handler for Owner message + internal static void InternalAddPlayer(NetworkIdentity view, short playerControllerId) + { + if (LogFilter.logDebug) { Debug.LogWarning("ClientScene::InternalAddPlayer: playerControllerId : " + playerControllerId); } + + if (playerControllerId >= s_LocalPlayers.Count) + { + if (LogFilter.logWarn) { Debug.LogWarning("ClientScene::InternalAddPlayer: playerControllerId higher than expected: " + playerControllerId); } + while (playerControllerId >= s_LocalPlayers.Count) + { + s_LocalPlayers.Add(new PlayerController()); + } + } + + // NOTE: It can be "normal" when changing scenes for the player to be destroyed and recreated. + // But, the player structures are not cleaned up, we'll just replace the old player + var newPlayer = new PlayerController {gameObject = view.gameObject, playerControllerId = playerControllerId, unetView = view}; + s_LocalPlayers[playerControllerId] = newPlayer; + if (s_ReadyConnection == null) + { + if (LogFilter.logWarn) { Debug.LogWarning("No ready connection found for setting player controller during InternalAddPlayer"); } + } + else + { + s_ReadyConnection.SetPlayerController(newPlayer); + } + } + + /// + /// This adds a player GameObject for this client. This causes an AddPlayer message to be sent to the server, and NetworkManager.OnServerAddPlayer is called. If an extra message was passed to AddPlayer, then OnServerAddPlayer will be called with a NetworkReader that contains the contents of the message. + /// The HLAPI treats players and clients as separate GameObjects. In most cases, there is a single player for each client, but in some situations (for example, when there are multiple controllers connected to a console system) there might be multiple player GameObjects for a single connection. When there are multiple players for a single connection, use the playerControllerId property to tell them apart. This is an identifier that is scoped to the connection, so that it maps to the id of the controller associated with the player on that client. This is not the global player number. + /// + /// The local player ID number. + /// True if player was added. + // use this if already ready + public static bool AddPlayer(short playerControllerId) + { + return AddPlayer(null, playerControllerId); + } + + /// + /// This adds a player GameObject for this client. This causes an AddPlayer message to be sent to the server, and NetworkManager.OnServerAddPlayer is called. If an extra message was passed to AddPlayer, then OnServerAddPlayer will be called with a NetworkReader that contains the contents of the message. + /// The HLAPI treats players and clients as separate GameObjects. In most cases, there is a single player for each client, but in some situations (for example, when there are multiple controllers connected to a console system) there might be multiple player GameObjects for a single connection. When there are multiple players for a single connection, use the playerControllerId property to tell them apart. This is an identifier that is scoped to the connection, so that it maps to the id of the controller associated with the player on that client. This is not the global player number. + /// + /// The connection to become ready for this client. + /// The local player ID number. + /// True if player was added. + // use this to implicitly become ready + public static bool AddPlayer(NetworkConnection readyConn, short playerControllerId) + { + return AddPlayer(readyConn, playerControllerId, null); + } + + /// + /// This adds a player GameObject for this client. This causes an AddPlayer message to be sent to the server, and NetworkManager.OnServerAddPlayer is called. If an extra message was passed to AddPlayer, then OnServerAddPlayer will be called with a NetworkReader that contains the contents of the message. + /// The HLAPI treats players and clients as separate GameObjects. In most cases, there is a single player for each client, but in some situations (for example, when there are multiple controllers connected to a console system) there might be multiple player GameObjects for a single connection. When there are multiple players for a single connection, use the playerControllerId property to tell them apart. This is an identifier that is scoped to the connection, so that it maps to the id of the controller associated with the player on that client. This is not the global player number. + /// + /// The connection to become ready for this client. + /// The local player ID number. + /// An extra message object that can be passed to the server for this player. + /// True if player was added. + // use this to implicitly become ready + public static bool AddPlayer(NetworkConnection readyConn, short playerControllerId, MessageBase extraMessage) + { + if (playerControllerId < 0) + { + if (LogFilter.logError) { Debug.LogError("ClientScene::AddPlayer: playerControllerId of " + playerControllerId + " is negative"); } + return false; + } + if (playerControllerId > PlayerController.MaxPlayersPerClient) + { + if (LogFilter.logError) { Debug.LogError("ClientScene::AddPlayer: playerControllerId of " + playerControllerId + " is too high, max is " + PlayerController.MaxPlayersPerClient); } + return false; + } + if (playerControllerId > PlayerController.MaxPlayersPerClient / 2) + { + if (LogFilter.logWarn) { Debug.LogWarning("ClientScene::AddPlayer: playerControllerId of " + playerControllerId + " is unusually high"); } + } + + // fill out local players array + while (playerControllerId >= s_LocalPlayers.Count) + { + s_LocalPlayers.Add(new PlayerController()); + } + + // ensure valid ready connection + if (readyConn == null) + { + if (!s_IsReady) + { + if (LogFilter.logError) { Debug.LogError("Must call AddPlayer() with a connection the first time to become ready."); } + return false; + } + } + else + { + s_IsReady = true; + s_ReadyConnection = readyConn; + } + + PlayerController existingPlayerController; + if (s_ReadyConnection.GetPlayerController(playerControllerId, out existingPlayerController)) + { + if (existingPlayerController.IsValid && existingPlayerController.gameObject != null) + { + if (LogFilter.logError) { Debug.LogError("ClientScene::AddPlayer: playerControllerId of " + playerControllerId + " already in use."); } + return false; + } + } + + if (LogFilter.logDebug) { Debug.Log("ClientScene::AddPlayer() for ID " + playerControllerId + " called with connection [" + s_ReadyConnection + "]"); } + + if (!hasMigrationPending()) + { + var msg = new AddPlayerMessage(); + msg.playerControllerId = playerControllerId; + if (extraMessage != null) + { + var writer = new NetworkWriter(); + extraMessage.Serialize(writer); + msg.msgData = writer.ToArray(); + msg.msgSize = writer.Position; + } + s_ReadyConnection.Send(MsgType.AddPlayer, msg); + } + else + { + return SendReconnectMessage(extraMessage); + } + return true; + } + + /// + /// Send a reconnect message to the new host, used during host migration. + /// An example usage might be that if you decide to spawn your own player and not use the built in "Auto Create Player" property in the NetworkManager together with HostMigration, you would need to send a reconnect message when your client reconnects. The code below illustrates such an example were we OnClientConnect check if we where disconnected from the host and in that case we send the reconnect message. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class NetworkManagerEx : NetworkManager + /// { + /// public override void OnClientConnect(NetworkConnection conn) + /// { + /// base.OnClientConnect(conn); + /// if (migrationManager.disconnectedFromHost) + /// { + /// ClientScene.SendReconnectMessage(null); + /// } + /// } + /// } + /// + /// + /// Any extra data to send. + /// Returns true if the send succeeded. + public static bool SendReconnectMessage(MessageBase extraMessage) + { + if (!hasMigrationPending()) + return false; + + if (LogFilter.logDebug) { Debug.Log("ClientScene::AddPlayer reconnect " + s_ReconnectId); } + + if (s_Peers == null) + { + SetReconnectId(ReconnectIdInvalid, null); + if (LogFilter.logError) + { + Debug.LogError("ClientScene::AddPlayer: reconnecting, but no peers."); + } + return false; + } + + // reconnect all the players + for (int i = 0; i < s_Peers.Length; i++) + { + var peer = s_Peers[i]; + if (peer.playerIds == null) + { + // this could be empty if this peer had no players + continue; + } + if (peer.connectionId == s_ReconnectId) + { + for (int pid = 0; pid < peer.playerIds.Length; pid++) + { + var msg = new ReconnectMessage(); + msg.oldConnectionId = s_ReconnectId; + msg.netId = peer.playerIds[pid].netId; + msg.playerControllerId = peer.playerIds[pid].playerControllerId; + if (extraMessage != null) + { + var writer = new NetworkWriter(); + extraMessage.Serialize(writer); + msg.msgData = writer.ToArray(); + msg.msgSize = writer.Position; + } + + s_ReadyConnection.Send(MsgType.ReconnectPlayer, msg); + } + } + } + // this should only be done once. + SetReconnectId(ReconnectIdInvalid, null); + return true; + } + + /// + /// Removes the specified player ID from the game. + /// Both the client and the server destroy the player GameObject and remove it from the player list. The playerControllerId is scoped to this client, not global to all players or clients. + /// The HLAPI treats players and clients as separate GameObjects. In most cases, there is a single player for each client, but in some situations (for example, when there are multiple controllers connected to a console system) there might be multiple player GameObjects for a single connection. When there are multiple players for a single connection, use the playerControllerId property to tell them apart. This is an identifier that is scoped to the connection, so that it maps to the id of the controller associated with the player on that client. + /// + /// The local playerControllerId number to be removed. + /// Returns true if the player was successfully destoyed and removed. + public static bool RemovePlayer(short playerControllerId) + { + if (LogFilter.logDebug) { Debug.Log("ClientScene::RemovePlayer() for ID " + playerControllerId + " called with connection [" + s_ReadyConnection + "]"); } + + PlayerController playerController; + if (s_ReadyConnection.GetPlayerController(playerControllerId, out playerController)) + { + var msg = new RemovePlayerMessage(); + msg.playerControllerId = playerControllerId; + s_ReadyConnection.Send(MsgType.RemovePlayer, msg); + + s_ReadyConnection.RemovePlayerController(playerControllerId); + s_LocalPlayers[playerControllerId] = new PlayerController(); + + Object.Destroy(playerController.gameObject); + return true; + } + if (LogFilter.logError) { Debug.LogError("Failed to find player ID " + playerControllerId); } + return false; + } + + /// + /// Signal that the client connection is ready to enter the game. + /// This could be for example when a client enters an ongoing game and has finished loading the current scene. The server should respond to the SYSTEM_READY event with an appropriate handler which instantiates the players object for example. + /// + /// using UnityEngine; + /// using UnityEngine.UI; + /// using UnityEngine.Networking; + /// + /// //This makes the GameObject a NetworkManager GameObject + /// public class Example : NetworkManager + /// { + /// public bool m_ServerStarted, m_ClientStarted; + /// public Button m_ClientButton; + /// + /// + /// //Detect when a client connects to the Server + /// public override void OnClientConnect(NetworkConnection connection) + /// { + /// ClientScene.Ready(connection); + /// ClientScene.AddPlayer(0); + /// m_ClientStarted = true; + /// //Output text to show the connection on the client side + /// Debug.Log("Client Side : Client " + connection.connectionId + " Connected!"); + /// //Register and receive the message on the Client's side (NetworkConnection.Send Example) + /// client.RegisterHandler(MsgType.Ready, ReadyMessage); + /// } + /// + /// //Use this to receive the message from the Server on the Client's side + /// public void ReadyMessage(NetworkMessage networkMessage) + /// { + /// Debug.Log("Client Ready! "); + /// } + /// + /// //Detect when a client disconnects from the Server + /// public override void OnClientDisconnect(NetworkConnection connection) + /// { + /// //Change the text to show the connection loss on the client side + /// Debug.Log("Client Side : Client " + connection.connectionId + " Lost!"); + /// m_ClientStarted = false; + /// } + /// public void ClientButton() + /// { + /// if (!m_ClientStarted) + /// { + /// NetworkServer.Reset(); + /// singleton.StartClient(); + /// m_ClientButton.GetComponentInChildren<Text>().text = "Disconnect"; + /// } + /// else + /// { + /// singleton.StopClient(); + /// } + /// } + /// } + /// + /// + /// The client connection which is ready. + /// + public static bool Ready(NetworkConnection conn) + { + if (s_IsReady) + { + if (LogFilter.logError) { Debug.LogError("A connection has already been set as ready. There can only be one."); } + return false; + } + + if (LogFilter.logDebug) { Debug.Log("ClientScene::Ready() called with connection [" + conn + "]"); } + + if (conn != null) + { + var msg = new ReadyMessage(); + conn.Send(MsgType.Ready, msg); + s_IsReady = true; + s_ReadyConnection = conn; + s_ReadyConnection.isReady = true; + return true; + } + if (LogFilter.logError) { Debug.LogError("Ready() called with invalid connection object: conn=null"); } + return false; + } + + /// + /// Create and connect a local client instance to the local server. This makes the client into a "host" - a client and server in the same process. + /// The returned local client acts like normal remote client but internally all messages are routed directly to the server process. Commands from a local client are executed synchronously on the server. + /// + /// A client object for communicating with the local server. + static public NetworkClient ConnectLocalServer() + { + var newClient = new LocalClient(); + NetworkServer.instance.ActivateLocalClientScene(); + newClient.InternalConnectLocalServer(true); + return newClient; + } + + static internal NetworkClient ReconnectLocalServer() + { + LocalClient newClient = new LocalClient(); + NetworkServer.instance.ActivateLocalClientScene(); + newClient.InternalConnectLocalServer(false); + return newClient; + } + + static internal void ClearLocalPlayers() + { + s_LocalPlayers.Clear(); + } + + static internal void HandleClientDisconnect(NetworkConnection conn) + { + if (s_ReadyConnection == conn && s_IsReady) + { + s_IsReady = false; + s_ReadyConnection = null; + } + } + + internal static void PrepareToSpawnSceneObjects() + { + //NOTE: what is there are already objects in this dict?! should we merge with them? + s_SpawnableObjects = new Dictionary(); + var uvs = Resources.FindObjectsOfTypeAll(); + for (int i = 0; i < uvs.Length; i++) + { + var uv = uvs[i]; + if (uv.gameObject.activeSelf) + { + // already active, cannot spawn it + continue; + } + + if (uv.gameObject.hideFlags == HideFlags.NotEditable || uv.gameObject.hideFlags == HideFlags.HideAndDontSave) + continue; + + if (uv.sceneId.IsEmpty()) + continue; + + s_SpawnableObjects[uv.sceneId] = uv; + + if (LogFilter.logDebug) { Debug.Log("ClientScene::PrepareSpawnObjects sceneId:" + uv.sceneId); } + } + } + + internal static NetworkIdentity SpawnSceneObject(NetworkSceneId sceneId) + { + if (s_SpawnableObjects.ContainsKey(sceneId)) + { + NetworkIdentity foundId = s_SpawnableObjects[sceneId]; + s_SpawnableObjects.Remove(sceneId); + return foundId; + } + return null; + } + + static internal void RegisterSystemHandlers(NetworkClient client, bool localClient) + { + if (localClient) + { + client.RegisterHandlerSafe(MsgType.ObjectDestroy, OnLocalClientObjectDestroy); + client.RegisterHandlerSafe(MsgType.ObjectHide, OnLocalClientObjectHide); + client.RegisterHandlerSafe(MsgType.ObjectSpawn, OnLocalClientObjectSpawn); + client.RegisterHandlerSafe(MsgType.ObjectSpawnScene, OnLocalClientObjectSpawnScene); + client.RegisterHandlerSafe(MsgType.LocalClientAuthority, OnClientAuthority); + } + else + { + // LocalClient shares the sim/scene with the server, no need for these events + client.RegisterHandlerSafe(MsgType.ObjectSpawn, OnObjectSpawn); + client.RegisterHandlerSafe(MsgType.ObjectSpawnScene, OnObjectSpawnScene); + client.RegisterHandlerSafe(MsgType.SpawnFinished, OnObjectSpawnFinished); + client.RegisterHandlerSafe(MsgType.ObjectDestroy, OnObjectDestroy); + client.RegisterHandlerSafe(MsgType.ObjectHide, OnObjectDestroy); + client.RegisterHandlerSafe(MsgType.UpdateVars, OnUpdateVarsMessage); + client.RegisterHandlerSafe(MsgType.Owner, OnOwnerMessage); + client.RegisterHandlerSafe(MsgType.SyncList, OnSyncListMessage); + client.RegisterHandlerSafe(MsgType.Animation, NetworkAnimator.OnAnimationClientMessage); + client.RegisterHandlerSafe(MsgType.AnimationParameters, NetworkAnimator.OnAnimationParametersClientMessage); + client.RegisterHandlerSafe(MsgType.LocalClientAuthority, OnClientAuthority); + } + + client.RegisterHandlerSafe(MsgType.Rpc, OnRPCMessage); + client.RegisterHandlerSafe(MsgType.SyncEvent, OnSyncEventMessage); + client.RegisterHandlerSafe(MsgType.AnimationTrigger, NetworkAnimator.OnAnimationTriggerClientMessage); + } + + // ------------------------ NetworkScene pass-throughs --------------------- + + static internal string GetStringForAssetId(NetworkHash128 assetId) + { + GameObject prefab; + if (NetworkScene.GetPrefab(assetId, out prefab)) + { + return prefab.name; + } + + SpawnDelegate handler; + if (NetworkScene.GetSpawnHandler(assetId, out handler)) + { + return handler.GetMethodName(); + } + + return "unknown"; + } + + /// + /// Registers a prefab with the UNET spawning system. + /// When a NetworkIdentity object is spawned on a server with NetworkServer.SpawnObject(), and the prefab that the object was created from was registered with RegisterPrefab(), the client will use that prefab to instantiate a corresponding client object with the same netId. + /// The NetworkManager has a list of spawnable prefabs, it uses this function to register those prefabs with the ClientScene. + /// The set of current spawnable object is available in the ClientScene static member variable ClientScene.prefabs, which is a dictionary of NetworkAssetIds and prefab references. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class PlantSpawner : NetworkBehaviour + /// { + /// public GameObject plantPrefab; + /// + /// public override void OnStartClient() + /// { + /// ClientScene.RegisterPrefab(plantPrefab); + /// } + /// + /// [Server] + /// public void ServerSpawnPlant(Vector3 pos, Quaternion rot) + /// { + /// var plant = (GameObject)Instantiate(plantPrefab, pos, rot); + /// NetworkServer.Spawn(plant); + /// } + /// } + /// + /// The optional custom spawn and un-spawn handler functions can be used to implement more advanced spawning strategies such as object pools. + /// + /// A Prefab that will be spawned. + /// An assetId to be assigned to this prefab. This allows a dynamically created game object to be registered for an already known asset Id. + // this assigns the newAssetId to the prefab. This is for registering dynamically created game objects for already know assetIds. + static public void RegisterPrefab(GameObject prefab, NetworkHash128 newAssetId) + { + NetworkScene.RegisterPrefab(prefab, newAssetId); + } + + /// + /// Registers a prefab with the UNET spawning system. + /// When a NetworkIdentity object is spawned on a server with NetworkServer.SpawnObject(), and the prefab that the object was created from was registered with RegisterPrefab(), the client will use that prefab to instantiate a corresponding client object with the same netId. + /// The NetworkManager has a list of spawnable prefabs, it uses this function to register those prefabs with the ClientScene. + /// The set of current spawnable object is available in the ClientScene static member variable ClientScene.prefabs, which is a dictionary of NetworkAssetIds and prefab references. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class PlantSpawner : NetworkBehaviour + /// { + /// public GameObject plantPrefab; + /// + /// public override void OnStartClient() + /// { + /// ClientScene.RegisterPrefab(plantPrefab); + /// } + /// + /// [Server] + /// public void ServerSpawnPlant(Vector3 pos, Quaternion rot) + /// { + /// var plant = (GameObject)Instantiate(plantPrefab, pos, rot); + /// NetworkServer.Spawn(plant); + /// } + /// } + /// + /// The optional custom spawn and un-spawn handler functions can be used to implement more advanced spawning strategies such as object pools. + /// + /// A Prefab that will be spawned. + static public void RegisterPrefab(GameObject prefab) + { + NetworkScene.RegisterPrefab(prefab); + } + + /// + /// Registers a prefab with the UNET spawning system. + /// When a NetworkIdentity object is spawned on a server with NetworkServer.SpawnObject(), and the prefab that the object was created from was registered with RegisterPrefab(), the client will use that prefab to instantiate a corresponding client object with the same netId. + /// The NetworkManager has a list of spawnable prefabs, it uses this function to register those prefabs with the ClientScene. + /// The set of current spawnable object is available in the ClientScene static member variable ClientScene.prefabs, which is a dictionary of NetworkAssetIds and prefab references. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class PlantSpawner : NetworkBehaviour + /// { + /// public GameObject plantPrefab; + /// + /// public override void OnStartClient() + /// { + /// ClientScene.RegisterPrefab(plantPrefab); + /// } + /// + /// [Server] + /// public void ServerSpawnPlant(Vector3 pos, Quaternion rot) + /// { + /// var plant = (GameObject)Instantiate(plantPrefab, pos, rot); + /// NetworkServer.Spawn(plant); + /// } + /// } + /// + /// The optional custom spawn and un-spawn handler functions can be used to implement more advanced spawning strategies such as object pools. + /// + /// A Prefab that will be spawned. + /// A method to use as a custom spawnhandler on clients. + /// A method to use as a custom un-spawnhandler on clients. + static public void RegisterPrefab(GameObject prefab, SpawnDelegate spawnHandler, UnSpawnDelegate unspawnHandler) + { + NetworkScene.RegisterPrefab(prefab, spawnHandler, unspawnHandler); + } + + /// + /// Removes a registered spawn prefab that was setup with ClientScene.RegisterPrefab. + /// + /// The prefab to be removed from registration. + static public void UnregisterPrefab(GameObject prefab) + { + NetworkScene.UnregisterPrefab(prefab); + } + + /// + /// This is an advanced spawning function that registers a custom assetId with the UNET spawning system. + /// This can be used to register custom spawning methods for an assetId - instead of the usual method of registering spawning methods for a prefab. This should be used when no prefab exists for the spawned objects - such as when they are constructed dynamically at runtime from configuration data. + /// + /// Custom assetId string. + /// A method to use as a custom spawnhandler on clients. + /// A method to use as a custom un-spawnhandler on clients. + static public void RegisterSpawnHandler(NetworkHash128 assetId, SpawnDelegate spawnHandler, UnSpawnDelegate unspawnHandler) + { + NetworkScene.RegisterSpawnHandler(assetId, spawnHandler, unspawnHandler); + } + + /// + /// Removes a registered spawn handler function that was registered with ClientScene.RegisterHandler(). + /// + /// The assetId for the handler to be removed for. + static public void UnregisterSpawnHandler(NetworkHash128 assetId) + { + NetworkScene.UnregisterSpawnHandler(assetId); + } + + /// + /// This clears the registered spawn prefabs and spawn handler functions for this client. + /// + static public void ClearSpawners() + { + NetworkScene.ClearSpawners(); + } + + /// + /// Destroys all networked objects on the client. + /// This can be used to clean up when a network connection is closed. + /// + static public void DestroyAllClientObjects() + { + s_NetworkScene.DestroyAllClientObjects(); + } + + /// + /// NetId is a unique number assigned to all objects with NetworkIdentity components in a game. + /// This number is the same on the server and all connected clients for a particular object, so it can be used to identify objects across the network. The FindLocalObject() function is called on a client to transform a netId received from a server to a local game object. + /// + /// NetId of object. + /// Networked object. + static public void SetLocalObject(NetworkInstanceId netId, GameObject obj) + { + // if still receiving initial state, dont set isClient + s_NetworkScene.SetLocalObject(netId, obj, s_IsSpawnFinished, false); + } + + /// + /// This finds the local NetworkIdentity object with the specified network Id. + /// NetId is a unique number assigned to all objects with NetworkIdentity components in a game. This number is the same on the server and all connected clients for a particular object, so it can be used to identify objects across the network. The FindLocalObject() function is called on a client to transform a netId received from a server to a local game object. + /// + /// The id of the networked object. + /// The game object that matches the netId. + static public GameObject FindLocalObject(NetworkInstanceId netId) + { + return s_NetworkScene.FindLocalObject(netId); + } + + static void ApplySpawnPayload(NetworkIdentity uv, Vector3 position, byte[] payload, NetworkInstanceId netId, GameObject newGameObject, NetworkMessage netMsg) + { + if (!uv.gameObject.activeSelf) + { + uv.gameObject.SetActive(true); + } + uv.transform.position = position; + if (payload != null && payload.Length > 0) + { + var payloadReader = new NetworkReader(payload); + uv.OnUpdateVars(payloadReader, true, netMsg); + } + if (newGameObject == null) + { + return; + } + + newGameObject.SetActive(true); + uv.SetNetworkInstanceId(netId); + SetLocalObject(netId, newGameObject); + + // objects spawned as part of initial state are started on a second pass + if (s_IsSpawnFinished) + { + uv.OnStartClient(); + CheckForOwner(uv); + } + } + + static void OnObjectSpawn(NetworkMessage netMsg) + { + netMsg.ReadMessage(s_ObjectSpawnMessage); + + if (!s_ObjectSpawnMessage.assetId.IsValid()) + { + if (LogFilter.logError) { Debug.LogError("OnObjSpawn netId: " + s_ObjectSpawnMessage.netId + " has invalid asset Id"); } + return; + } + if (LogFilter.logDebug) { Debug.Log("Client spawn handler instantiating [netId:" + s_ObjectSpawnMessage.netId + " asset ID:" + s_ObjectSpawnMessage.assetId + " pos:" + s_ObjectSpawnMessage.position + "]"); } + +#if UNITY_EDITOR + Profiler.IncrementStatIncoming(MsgType.ObjectSpawn, GetStringForAssetId(s_ObjectSpawnMessage.assetId)); +#endif + + NetworkIdentity localNetworkIdentity; + if (s_NetworkScene.GetNetworkIdentity(s_ObjectSpawnMessage.netId, out localNetworkIdentity)) + { + // this object already exists (was in the scene), just apply the update to existing object + ApplySpawnPayload(localNetworkIdentity, s_ObjectSpawnMessage.position, s_ObjectSpawnMessage.payload, s_ObjectSpawnMessage.netId, null, netMsg); + return; + } + + GameObject prefab; + SpawnDelegate handler; + if (NetworkScene.GetPrefab(s_ObjectSpawnMessage.assetId, out prefab)) + { + var obj = (GameObject)Object.Instantiate(prefab, s_ObjectSpawnMessage.position, s_ObjectSpawnMessage.rotation); + if (LogFilter.logDebug) + { + Debug.Log("Client spawn handler instantiating [netId:" + s_ObjectSpawnMessage.netId + " asset ID:" + s_ObjectSpawnMessage.assetId + " pos:" + s_ObjectSpawnMessage.position + " rotation: " + s_ObjectSpawnMessage.rotation + "]"); + } + + localNetworkIdentity = obj.GetComponent(); + if (localNetworkIdentity == null) + { + if (LogFilter.logError) { Debug.LogError("Client object spawned for " + s_ObjectSpawnMessage.assetId + " does not have a NetworkIdentity"); } + return; + } + localNetworkIdentity.Reset(); + ApplySpawnPayload(localNetworkIdentity, s_ObjectSpawnMessage.position, s_ObjectSpawnMessage.payload, s_ObjectSpawnMessage.netId, obj, netMsg); + } + // lookup registered factory for type: + else if (NetworkScene.GetSpawnHandler(s_ObjectSpawnMessage.assetId, out handler)) + { + GameObject obj = handler(s_ObjectSpawnMessage.position, s_ObjectSpawnMessage.assetId); + if (obj == null) + { + if (LogFilter.logWarn) { Debug.LogWarning("Client spawn handler for " + s_ObjectSpawnMessage.assetId + " returned null"); } + return; + } + localNetworkIdentity = obj.GetComponent(); + if (localNetworkIdentity == null) + { + if (LogFilter.logError) { Debug.LogError("Client object spawned for " + s_ObjectSpawnMessage.assetId + " does not have a network identity"); } + return; + } + localNetworkIdentity.Reset(); + localNetworkIdentity.SetDynamicAssetId(s_ObjectSpawnMessage.assetId); + ApplySpawnPayload(localNetworkIdentity, s_ObjectSpawnMessage.position, s_ObjectSpawnMessage.payload, s_ObjectSpawnMessage.netId, obj, netMsg); + } + else + { + if (LogFilter.logError) { Debug.LogError("Failed to spawn server object, did you forget to add it to the NetworkManager? assetId=" + s_ObjectSpawnMessage.assetId + " netId=" + s_ObjectSpawnMessage.netId); } + } + } + + static void OnObjectSpawnScene(NetworkMessage netMsg) + { + netMsg.ReadMessage(s_ObjectSpawnSceneMessage); + + if (LogFilter.logDebug) { Debug.Log("Client spawn scene handler instantiating [netId:" + s_ObjectSpawnSceneMessage.netId + " sceneId:" + s_ObjectSpawnSceneMessage.sceneId + " pos:" + s_ObjectSpawnSceneMessage.position); } + + +#if UNITY_EDITOR + Profiler.IncrementStatIncoming(MsgType.ObjectSpawnScene, "sceneId"); +#endif + + NetworkIdentity localNetworkIdentity; + if (s_NetworkScene.GetNetworkIdentity(s_ObjectSpawnSceneMessage.netId, out localNetworkIdentity)) + { + // this object already exists (was in the scene) + ApplySpawnPayload(localNetworkIdentity, s_ObjectSpawnSceneMessage.position, s_ObjectSpawnSceneMessage.payload, s_ObjectSpawnSceneMessage.netId, localNetworkIdentity.gameObject, netMsg); + return; + } + + NetworkIdentity spawnedId = SpawnSceneObject(s_ObjectSpawnSceneMessage.sceneId); + if (spawnedId == null) + { + if (LogFilter.logError) { Debug.LogError("Spawn scene object not found for " + s_ObjectSpawnSceneMessage.sceneId); } + return; + } + + if (LogFilter.logDebug) { Debug.Log("Client spawn for [netId:" + s_ObjectSpawnSceneMessage.netId + "] [sceneId:" + s_ObjectSpawnSceneMessage.sceneId + "] obj:" + spawnedId.gameObject.name); } + ApplySpawnPayload(spawnedId, s_ObjectSpawnSceneMessage.position, s_ObjectSpawnSceneMessage.payload, s_ObjectSpawnSceneMessage.netId, spawnedId.gameObject, netMsg); + } + + static void OnObjectSpawnFinished(NetworkMessage netMsg) + { + netMsg.ReadMessage(s_ObjectSpawnFinishedMessage); + if (LogFilter.logDebug) { Debug.Log("SpawnFinished:" + s_ObjectSpawnFinishedMessage.state); } + + if (s_ObjectSpawnFinishedMessage.state == 0) + { + PrepareToSpawnSceneObjects(); + s_IsSpawnFinished = false; + return; + } + + foreach (var uv in objects.Values) + { + if (!uv.isClient) + { + uv.OnStartClient(); + CheckForOwner(uv); + } + } + s_IsSpawnFinished = true; + } + + static void OnObjectDestroy(NetworkMessage netMsg) + { + netMsg.ReadMessage(s_ObjectDestroyMessage); + if (LogFilter.logDebug) { Debug.Log("ClientScene::OnObjDestroy netId:" + s_ObjectDestroyMessage.netId); } + + NetworkIdentity localObject; + if (s_NetworkScene.GetNetworkIdentity(s_ObjectDestroyMessage.netId, out localObject)) + { +#if UNITY_EDITOR + Profiler.IncrementStatIncoming(MsgType.ObjectDestroy, GetStringForAssetId(localObject.assetId)); +#endif + localObject.OnNetworkDestroy(); + + if (!NetworkScene.InvokeUnSpawnHandler(localObject.assetId, localObject.gameObject)) + { + // default handling + if (localObject.sceneId.IsEmpty()) + { + Object.Destroy(localObject.gameObject); + } + else + { + // scene object.. disable it in scene instead of destroying + localObject.gameObject.SetActive(false); + s_SpawnableObjects[localObject.sceneId] = localObject; + } + } + s_NetworkScene.RemoveLocalObject(s_ObjectDestroyMessage.netId); + localObject.MarkForReset(); + } + else + { + if (LogFilter.logDebug) { Debug.LogWarning("Did not find target for destroy message for " + s_ObjectDestroyMessage.netId); } + } + } + + static void OnLocalClientObjectDestroy(NetworkMessage netMsg) + { + netMsg.ReadMessage(s_ObjectDestroyMessage); + if (LogFilter.logDebug) { Debug.Log("ClientScene::OnLocalObjectObjDestroy netId:" + s_ObjectDestroyMessage.netId); } + + s_NetworkScene.RemoveLocalObject(s_ObjectDestroyMessage.netId); + } + + static void OnLocalClientObjectHide(NetworkMessage netMsg) + { + netMsg.ReadMessage(s_ObjectDestroyMessage); + if (LogFilter.logDebug) { Debug.Log("ClientScene::OnLocalObjectObjHide netId:" + s_ObjectDestroyMessage.netId); } + + NetworkIdentity localObject; + if (s_NetworkScene.GetNetworkIdentity(s_ObjectDestroyMessage.netId, out localObject)) + { + localObject.OnSetLocalVisibility(false); + } + } + + static void OnLocalClientObjectSpawn(NetworkMessage netMsg) + { + netMsg.ReadMessage(s_ObjectSpawnMessage); + NetworkIdentity localObject; + if (s_NetworkScene.GetNetworkIdentity(s_ObjectSpawnMessage.netId, out localObject)) + { + localObject.OnSetLocalVisibility(true); + } + } + + static void OnLocalClientObjectSpawnScene(NetworkMessage netMsg) + { + netMsg.ReadMessage(s_ObjectSpawnSceneMessage); + NetworkIdentity localObject; + if (s_NetworkScene.GetNetworkIdentity(s_ObjectSpawnSceneMessage.netId, out localObject)) + { + localObject.OnSetLocalVisibility(true); + } + } + + static void OnUpdateVarsMessage(NetworkMessage netMsg) + { + NetworkInstanceId netId = netMsg.reader.ReadNetworkId(); + if (LogFilter.logDev) { Debug.Log("ClientScene::OnUpdateVarsMessage " + netId + " channel:" + netMsg.channelId); } + + + NetworkIdentity localObject; + if (s_NetworkScene.GetNetworkIdentity(netId, out localObject)) + { + localObject.OnUpdateVars(netMsg.reader, false, netMsg); + } + else + { + if (LogFilter.logWarn) { Debug.LogWarning("Did not find target for sync message for " + netId); } + } + } + + static void OnRPCMessage(NetworkMessage netMsg) + { + var cmdHash = (int)netMsg.reader.ReadPackedUInt32(); + var netId = netMsg.reader.ReadNetworkId(); + + if (LogFilter.logDebug) { Debug.Log("ClientScene::OnRPCMessage hash:" + cmdHash + " netId:" + netId); } + + NetworkIdentity uv; + if (s_NetworkScene.GetNetworkIdentity(netId, out uv)) + { + uv.HandleRPC(cmdHash, netMsg.reader); + } + else + { + if (LogFilter.logWarn) + { + string errorCmdName = NetworkBehaviour.GetCmdHashHandlerName(cmdHash); + Debug.LogWarningFormat("Could not find target object with netId:{0} for RPC call {1}", netId, errorCmdName); + } + } + } + + static void OnSyncEventMessage(NetworkMessage netMsg) + { + var cmdHash = (int)netMsg.reader.ReadPackedUInt32(); + var netId = netMsg.reader.ReadNetworkId(); + + if (LogFilter.logDebug) { Debug.Log("ClientScene::OnSyncEventMessage " + netId); } + + NetworkIdentity uv; + if (s_NetworkScene.GetNetworkIdentity(netId, out uv)) + { + uv.HandleSyncEvent(cmdHash, netMsg.reader); + } + else + { + if (LogFilter.logWarn) { Debug.LogWarning("Did not find target for SyncEvent message for " + netId); } + } + +#if UNITY_EDITOR + Profiler.IncrementStatOutgoing(MsgType.SyncEvent, NetworkBehaviour.GetCmdHashHandlerName(cmdHash)); +#endif + } + + static void OnSyncListMessage(NetworkMessage netMsg) + { + var netId = netMsg.reader.ReadNetworkId(); + var cmdHash = (int)netMsg.reader.ReadPackedUInt32(); + + if (LogFilter.logDebug) { Debug.Log("ClientScene::OnSyncListMessage " + netId); } + + NetworkIdentity uv; + if (s_NetworkScene.GetNetworkIdentity(netId, out uv)) + { + uv.HandleSyncList(cmdHash, netMsg.reader); + } + else + { + if (LogFilter.logWarn) { Debug.LogWarning("Did not find target for SyncList message for " + netId); } + } + +#if UNITY_EDITOR + Profiler.IncrementStatOutgoing(MsgType.SyncList, NetworkBehaviour.GetCmdHashHandlerName(cmdHash)); +#endif + } + + static void OnClientAuthority(NetworkMessage netMsg) + { + netMsg.ReadMessage(s_ClientAuthorityMessage); + + if (LogFilter.logDebug) { Debug.Log("ClientScene::OnClientAuthority for connectionId=" + netMsg.conn.connectionId + " netId: " + s_ClientAuthorityMessage.netId); } + + NetworkIdentity uv; + if (s_NetworkScene.GetNetworkIdentity(s_ClientAuthorityMessage.netId, out uv)) + { + uv.HandleClientAuthority(s_ClientAuthorityMessage.authority); + } + } + + // OnClientAddedPlayer? + static void OnOwnerMessage(NetworkMessage netMsg) + { + netMsg.ReadMessage(s_OwnerMessage); + + if (LogFilter.logDebug) { Debug.Log("ClientScene::OnOwnerMessage - connectionId=" + netMsg.conn.connectionId + " netId: " + s_OwnerMessage.netId); } + + + // is there already an owner that is a different object?? + PlayerController oldOwner; + if (netMsg.conn.GetPlayerController(s_OwnerMessage.playerControllerId, out oldOwner)) + { + oldOwner.unetView.SetNotLocalPlayer(); + } + + NetworkIdentity localNetworkIdentity; + if (s_NetworkScene.GetNetworkIdentity(s_OwnerMessage.netId, out localNetworkIdentity)) + { + // this object already exists + localNetworkIdentity.SetConnectionToServer(netMsg.conn); + localNetworkIdentity.SetLocalPlayer(s_OwnerMessage.playerControllerId); + InternalAddPlayer(localNetworkIdentity, s_OwnerMessage.playerControllerId); + } + else + { + var pendingOwner = new PendingOwner { netId = s_OwnerMessage.netId, playerControllerId = s_OwnerMessage.playerControllerId }; + s_PendingOwnerIds.Add(pendingOwner); + } + } + + static void CheckForOwner(NetworkIdentity uv) + { + for (int i = 0; i < s_PendingOwnerIds.Count; i++) + { + var pendingOwner = s_PendingOwnerIds[i]; + + if (pendingOwner.netId == uv.netId) + { + // found owner, turn into a local player + + // Set isLocalPlayer to true on this NetworkIdentity and trigger OnStartLocalPlayer in all scripts on the same GO + uv.SetConnectionToServer(s_ReadyConnection); + uv.SetLocalPlayer(pendingOwner.playerControllerId); + + if (LogFilter.logDev) { Debug.Log("ClientScene::OnOwnerMessage - player=" + uv.gameObject.name); } + if (s_ReadyConnection.connectionId < 0) + { + if (LogFilter.logError) { Debug.LogError("Owner message received on a local client."); } + return; + } + InternalAddPlayer(uv, pendingOwner.playerControllerId); + + s_PendingOwnerIds.RemoveAt(i); + break; + } + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/ConnectionArray.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/ConnectionArray.cs new file mode 100644 index 00000000..c540dc4d --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/ConnectionArray.cs @@ -0,0 +1,128 @@ +#if ENABLE_UNET +using System; +using System.Collections.Generic; + +#pragma warning disable 618 +namespace UnityEngine.Networking +{ + // This has a list of real connections + // The local or "fake" connections are kept separate because sometimes you + // only want to iterate through those, and not all connections. + class ConnectionArray + { + List m_LocalConnections; + List m_Connections; + + internal List localConnections { get { return m_LocalConnections; }} + internal List connections { get { return m_Connections; }} + + public int Count { get { return m_Connections.Count; } } + + public int LocalIndex { get { return -m_LocalConnections.Count; } } + + public ConnectionArray() + { + m_Connections = new List(); + m_LocalConnections = new List(); + } + + public int Add(int connId, NetworkConnection conn) + { + if (connId < 0) + { + if (LogFilter.logWarn) {Debug.LogWarning("ConnectionArray Add bad id " + connId); } + return -1; + } + + if (connId < m_Connections.Count && m_Connections[connId] != null) + { + if (LogFilter.logWarn) { Debug.LogWarning("ConnectionArray Add dupe at " + connId); } + return -1; + } + + while (connId > (m_Connections.Count - 1)) + { + m_Connections.Add(null); + } + + m_Connections[connId] = conn; + return connId; + } + + // call this if you know the connnection exists + public NetworkConnection Get(int connId) + { + if (connId < 0) + { + return m_LocalConnections[Mathf.Abs(connId) - 1]; + } + + if (connId > m_Connections.Count) + { + if (LogFilter.logWarn) { Debug.LogWarning("ConnectionArray Get invalid index " + connId); } + return null; + } + + return m_Connections[connId]; + } + + // call this if the connection may not exist (in disconnect handler) + public NetworkConnection GetUnsafe(int connId) + { + if (connId < 0 || connId > m_Connections.Count) + { + return null; + } + return m_Connections[connId]; + } + + public void Remove(int connId) + { + if (connId < 0) + { + m_LocalConnections[Mathf.Abs(connId) - 1] = null; + return; + } + + if (connId > m_Connections.Count) + { + if (LogFilter.logWarn) { Debug.LogWarning("ConnectionArray Remove invalid index " + connId); } + return; + } + m_Connections[connId] = null; + } + + public int AddLocal(NetworkConnection conn) + { + m_LocalConnections.Add(conn); + int index = -m_LocalConnections.Count; + conn.connectionId = index; + return index; + } + + public bool ContainsPlayer(GameObject player, out NetworkConnection conn) + { + conn = null; + if (player == null) + return false; + + for (int i = LocalIndex; i < m_Connections.Count; i++) + { + conn = Get(i); + if (conn != null) + { + for (int j = 0; j < conn.playerControllers.Count; j++) + { + if (conn.playerControllers[j].IsValid && conn.playerControllers[j].gameObject == player) + { + return true; + } + } + } + } + return false; + } + } +} +#pragma warning restore 618 +#endif //ENABLE_UNET diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/CustomAttributes.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/CustomAttributes.cs new file mode 100644 index 00000000..e00775a9 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/CustomAttributes.cs @@ -0,0 +1,514 @@ +using System; + + +namespace UnityEngine.Networking +{ + /// + /// This attribute is used to configure the network settings of scripts that are derived from the NetworkBehaviour base class. + /// + /// using UnityEngine.Networking; + /// + /// [NetworkSettings(channel = 1, sendInterval = 0.2f)] + /// class MyScript : NetworkBehaviour + /// { + /// [SyncVar] + /// int value; + /// } + /// + /// + [AttributeUsage(AttributeTargets.Class)] + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class NetworkSettingsAttribute : Attribute + { + /// + /// The QoS channel to use for updates for this script. + /// Updates for SyncVar variables will be sent on the specified QoS channel. The default channel for scripts is zero. + /// + public int channel = Channels.DefaultReliable; + /// + /// The sendInterval control how frequently updates are sent for this script. + /// If sendInterval is zero, updates will be sent at the end of the frame when dirty bits are set for that script. Note that setting the value of a SyncVar will automatically set dirty bits. + /// If sendInterval is non-zero, updates are deferred until sendInterval seconds have passed since the last update for that script. So it can be used as a throttle in cases where the Sync value is changing constantly on the server, but you don't want it to be updated every frame. + /// The default sendInterval for scripts is 0.1f seconds. + /// The send interval can also be customized by implementing the virtual function GetNetworkSendInterval() on NetworkBehaviour. + /// + public float sendInterval = 0.1f; + } + + /// + /// [SyncVar] is an attribute that can be put on member variables of NetworkBehaviour classes. These variables will have their values sychronized from the server to clients in the game that are in the ready state. + /// Setting the value of a [SyncVar] marks it as dirty, so it will be sent to clients at the end of the current frame. Only simple values can be marked as [SyncVars]. The type of the SyncVar variable cannot be from an external DLL or assembly. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class Ship : NetworkBehaviour + /// { + /// [SyncVar] + /// public int health = 100; + /// + /// [SyncVar] + /// public float energy = 100; + /// } + /// + /// The allowed SyncVar types are: + /// + /// + /// Basic type (byte, int, float, string, UInt64, etc) + /// + /// + /// Built-in Unity math type (Vector3, Quaternion, etc), + /// + /// + /// Structs containing allowable types. + /// + /// + /// + [AttributeUsage(AttributeTargets.Field)] + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class SyncVarAttribute : Attribute + { + /// + /// The hook attribute can be used to specify a function to be called when the sync var changes value on the client. + /// This ensures that all clients receive the proper variables from other clients. + /// + /// //Attach this to the GameObject you would like to spawn (the player). + /// //Make sure to create a NetworkManager with an HUD component in your Scene. To do this, create a GameObject, click on it, and click on the Add Component button in the Inspector window. From there, Go to Network>NetworkManager and Network>NetworkManagerHUD respectively. + /// //Assign the GameObject you would like to spawn in the NetworkManager. + /// //Start the server and client for this to work. + /// + /// //Use this script to send and update variables between Networked GameObjects + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class Health : NetworkBehaviour + /// { + /// public const int m_MaxHealth = 100; + /// + /// //Detects when a health change happens and calls the appropriate function + /// [SyncVar(hook = "OnChangeHealth")] + /// public int m_CurrentHealth = m_MaxHealth; + /// public RectTransform healthBar; + /// + /// public void TakeDamage(int amount) + /// { + /// if (!isServer) + /// return; + /// //Decrease the "health" of the GameObject + /// m_CurrentHealth -= amount; + /// //Make sure the health doesn't go below 0 + /// if (m_CurrentHealth <= 0) + /// { + /// m_CurrentHealth = 0; + /// } + /// } + /// + /// void Update() + /// { + /// //If the space key is pressed, decrease the GameObject's own "health" + /// if (Input.GetKey(KeyCode.Space)) + /// { + /// if (isLocalPlayer) + /// CmdTakeHealth(); + /// } + /// } + /// + /// void OnChangeHealth(int health) + /// { + /// healthBar.sizeDelta = new Vector2(health, healthBar.sizeDelta.y); + /// } + /// + /// //This is a Network command, so the damage is done to the relevant GameObject + /// [Command] + /// void CmdTakeHealth() + /// { + /// //Apply damage to the GameObject + /// TakeDamage(2); + /// } + /// } + /// + /// + public string hook; + } + + /// + /// This is an attribute that can be put on methods of NetworkBehaviour classes to allow them to be invoked on the server by sending a command from a client. + /// [Command] functions are invoked on the player GameObject associated with a connection. This is set up in response to the "ready" message, by passing the player GameObject to the NetworkServer.PlayerIsReady() function. The arguments to the command call are serialized across the network, so that the server function is invoked with the same values as the function on the client. These functions must begin with the prefix "Cmd" and cannot be static. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class Player : NetworkBehaviour + /// { + /// int moveX = 0; + /// int moveY = 0; + /// float moveSpeed = 0.2f; + /// bool isDirty = false; + /// + /// void Update() + /// { + /// if (!isLocalPlayer) + /// { + /// return; + /// } + /// // input handling for local player only + /// int oldMoveX = moveX; + /// int oldMoveY = moveY; + /// moveX = 0; + /// moveY = 0; + /// if (Input.GetKey(KeyCode.LeftArrow)) + /// { + /// moveX -= 1; + /// } + /// if (Input.GetKey(KeyCode.RightArrow)) + /// { + /// moveX += 1; + /// } + /// if (Input.GetKey(KeyCode.UpArrow)) + /// { + /// moveY += 1; + /// } + /// if (Input.GetKey(KeyCode.DownArrow)) + /// { + /// moveY -= 1; + /// } + /// if (moveX != oldMoveX || moveY != oldMoveY) + /// { + /// CmdMove(moveX, moveY); + /// } + /// } + /// + /// [Command] + /// public void CmdMove(int x, int y) + /// { + /// moveX = x; + /// moveY = y; + /// isDirty = true; + /// } + /// + /// public void FixedUpdate() + /// { + /// if (NetworkServer.active) + /// { + /// transform.Translate(moveX * moveSpeed, moveY * moveSpeed, 0); + /// } + /// } + /// } + /// + /// The allowed argument types are; + /// + /// + /// Basic type (byte, int, float, string, UInt64, etc) + /// + /// + /// Built-in Unity math type (Vector3, Quaternion, etc), + /// + /// + /// Arrays of basic types + /// + /// + /// Structs containing allowable types + /// + /// + /// NetworkIdentity + /// + /// + /// NetworkInstanceId + /// + /// + /// NetworkHash128 + /// + /// + /// GameObject with a NetworkIdentity component attached. + /// + /// + /// + [AttributeUsage(AttributeTargets.Method)] + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class CommandAttribute : Attribute + { + /// + /// The QoS channel to use to send this command on, see QosType. + /// + public int channel = Channels.DefaultReliable; // this is zero + } + + /// + /// This is an attribute that can be put on methods of NetworkBehaviour classes to allow them to be invoked on clients from a server. + /// [ClientRPC] functions are called by code on Unity Multiplayer servers, and then invoked on corresponding GameObjects on clients connected to the server. The arguments to the RPC call are serialized across the network, so that the client function is invoked with the same values as the function on the server. These functions must begin with the prefix "Rpc" and cannot be static. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class Example : NetworkBehaviour + /// { + /// int counter; + /// [ClientRpc] + /// public void RpcDoMagic(int extra) + /// { + /// Debug.Log("Magic = " + (123 + extra)); + /// } + /// + /// void Update() + /// { + /// counter += 1; + /// if (counter % 100 == 0 && NetworkServer.active) + /// { + /// RpcDoMagic(counter); + /// } + /// } + /// } + /// + /// The allowed argument types are; + /// + /// + /// Basic type (byte, int, float, string, UInt64, etc) + /// + /// + /// Built-in Unity math type (Vector3, Quaternion, etc), + /// + /// + /// Arrays of basic types + /// + /// + /// Structs containing allowable types + /// + /// + /// NetworkIdentity + /// + /// + /// NetworkInstanceId + /// + /// + /// NetworkHash128 + /// + /// + /// GameObject with a NetworkIdentity component attached. + /// + /// + /// + [AttributeUsage(AttributeTargets.Method)] + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class ClientRpcAttribute : Attribute + { + /// + /// The channel ID which this RPC transmission will use. + /// + public int channel = Channels.DefaultReliable; // this is zero + } + + /// + /// This is an attribute that can be put on methods of NetworkBehaviour classes to allow them to be invoked on clients from a server. Unlike the ClientRpc attribute, these functions are invoked on one individual target client, not all of the ready clients. + /// [TargetRpc] functions are called by user code on the server, and then invoked on the corresponding client object on the client of the specified NetworkConnection. The arguments to the RPC call are serialized across the network, so that the client function is invoked with the same values as the function on the server. These functions must begin with the prefix "Target" and cannot be static. + /// The first argument to an TargetRpc function must be a NetworkConnection object. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class Example : NetworkBehaviour + /// { + /// [TargetRpc] + /// public void TargetDoMagic(NetworkConnection target, int extra) + /// { + /// Debug.Log("Magic = " + (123 + extra)); + /// } + /// + /// [Command] + /// void CmdTest() + /// { + /// TargetDoMagic(connectionToClient, 55); + /// } + /// } + /// + /// The allowed argument types are; + /// + /// + /// Basic type (byte, int, float, string, UInt64, etc) + /// + /// + /// Built-in Unity math type (Vector3, Quaternion, etc), + /// + /// + /// Arrays of basic types + /// + /// + /// Structs containing allowable types + /// + /// + /// NetworkIdentity + /// + /// + /// NetworkInstanceId + /// + /// + /// NetworkHash128 + /// + /// + /// GameObject with a NetworkIdentity component attached. + /// + /// + /// + [AttributeUsage(AttributeTargets.Method)] + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class TargetRpcAttribute : Attribute + { + /// + /// The channel ID which this RPC transmission will use. + /// + public int channel = Channels.DefaultReliable; // this is zero + } + + /// + /// This is an attribute that can be put on events in NetworkBehaviour classes to allow them to be invoked on client when the event is called on the server. + /// [SyncEvent] events are called by user code on UNET servers, and then invoked on corresponding client objects on clients connected to the server. The arguments to the Event call are serialized across the network, so that the client event is invoked with the same values as the function on the server. These events must begin with the prefix "Event". + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class DamageClass : NetworkBehaviour + /// { + /// public delegate void TakeDamageDelegate(int amount, float dir); + /// + /// [SyncEvent] + /// public event TakeDamageDelegate EventTakeDamage; + /// + /// [Command] + /// public void CmdDoMe(int val) + /// { + /// EventTakeDamage(val, 1.0f); + /// } + /// } + /// + /// public class Other : NetworkBehaviour + /// { + /// public DamageClass damager; + /// int health = 100; + /// + /// void Start() + /// { + /// if (NetworkClient.active) + /// damager.EventTakeDamage += TakeDamage; + /// } + /// + /// public void TakeDamage(int amount, float dir) + /// { + /// health -= amount; + /// } + /// } + /// + /// SyncEvents allow networked actions to be propagated to other scripts attached to the object. In the example above, the Other class registers for the TakeDamage event on the DamageClass. When the event happens on the DamageClass on the server, the TakeDamage() method will be invoked on the Other class on the client object. This allows modular network aware systems to be created, that can be extended by new scripts that respond to the events generated by them. + /// + [AttributeUsage(AttributeTargets.Event)] + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class SyncEventAttribute : Attribute + { + /// + /// The UNET QoS channel that this event should be sent on. + /// This defaults to zero - the default reliable channel. This can be used to make events that are not essential for game play (such as effects) unreliable. + /// + public int channel = Channels.DefaultReliable; // this is zero + } + + /// + /// A Custom Attribute that can be added to member functions of NetworkBehaviour scripts, to make them only run on servers. + /// A [Server] method returns immediately if NetworkServer.active is not true, and generates a warning on the console. This attribute can be put on member functions that are meant to be only called on server. This would be redundant for Command] functions, as being server-only is already enforced for them. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class Example : NetworkBehaviour + /// { + /// [Server] + /// public void Explode() + /// { + /// NetworkServer.Destroy(gameObject); + /// } + /// } + /// + /// + [AttributeUsage(AttributeTargets.Method)] + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class ServerAttribute : Attribute + { + } + + /// + /// A Custom Attribute that can be added to member functions of NetworkBehaviour scripts, to make them only run on servers, but not generate warnings. + /// This custom attribute is the same as the [Server] custom attribute, except that it does not generate a warning in the console if called on a client. This is useful to avoid spamming the console for functions that will be invoked by the engine, such as Update() or physics callbacks. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class Example : MonoBehaviour + /// { + /// float regenTimer = 0; + /// int heat = 100; + /// + /// [ServerCallback] + /// void Update() + /// { + /// // heat dissipates over time + /// if (Time.time > regenTimer) + /// { + /// if (heat > 1) + /// heat -= 2; + /// regenTimer = Time.time + 1.0f; + /// } + /// } + /// } + /// + /// + [AttributeUsage(AttributeTargets.Method)] + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class ServerCallbackAttribute : Attribute + { + } + + /// + /// A Custom Attribute that can be added to member functions of NetworkBehaviour scripts, to make them only run on clients. + /// A [Client] method returns immediately if NetworkClient.active is not true, and generates a warning on the console. This attribute can be put on member functions that are meant to be only called on clients. This would redundant for [ClientRPC] functions, as being client-only is already enforced for them. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class Example : MonoBehaviour + /// { + /// [Client] + /// public void OnClientDisconnected(NetworkConnection conn, NetworkReader reader) + /// { + /// Debug.Log("Client Disconnected"); + /// //ShutdownGame(); + /// Application.LoadLevel("title"); + /// } + /// } + /// + /// + [AttributeUsage(AttributeTargets.Method)] + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class ClientAttribute : Attribute + { + } + + /// + /// A Custom Attribute that can be added to member functions of NetworkBehaviour scripts, to make them only run on clients, but not generate warnings. + /// This custom attribute is the same as the Client custom attribute, except that it does not generate a warning in the console if called on a server. This is useful to avoid spamming the console for functions that will be invoked by the engine, such as Update() or physics callbacks. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class Example : MonoBehaviour + /// { + /// [ClientCallback] + /// void OnTriggerEnter2D(Collider2D collider) + /// { + /// // make explosion + /// } + /// } + /// + /// + [AttributeUsage(AttributeTargets.Method)] + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class ClientCallbackAttribute : Attribute + { + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/DefaultNetworkTransport.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/DefaultNetworkTransport.cs new file mode 100644 index 00000000..0fb04e80 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/DefaultNetworkTransport.cs @@ -0,0 +1,156 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Text; + +using UnityEngine.Networking.Types; + +namespace UnityEngine.Networking +{ + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + class DefaultNetworkTransport : INetworkTransport + { + public DefaultNetworkTransport() + { + } + + public bool IsStarted + { + get + { + return NetworkTransport.IsStarted; + } + } + + public int AddHost(HostTopology topology, int port, string ip) + { + return NetworkTransport.AddHost(topology, port, ip); + } + + public int AddHostWithSimulator(HostTopology topology, int minTimeout, int maxTimeout, int port) + { + return NetworkTransport.AddHostWithSimulator(topology, minTimeout, maxTimeout, port); + } + + public int AddWebsocketHost(HostTopology topology, int port, string ip) + { + return NetworkTransport.AddWebsocketHost(topology, port, ip); + } + + public int Connect(int hostId, string address, int port, int specialConnectionId, out byte error) + { + return NetworkTransport.Connect(hostId, address, port, specialConnectionId, out error); + } + + public void ConnectAsNetworkHost(int hostId, string address, int port, NetworkID network, SourceID source, NodeID node, out byte error) + { + NetworkTransport.ConnectAsNetworkHost(hostId, address, port, network, source, node, out error); + } + + public int ConnectEndPoint(int hostId, EndPoint endPoint, int specialConnectionId, out byte error) + { + return NetworkTransport.ConnectEndPoint(hostId, endPoint, specialConnectionId, out error); + } + + public int ConnectToNetworkPeer(int hostId, string address, int port, int specialConnectionId, int relaySlotId, NetworkID network, SourceID source, NodeID node, out byte error) + { + return NetworkTransport.ConnectToNetworkPeer(hostId, address, port, specialConnectionId, relaySlotId, network, source, node, out error); + } + + public int ConnectWithSimulator(int hostId, string address, int port, int specialConnectionId, out byte error, ConnectionSimulatorConfig conf) + { + return NetworkTransport.ConnectWithSimulator(hostId, address, port, specialConnectionId, out error, conf); + } + + public bool Disconnect(int hostId, int connectionId, out byte error) + { + return NetworkTransport.Disconnect(hostId, connectionId, out error); + } + + public bool DoesEndPointUsePlatformProtocols(EndPoint endPoint) + { + return NetworkTransport.DoesEndPointUsePlatformProtocols(endPoint); + } + + public void GetBroadcastConnectionInfo(int hostId, out string address, out int port, out byte error) + { + NetworkTransport.GetBroadcastConnectionInfo(hostId, out address, out port, out error); + } + + public void GetBroadcastConnectionMessage(int hostId, byte[] buffer, int bufferSize, out int receivedSize, out byte error) + { + NetworkTransport.GetBroadcastConnectionMessage(hostId, buffer, bufferSize, out receivedSize, out error); + } + + public void GetConnectionInfo(int hostId, int connectionId, out string address, out int port, out NetworkID network, out NodeID dstNode, out byte error) + { + NetworkTransport.GetConnectionInfo(hostId, connectionId, out address, out port, out network, out dstNode, out error); + } + + public int GetCurrentRTT(int hostId, int connectionId, out byte error) + { + return NetworkTransport.GetCurrentRTT(hostId, connectionId, out error); + } + + public void Init() + { + NetworkTransport.Init(); + } + + public void Init(GlobalConfig config) + { + NetworkTransport.Init(config); + } + + public NetworkEventType Receive(out int hostId, out int connectionId, out int channelId, byte[] buffer, int bufferSize, out int receivedSize, out byte error) + { + return NetworkTransport.Receive(out hostId, out connectionId, out channelId, buffer, bufferSize, out receivedSize, out error); + } + + public NetworkEventType ReceiveFromHost(int hostId, out int connectionId, out int channelId, byte[] buffer, int bufferSize, out int receivedSize, out byte error) + { + return NetworkTransport.ReceiveFromHost(hostId, out connectionId, out channelId, buffer, bufferSize, out receivedSize, out error); + } + + public NetworkEventType ReceiveRelayEventFromHost(int hostId, out byte error) + { + return NetworkTransport.ReceiveRelayEventFromHost(hostId, out error); + } + + public bool RemoveHost(int hostId) + { + return NetworkTransport.RemoveHost(hostId); + } + + public bool Send(int hostId, int connectionId, int channelId, byte[] buffer, int size, out byte error) + { + return NetworkTransport.Send(hostId, connectionId, channelId, buffer, size, out error); + } + + public void SetBroadcastCredentials(int hostId, int key, int version, int subversion, out byte error) + { + NetworkTransport.SetBroadcastCredentials(hostId, key, version, subversion, out error); + } + + public void SetPacketStat(int direction, int packetStatId, int numMsgs, int numBytes) + { + NetworkTransport.SetPacketStat(direction, packetStatId, numMsgs, numBytes); + } + + public void Shutdown() + { + NetworkTransport.Shutdown(); + } + + public bool StartBroadcastDiscovery(int hostId, int broadcastPort, int key, int version, int subversion, byte[] buffer, int size, int timeout, out byte error) + { + return NetworkTransport.StartBroadcastDiscovery(hostId, broadcastPort, key, version, subversion, buffer, size, timeout, out error); + } + + public void StopBroadcastDiscovery() + { + NetworkTransport.StopBroadcastDiscovery(); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/DotNetCompatibility.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/DotNetCompatibility.cs new file mode 100644 index 00000000..afe50820 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/DotNetCompatibility.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Net.Sockets; + +namespace UnityEngine.Networking +{ + internal static class DotNetCompatibility + { + internal static string GetMethodName(this Delegate func) + { + return func.Method.Name; + } + + internal static Type GetBaseType(this Type type) + { + return type.BaseType; + } + + internal static string GetErrorCode(this SocketException e) + { + return e.ErrorCode.ToString(); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/INetworkTransport.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/INetworkTransport.cs new file mode 100644 index 00000000..46704de2 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/INetworkTransport.cs @@ -0,0 +1,65 @@ +using System; +using System.Net; + +using UnityEngine.Networking.Types; + +namespace UnityEngine.Networking +{ + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public interface INetworkTransport + { + void Init(); + + void Init(GlobalConfig config); + + bool IsStarted { get; } + + void Shutdown(); + + int AddHost(HostTopology topology, int port, string ip); + + int AddWebsocketHost(HostTopology topology, int port, string ip); + + int ConnectWithSimulator(int hostId, string address, int port, int specialConnectionId, out byte error, ConnectionSimulatorConfig conf); + + int Connect(int hostId, string address, int port, int specialConnectionId, out byte error); + + void ConnectAsNetworkHost(int hostId, string address, int port, NetworkID network, SourceID source, NodeID node, out byte error); + + int ConnectToNetworkPeer(int hostId, string address, int port, int specialConnectionId, int relaySlotId, NetworkID network, SourceID source, NodeID node, out byte error); + + int ConnectEndPoint(int hostId, EndPoint endPoint, int specialConnectionId, out byte error); + + bool DoesEndPointUsePlatformProtocols(EndPoint endPoint); + + int AddHostWithSimulator(HostTopology topology, int minTimeout, int maxTimeout, int port); + + bool RemoveHost(int hostId); + + bool Send(int hostId, int connectionId, int channelId, byte[] buffer, int size, out byte error); + + NetworkEventType Receive(out int hostId, out int connectionId, out int channelId, byte[] buffer, int bufferSize, out int receivedSize, out byte error); + + NetworkEventType ReceiveFromHost(int hostId, out int connectionId, out int channelId, byte[] buffer, int bufferSize, out int receivedSize, out byte error); + + NetworkEventType ReceiveRelayEventFromHost(int hostId, out byte error); + + int GetCurrentRTT(int hostId, int connectionId, out byte error); + + void GetConnectionInfo(int hostId, int connectionId, out string address, out int port, out NetworkID network, out NodeID dstNode, out byte error); + + bool Disconnect(int hostId, int connectionId, out byte error); + + void SetBroadcastCredentials(int hostId, int key, int version, int subversion, out byte error); + + bool StartBroadcastDiscovery(int hostId, int broadcastPort, int key, int version, int subversion, byte[] buffer, int size, int timeout, out byte error); + + void GetBroadcastConnectionInfo(int hostId, out string address, out int port, out byte error); + + void GetBroadcastConnectionMessage(int hostId, byte[] buffer, int bufferSize, out int receivedSize, out byte error); + + void StopBroadcastDiscovery(); + + void SetPacketStat(int direction, int packetStatId, int numMsgs, int numBytes); + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/LocalClient.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/LocalClient.cs new file mode 100644 index 00000000..37b2fb02 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/LocalClient.cs @@ -0,0 +1,176 @@ +#if ENABLE_UNET +using System.Collections.Generic; + +#pragma warning disable 618 +namespace UnityEngine.Networking +{ + sealed class LocalClient : NetworkClient + { + const int k_InitialFreeMessagePoolSize = 64; + + struct InternalMsg + { + internal byte[] buffer; + internal int channelId; + } + + List m_InternalMsgs = new List(); + List m_InternalMsgs2 = new List(); + Stack m_FreeMessages; + + NetworkServer m_LocalServer; + bool m_Connected; + NetworkMessage s_InternalMessage = new NetworkMessage(); + + public override void Disconnect() + { + ClientScene.HandleClientDisconnect(m_Connection); + if (m_Connected) + { + PostInternalMessage(MsgType.Disconnect); + m_Connected = false; + } + m_AsyncConnect = ConnectState.Disconnected; + m_LocalServer.RemoveLocalClient(m_Connection); + } + + internal void InternalConnectLocalServer(bool generateConnectMsg) + { + if (m_FreeMessages == null) + { + m_FreeMessages = new Stack(); + for (int i = 0; i < k_InitialFreeMessagePoolSize; i++) + { + InternalMsg msg = new InternalMsg(); + m_FreeMessages.Push(msg); + } + } + + m_LocalServer = NetworkServer.instance; + m_Connection = new ULocalConnectionToServer(m_LocalServer); + SetHandlers(m_Connection); + m_Connection.connectionId = m_LocalServer.AddLocalClient(this); + m_AsyncConnect = ConnectState.Connected; + + SetActive(true); + RegisterSystemHandlers(true); + + if (generateConnectMsg) + { + PostInternalMessage(MsgType.Connect); + } + m_Connected = true; + } + + internal override void Update() + { + ProcessInternalMessages(); + } + + // Called by the server to set the LocalClient's LocalPlayer object during NetworkServer.AddPlayer() + internal void AddLocalPlayer(PlayerController localPlayer) + { + if (LogFilter.logDev) Debug.Log("Local client AddLocalPlayer " + localPlayer.gameObject.name + " conn=" + m_Connection.connectionId); + m_Connection.isReady = true; + m_Connection.SetPlayerController(localPlayer); + var uv = localPlayer.unetView; + if (uv != null) + { + ClientScene.SetLocalObject(uv.netId, localPlayer.gameObject); + uv.SetConnectionToServer(m_Connection); + } + // there is no SystemOwnerMessage for local client. add to ClientScene here instead + ClientScene.InternalAddPlayer(uv, localPlayer.playerControllerId); + } + + private void PostInternalMessage(byte[] buffer, int channelId) + { + InternalMsg msg; + if (m_FreeMessages.Count == 0) + { + msg = new InternalMsg(); // grow forever? + } + else + { + msg = m_FreeMessages.Pop(); + } + msg.buffer = buffer; + msg.channelId = channelId; + m_InternalMsgs.Add(msg); + } + + private void PostInternalMessage(short msgType) + { + NetworkWriter writer = new NetworkWriter(); + writer.StartMessage(msgType); + writer.FinishMessage(); + + PostInternalMessage(writer.AsArray(), 0); + } + + private void ProcessInternalMessages() + { + if (m_InternalMsgs.Count == 0) + { + return; + } + + // new msgs will get put in m_InternalMsgs2 + List tmp = m_InternalMsgs; + m_InternalMsgs = m_InternalMsgs2; + + // iterate through existing set + for (int i = 0; i < tmp.Count; i++) + { + var msg = tmp[i]; + if (s_InternalMessage.reader == null) + { + s_InternalMessage.reader = new NetworkReader(msg.buffer); + } + else + { + s_InternalMessage.reader.Replace(msg.buffer); + } + s_InternalMessage.reader.ReadInt16(); //size + s_InternalMessage.channelId = msg.channelId; + s_InternalMessage.conn = connection; + s_InternalMessage.msgType = s_InternalMessage.reader.ReadInt16(); + + m_Connection.InvokeHandler(s_InternalMessage); + m_FreeMessages.Push(msg); + connection.lastMessageTime = Time.time; + } + + // put m_InternalMsgs back and clear it + m_InternalMsgs = tmp; + m_InternalMsgs.Clear(); + + // add any newly generated msgs in m_InternalMsgs2 and clear it + for (int ii = 0; ii < m_InternalMsgs2.Count; ii++) + { + m_InternalMsgs.Add(m_InternalMsgs2[ii]); + } + m_InternalMsgs2.Clear(); + } + + // called by the server, to bypass network + internal void InvokeHandlerOnClient(short msgType, MessageBase msg, int channelId) + { + // write the message to a local buffer + NetworkWriter writer = new NetworkWriter(); + writer.StartMessage(msgType); + msg.Serialize(writer); + writer.FinishMessage(); + + InvokeBytesOnClient(writer.AsArray(), channelId); + } + + // called by the server, to bypass network + internal void InvokeBytesOnClient(byte[] buffer, int channelId) + { + PostInternalMessage(buffer, channelId); + } + } +} +#pragma warning restore 618 +#endif //ENABLE_UNET diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/LocalConnections.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/LocalConnections.cs new file mode 100644 index 00000000..bedecbcf --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/LocalConnections.cs @@ -0,0 +1,128 @@ +using System; + +#if ENABLE_UNET + +#pragma warning disable 618 +namespace UnityEngine.Networking +{ + // a server's connection TO a LocalClient. + // sending messages on this connection causes the client's + // handler function to be invoked directly + class ULocalConnectionToClient : NetworkConnection + { + LocalClient m_LocalClient; + + public LocalClient localClient { get { return m_LocalClient; } } + + public ULocalConnectionToClient(LocalClient localClient) + { + address = "localClient"; + m_LocalClient = localClient; + } + + public override bool Send(short msgType, MessageBase msg) + { + m_LocalClient.InvokeHandlerOnClient(msgType, msg, Channels.DefaultReliable); + return true; + } + + public override bool SendUnreliable(short msgType, MessageBase msg) + { + m_LocalClient.InvokeHandlerOnClient(msgType, msg, Channels.DefaultUnreliable); + return true; + } + + public override bool SendByChannel(short msgType, MessageBase msg, int channelId) + { + m_LocalClient.InvokeHandlerOnClient(msgType, msg, channelId); + return true; + } + + public override bool SendBytes(byte[] bytes, int numBytes, int channelId) + { + m_LocalClient.InvokeBytesOnClient(bytes, channelId); + return true; + } + + public override bool SendWriter(NetworkWriter writer, int channelId) + { + m_LocalClient.InvokeBytesOnClient(writer.AsArray(), channelId); + return true; + } + + public override void GetStatsOut(out int numMsgs, out int numBufferedMsgs, out int numBytes, out int lastBufferedPerSecond) + { + numMsgs = 0; + numBufferedMsgs = 0; + numBytes = 0; + lastBufferedPerSecond = 0; + } + + public override void GetStatsIn(out int numMsgs, out int numBytes) + { + numMsgs = 0; + numBytes = 0; + } + } + + // a localClient's connection TO a server. + // send messages on this connection causes the server's + // handler function to be invoked directly. + + internal class ULocalConnectionToServer : NetworkConnection + { + NetworkServer m_LocalServer; + + public ULocalConnectionToServer(NetworkServer localServer) + { + address = "localServer"; + m_LocalServer = localServer; + } + + public override bool Send(short msgType, MessageBase msg) + { + return m_LocalServer.InvokeHandlerOnServer(this, msgType, msg, Channels.DefaultReliable); + } + + public override bool SendUnreliable(short msgType, MessageBase msg) + { + return m_LocalServer.InvokeHandlerOnServer(this, msgType, msg, Channels.DefaultUnreliable); + } + + public override bool SendByChannel(short msgType, MessageBase msg, int channelId) + { + return m_LocalServer.InvokeHandlerOnServer(this, msgType, msg, channelId); + } + + public override bool SendBytes(byte[] bytes, int numBytes, int channelId) + { + if (numBytes <= 0) + { + if (LogFilter.logError) { Debug.LogError("LocalConnection:SendBytes cannot send zero bytes"); } + return false; + } + return m_LocalServer.InvokeBytes(this, bytes, numBytes, channelId); + } + + public override bool SendWriter(NetworkWriter writer, int channelId) + { + return m_LocalServer.InvokeBytes(this, writer.AsArray(), (short)writer.AsArray().Length, channelId); + } + + public override void GetStatsOut(out int numMsgs, out int numBufferedMsgs, out int numBytes, out int lastBufferedPerSecond) + { + numMsgs = 0; + numBufferedMsgs = 0; + numBytes = 0; + lastBufferedPerSecond = 0; + } + + public override void GetStatsIn(out int numMsgs, out int numBytes) + { + numMsgs = 0; + numBytes = 0; + } + } +} +#pragma warning restore 618 +#endif //ENABLE_UNET diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/LogFilter.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/LogFilter.cs new file mode 100644 index 00000000..dad91daa --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/LogFilter.cs @@ -0,0 +1,72 @@ +using System; + +namespace UnityEngine.Networking +{ + /// + /// FilterLog is a utility class that controls the level of logging generated by UNET clients and servers. + /// + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class LogFilter + { + // this only exists for inspector UI?! + public enum FilterLevel + { + Developer = 0, + Debug = 1, + Info = 2, + Warn = 3, + Error = 4, + Fatal = 5, + SetInScripting = -1 + }; + + internal const int Developer = 0; + internal const int SetInScripting = -1; + + /// + /// Setting LogFilter.currentLogLevel to this will enable verbose debug logging. + /// + public const int Debug = 1; + /// + /// Setting LogFilter.currentLogLevel to this will log only info and above messages. This is the default level. + /// + public const int Info = 2; + /// + /// Setting LogFilter.currentLogLevel to this will log wanring and above messages. + /// + public const int Warn = 3; + /// + /// Setting LogFilter.currentLogLevel to this will error and above messages. + /// + public const int Error = 4; + public const int Fatal = 5; + + [Obsolete("Use LogFilter.currentLogLevel instead")] + static public FilterLevel current = FilterLevel.Info; + + static int s_CurrentLogLevel = Info; + /// + /// The current logging level that UNET is running with. + /// + static public int currentLogLevel { get { return s_CurrentLogLevel; } set { s_CurrentLogLevel = value; } } + + static internal bool logDev { get { return s_CurrentLogLevel <= Developer; } } + /// + /// Checks if debug logging is enabled. + /// + static public bool logDebug { get { return s_CurrentLogLevel <= Debug; } } + /// + /// Checks if info level logging is enabled. + /// + static public bool logInfo { get { return s_CurrentLogLevel <= Info; } } + /// + /// Checks if wanring level logging is enabled. + /// + static public bool logWarn { get { return s_CurrentLogLevel <= Warn; } } + /// + /// Checks if error logging is enabled. + /// + static public bool logError { get { return s_CurrentLogLevel <= Error; } } + static public bool logFatal { get { return s_CurrentLogLevel <= Fatal; } } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/Messages.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/Messages.cs new file mode 100644 index 00000000..7029ac71 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/Messages.cs @@ -0,0 +1,816 @@ +using System; +using System.Collections.Generic; + +#pragma warning disable 618 +namespace UnityEngine.Networking +{ + /// + /// Network message classes should be derived from this class. These message classes can then be sent using the various Send functions of NetworkConnection, NetworkClient and NetworkServer. + /// Public data fields of classes derived from MessageBase will be automatically serialized with the class. The virtual methods Serialize and Deserialize may be implemented by developers for precise control, but if they are not implemented, then implementations will be generated for them. + /// Note : Unity uses its own network serialization system. It doesn't support the NonSerialized attribute. Instead, use private variables. + /// In the example below, the methods have implementations, but if those methods were not implemented, the message would still be usable. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// class SpawnMessage : MessageBase + /// { + /// public uint netId; + /// public NetworkHash128 assetId; + /// public Vector3 position; + /// public byte[] payload; + /// + /// // This method would be generated + /// public override void Deserialize(NetworkReader reader) + /// { + /// netId = reader.ReadPackedUInt32(); + /// assetId = reader.ReadNetworkHash128(); + /// position = reader.ReadVector3(); + /// payload = reader.ReadBytesAndSize(); + /// } + /// + /// // This method would be generated + /// public override void Serialize(NetworkWriter writer) + /// { + /// writer.WritePackedUInt32(netId); + /// writer.Write(assetId); + /// writer.Write(position); + /// writer.WriteBytesFull(payload); + /// } + /// } + /// + /// + // This can't be an interface because users don't need to implement the + // serialization functions, we'll code generate it for them when they omit it. + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public abstract class MessageBase + { + /// + /// This method is used to populate a message object from a NetworkReader stream. + /// Developers may implement this method for precise control of serialization, but they do no have to. An implemenation of this method will be generated for derived classes. + /// + /// Stream to read from. + // De-serialize the contents of the reader into this message + public virtual void Deserialize(NetworkReader reader) {} + + /// + /// The method is used to populate a NetworkWriter stream from a message object. + /// Developers may implement this method for precise control of serialization, but they do no have to. An implemenation of this method will be generated for derived classes. + /// + /// Stream to write to. + // Serialize the contents of this message into the writer + public virtual void Serialize(NetworkWriter writer) {} + } +} + +namespace UnityEngine.Networking.NetworkSystem +{ + // ---------- General Typed Messages ------------------- + /// + /// This is a utility class for simple network messages that contain only a string. + /// This example sends a message with the name of the scene. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// using UnityEngine.Networking.NetworkSystem; + /// + /// public class Test + /// { + /// void SendSceneName(string sceneName) + /// { + /// var msg = new StringMessage(sceneName); + /// NetworkServer.SendToAll(MsgType.Scene, msg); + /// } + /// } + /// + /// + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class StringMessage : MessageBase + { + /// + /// The string that will be serialized. + /// + public string value; + + public StringMessage() + { + } + + public StringMessage(string v) + { + value = v; + } + + public override void Deserialize(NetworkReader reader) + { + value = reader.ReadString(); + } + + public override void Serialize(NetworkWriter writer) + { + writer.Write(value); + } + } + + /// + /// A utility class to send simple network messages that only contain an integer. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// using UnityEngine.Networking.NetworkSystem; + /// + /// public class Test + /// { + /// void SendValue(int value) + /// { + /// var msg = new IntegerMessage(value); + /// NetworkServer.SendToAll(MsgType.Scene, msg); + /// } + /// } + /// + /// + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class IntegerMessage : MessageBase + { + /// + /// The integer value to serialize. + /// + public int value; + + public IntegerMessage() + { + } + + public IntegerMessage(int v) + { + value = v; + } + + public override void Deserialize(NetworkReader reader) + { + value = (int)reader.ReadPackedUInt32(); + } + + public override void Serialize(NetworkWriter writer) + { + writer.WritePackedUInt32((uint)value); + } + } + + /// + /// A utility class to send a network message with no contents. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// using UnityEngine.Networking.NetworkSystem; + /// + /// public class Test + /// { + /// void SendNotification() + /// { + /// var msg = new EmptyMessage(); + /// NetworkServer.SendToAll(667, msg); + /// } + /// } + /// + /// + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class EmptyMessage : MessageBase + { + public override void Deserialize(NetworkReader reader) + { + } + + public override void Serialize(NetworkWriter writer) + { + } + } + + // ---------- Public System Messages ------------------- + /// + /// This is passed to handler functions registered for the SYSTEM_ERROR built-in message. + /// + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class ErrorMessage : MessageBase + { + /// + /// The error code. + /// This is a value from the UNETError enumeration. + /// + public int errorCode; + + public override void Deserialize(NetworkReader reader) + { + errorCode = reader.ReadUInt16(); + } + + public override void Serialize(NetworkWriter writer) + { + writer.Write((ushort)errorCode); + } + } + + /// + /// This is passed to handler funtions registered for the SYSTEM_READY built-in message. + /// + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class ReadyMessage : EmptyMessage + { + } + + /// + /// This is passed to handler funtions registered for the SYSTEM_NOT_READY built-in message. + /// + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class NotReadyMessage : EmptyMessage + { + } + + /// + /// This is passed to handler funtions registered for the AddPlayer built-in message. + /// + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class AddPlayerMessage : MessageBase + { + /// + /// The playerId of the new player. + /// This is specified by the client when they call NetworkClient.AddPlayer(someId). + /// The HLAPI treats players and clients as separate GameObjects. In most cases, there is a single player for each client, but in some situations (for example, when there are multiple controllers connected to a console system) there might be multiple player GameObjects for a single connection. When there are multiple players for a single connection, use the playerControllerId property to tell them apart. This is an identifier that is scoped to the connection, so that it maps to the id of the controller associated with the player on that client. + /// + public short playerControllerId; + /// + /// The size of the extra message data included in the AddPlayerMessage. + /// + public int msgSize; + /// + /// The extra message data included in the AddPlayerMessage. + /// + public byte[] msgData; + + public override void Deserialize(NetworkReader reader) + { + playerControllerId = (short)reader.ReadUInt16(); + msgData = reader.ReadBytesAndSize(); + if (msgData == null) + { + msgSize = 0; + } + else + { + msgSize = msgData.Length; + } + } + + public override void Serialize(NetworkWriter writer) + { + writer.Write((ushort)playerControllerId); + writer.WriteBytesAndSize(msgData, msgSize); + } + } + + /// + /// This is passed to handler funtions registered for the SYSTEM_REMOVE_PLAYER built-in message. + /// + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class RemovePlayerMessage : MessageBase + { + /// + /// The player ID of the player GameObject which should be removed. + /// This is specified by the client when they call NetworkClient.RemovePlayer(someId). + /// The HLAPI treats players and clients as separate GameObjects. In most cases, there is a single player for each client, but in some situations (for example, when there are multiple controllers connected to a console system) there might be multiple player GameObjects for a single connection. When there are multiple players for a single connection, use the playerControllerId property to tell them apart. This is an identifier that is scoped to the connection, so that it maps to the id of the controller associated with the player on that client. + /// + public short playerControllerId; + + public override void Deserialize(NetworkReader reader) + { + playerControllerId = (short)reader.ReadUInt16(); + } + + public override void Serialize(NetworkWriter writer) + { + writer.Write((ushort)playerControllerId); + } + } + + /// + /// Information about a change in authority of a non-player in the same network game. + /// This information is cached by clients and used during host-migration. + /// + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class PeerAuthorityMessage : MessageBase + { + /// + /// The connection Id (on the server) of the peer whose authority is changing for the object. + /// + public int connectionId; + /// + /// The network id of the object whose authority state changed. + /// + public NetworkInstanceId netId; + /// + /// The new state of authority for the object referenced by this message. + /// + public bool authorityState; + + public override void Deserialize(NetworkReader reader) + { + connectionId = (int)reader.ReadPackedUInt32(); + netId = reader.ReadNetworkId(); + authorityState = reader.ReadBoolean(); + } + + public override void Serialize(NetworkWriter writer) + { + writer.WritePackedUInt32((uint)connectionId); + writer.Write(netId); + writer.Write(authorityState); + } + } + + /// + /// A structure used to identify player object on other peers for host migration. + /// + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public struct PeerInfoPlayer + { + /// + /// The networkId of the player object. + /// + public NetworkInstanceId netId; + /// + /// The playerControllerId of the player GameObject. + /// The HLAPI treats players and clients as separate GameObjects. In most cases, there is a single player for each client, but in some situations (for example, when there are multiple controllers connected to a console system) there might be multiple player GameObjects for a single connection. When there are multiple players for a single connection, use the playerControllerId property to tell them apart. This is an identifier that is scoped to the connection, so that it maps to the id of the controller associated with the player on that client. + /// + public short playerControllerId; + } + + /// + /// Information about another participant in the same network game. + /// This information is cached by clients and used during host-migration. + /// + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class PeerInfoMessage : MessageBase + { + /// + /// The id of the NetworkConnection associated with the peer. + /// + public int connectionId; + /// + /// The IP address of the peer. + /// + public string address; + /// + /// The network port being used by the peer. + /// + public int port; + /// + /// True if this peer is the host of the network game. + /// + public bool isHost; + /// + /// True if the peer if the same as the current client. + /// + public bool isYou; + /// + /// The players for this peer. + /// + public PeerInfoPlayer[] playerIds; + + public override void Deserialize(NetworkReader reader) + { + connectionId = (int)reader.ReadPackedUInt32(); + address = reader.ReadString(); + port = (int)reader.ReadPackedUInt32(); + isHost = reader.ReadBoolean(); + isYou = reader.ReadBoolean(); + + uint numPlayers = reader.ReadPackedUInt32(); + if (numPlayers > 0) + { + List ids = new List(); + for (uint i = 0; i < numPlayers; i++) + { + PeerInfoPlayer info; + info.netId = reader.ReadNetworkId(); + info.playerControllerId = (short)reader.ReadPackedUInt32(); + ids.Add(info); + } + playerIds = ids.ToArray(); + } + } + + public override void Serialize(NetworkWriter writer) + { + writer.WritePackedUInt32((uint)connectionId); + writer.Write(address); + writer.WritePackedUInt32((uint)port); + writer.Write(isHost); + writer.Write(isYou); + if (playerIds == null) + { + writer.WritePackedUInt32(0); + } + else + { + writer.WritePackedUInt32((uint)playerIds.Length); + for (int i = 0; i < playerIds.Length; i++) + { + writer.Write(playerIds[i].netId); + writer.WritePackedUInt32((uint)playerIds[i].playerControllerId); + } + } + } + + public override string ToString() + { + return "PeerInfo conn:" + connectionId + " addr:" + address + ":" + port + " host:" + isHost + " isYou:" + isYou; + } + } + + /// + /// Internal UNET message for sending information about network peers to clients. + /// + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class PeerListMessage : MessageBase + { + /// + /// The list of participants in a networked game. + /// + public PeerInfoMessage[] peers; + /// + /// The connectionId of this client on the old host. + /// + public int oldServerConnectionId; + + public override void Deserialize(NetworkReader reader) + { + oldServerConnectionId = (int)reader.ReadPackedUInt32(); + int numPeers = reader.ReadUInt16(); + peers = new PeerInfoMessage[numPeers]; + for (int i = 0; i < peers.Length; ++i) + { + var peerInfo = new PeerInfoMessage(); + peerInfo.Deserialize(reader); + peers[i] = peerInfo; + } + } + + public override void Serialize(NetworkWriter writer) + { + writer.WritePackedUInt32((uint)oldServerConnectionId); + writer.Write((ushort)peers.Length); + for (int i = 0; i < peers.Length; i++) + { + peers[i].Serialize(writer); + } + } + } + + /// + /// This network message is used when a client reconnect to the new host of a game. + /// + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class ReconnectMessage : MessageBase + { + /// + /// This client's connectionId on the old host. + /// + public int oldConnectionId; + /// + /// The playerControllerId of the player that is rejoining. + /// The HLAPI treats players and clients as separate GameObjects. In most cases, there is a single player for each client, but in some situations (for example, when there are multiple controllers connected to a console system) there might be multiple player GameObjects for a single connection. When there are multiple players for a single connection, use the playerControllerId property to tell them apart. This is an identifier that is scoped to the connection, so that it maps to the id of the controller associated with the player on that client. + /// + public short playerControllerId; + /// + /// The networkId of this player on the old host. + /// + public NetworkInstanceId netId; + /// + /// Size of additional data. + /// + public int msgSize; + /// + /// Additional data. + /// + public byte[] msgData; + + public override void Deserialize(NetworkReader reader) + { + oldConnectionId = (int)reader.ReadPackedUInt32(); + playerControllerId = (short)reader.ReadPackedUInt32(); + netId = reader.ReadNetworkId(); + msgData = reader.ReadBytesAndSize(); + msgSize = msgData.Length; + } + + public override void Serialize(NetworkWriter writer) + { + writer.WritePackedUInt32((uint)oldConnectionId); + writer.WritePackedUInt32((uint)playerControllerId); + writer.Write(netId); + writer.WriteBytesAndSize(msgData, msgSize); + } + } + + // ---------- System Messages requried for code gen path ------------------- + /* These are not used directly but manually serialized, these are here for reference. + + public struct CommandMessage + { + public int cmdHash; + public string cmdName; + public byte[] payload; + } + public struct RPCMessage + { + public NetworkId netId; + public int cmdHash; + public byte[] payload; + } + public struct SyncEventMessage + { + public NetworkId netId; + public int cmdHash; + public byte[] payload; + } + + internal class SyncListMessage where T: struct + { + public NetworkId netId; + public int cmdHash; + public byte operation; + public int itemIndex; + public T item; + } + +*/ + + // ---------- Internal System Messages ------------------- + class ObjectSpawnMessage : MessageBase + { + public NetworkInstanceId netId; + public NetworkHash128 assetId; + public Vector3 position; + public byte[] payload; + public Quaternion rotation; + + public override void Deserialize(NetworkReader reader) + { + netId = reader.ReadNetworkId(); + assetId = reader.ReadNetworkHash128(); + position = reader.ReadVector3(); + payload = reader.ReadBytesAndSize(); + + uint extraPayloadSize = sizeof(uint) * 4; + if ((reader.Length - reader.Position) >= extraPayloadSize) + { + rotation = reader.ReadQuaternion(); + } + } + + public override void Serialize(NetworkWriter writer) + { + writer.Write(netId); + writer.Write(assetId); + writer.Write(position); + writer.WriteBytesFull(payload); + + writer.Write(rotation); + } + } + + class ObjectSpawnSceneMessage : MessageBase + { + public NetworkInstanceId netId; + public NetworkSceneId sceneId; + public Vector3 position; + public byte[] payload; + + public override void Deserialize(NetworkReader reader) + { + netId = reader.ReadNetworkId(); + sceneId = reader.ReadSceneId(); + position = reader.ReadVector3(); + payload = reader.ReadBytesAndSize(); + } + + public override void Serialize(NetworkWriter writer) + { + writer.Write(netId); + writer.Write(sceneId); + writer.Write(position); + writer.WriteBytesFull(payload); + } + } + + class ObjectSpawnFinishedMessage : MessageBase + { + public uint state; + + public override void Deserialize(NetworkReader reader) + { + state = reader.ReadPackedUInt32(); + } + + public override void Serialize(NetworkWriter writer) + { + writer.WritePackedUInt32(state); + } + } + + class ObjectDestroyMessage : MessageBase + { + public NetworkInstanceId netId; + + public override void Deserialize(NetworkReader reader) + { + netId = reader.ReadNetworkId(); + } + + public override void Serialize(NetworkWriter writer) + { + writer.Write(netId); + } + } + + class OwnerMessage : MessageBase + { + public NetworkInstanceId netId; + public short playerControllerId; + + public override void Deserialize(NetworkReader reader) + { + netId = reader.ReadNetworkId(); + playerControllerId = (short)reader.ReadPackedUInt32(); + } + + public override void Serialize(NetworkWriter writer) + { + writer.Write(netId); + writer.WritePackedUInt32((uint)playerControllerId); + } + } + + class ClientAuthorityMessage : MessageBase + { + public NetworkInstanceId netId; + public bool authority; + + public override void Deserialize(NetworkReader reader) + { + netId = reader.ReadNetworkId(); + authority = reader.ReadBoolean(); + } + + public override void Serialize(NetworkWriter writer) + { + writer.Write(netId); + writer.Write(authority); + } + } + + class OverrideTransformMessage : MessageBase + { + public NetworkInstanceId netId; + public byte[] payload; + public bool teleport; + public int time; + + public override void Deserialize(NetworkReader reader) + { + netId = reader.ReadNetworkId(); + payload = reader.ReadBytesAndSize(); + teleport = reader.ReadBoolean(); + time = (int)reader.ReadPackedUInt32(); + } + + public override void Serialize(NetworkWriter writer) + { + writer.Write(netId); + writer.WriteBytesFull(payload); + writer.Write(teleport); + writer.WritePackedUInt32((uint)time); + } + } + + class AnimationMessage : MessageBase + { + public NetworkInstanceId netId; + public int stateHash; // if non-zero, then Play() this animation, skipping transitions + public float normalizedTime; + public byte[] parameters; + + public override void Deserialize(NetworkReader reader) + { + netId = reader.ReadNetworkId(); + stateHash = (int)reader.ReadPackedUInt32(); + normalizedTime = reader.ReadSingle(); + parameters = reader.ReadBytesAndSize(); + } + + public override void Serialize(NetworkWriter writer) + { + writer.Write(netId); + writer.WritePackedUInt32((uint)stateHash); + writer.Write(normalizedTime); + + if (parameters == null) + writer.WriteBytesAndSize(parameters, 0); + else + writer.WriteBytesAndSize(parameters, parameters.Length); + } + } + + class AnimationParametersMessage : MessageBase + { + public NetworkInstanceId netId; + public byte[] parameters; + + public override void Deserialize(NetworkReader reader) + { + netId = reader.ReadNetworkId(); + parameters = reader.ReadBytesAndSize(); + } + + public override void Serialize(NetworkWriter writer) + { + writer.Write(netId); + + if (parameters == null) + writer.WriteBytesAndSize(parameters, 0); + else + writer.WriteBytesAndSize(parameters, parameters.Length); + } + } + + class AnimationTriggerMessage : MessageBase + { + public NetworkInstanceId netId; + public int hash; + + public override void Deserialize(NetworkReader reader) + { + netId = reader.ReadNetworkId(); + hash = (int)reader.ReadPackedUInt32(); + } + + public override void Serialize(NetworkWriter writer) + { + writer.Write(netId); + writer.WritePackedUInt32((uint)hash); + } + } + + class LobbyReadyToBeginMessage : MessageBase + { + public byte slotId; + public bool readyState; + + public override void Deserialize(NetworkReader reader) + { + slotId = reader.ReadByte(); + readyState = reader.ReadBoolean(); + } + + public override void Serialize(NetworkWriter writer) + { + writer.Write(slotId); + writer.Write(readyState); + } + } + + struct CRCMessageEntry + { + public string name; + public byte channel; + } + + class CRCMessage : MessageBase + { + public CRCMessageEntry[] scripts; + + public override void Deserialize(NetworkReader reader) + { + int numScripts = reader.ReadUInt16(); + scripts = new CRCMessageEntry[numScripts]; + for (int i = 0; i < scripts.Length; ++i) + { + var entry = new CRCMessageEntry(); + entry.name = reader.ReadString(); + entry.channel = reader.ReadByte(); + scripts[i] = entry; + } + } + + public override void Serialize(NetworkWriter writer) + { + writer.Write((ushort)scripts.Length); + for (int i = 0; i < scripts.Length; i++) + { + writer.Write(scripts[i].name); + writer.Write(scripts[i].channel); + } + } + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkAnimator.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkAnimator.cs new file mode 100644 index 00000000..68dacd3f --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkAnimator.cs @@ -0,0 +1,512 @@ +using System; +using UnityEngine; +using UnityEngine.Networking.NetworkSystem; + +namespace UnityEngine.Networking +{ + /// + /// A component to synchronize Mecanim animation states for networked objects. + /// The animation of game objects can be networked by this component. There are two models of authority for networked movement: + /// If the object has authority on the client, then it should animated locally on the owning client. The animation state information will be sent from the owning client to the server, then broadcast to all of the other clients. This is common for player objects. + /// If the object has authority on the server, then it should be animated on the server and state information will be sent to all clients. This is common for objects not related to a specific client, such as an enemy unit. + /// The NetworkAnimator synchronizes the animation parameters that are checked in the inspector view. It does not automatically sychronize triggers. The function SetTrigger can by used by an object with authority to fire an animation trigger on other clients. + /// + [DisallowMultipleComponent] + [AddComponentMenu("Network/NetworkAnimator")] + [RequireComponent(typeof(NetworkIdentity))] + [RequireComponent(typeof(Animator))] + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class NetworkAnimator : NetworkBehaviour + { + // configuration + [SerializeField] Animator m_Animator; + [SerializeField] uint m_ParameterSendBits; + + // static message objects to avoid runtime-allocations + static AnimationMessage s_AnimationMessage = new AnimationMessage(); + static AnimationParametersMessage s_AnimationParametersMessage = new AnimationParametersMessage(); + static AnimationTriggerMessage s_AnimationTriggerMessage = new AnimationTriggerMessage(); + + /// + /// The animator component to synchronize. + /// + // properties + public Animator animator + { + get { return m_Animator; } + set + { + m_Animator = value; + ResetParameterOptions(); + } + } + + /// + /// Sets whether an animation parameter should be auto sent. + /// + /// Index of the parameter in the Animator. + /// The new value. + public void SetParameterAutoSend(int index, bool value) + { + if (value) + { + m_ParameterSendBits |= (uint)(1 << index); + } + else + { + m_ParameterSendBits &= (uint)(~(1 << index)); + } + } + + /// + /// Gets whether an animation parameter should be auto sent. + /// + /// Index of the parameter in the Animator. + /// True if the parameter should be sent. + public bool GetParameterAutoSend(int index) + { + return (m_ParameterSendBits & (uint)(1 << index)) != 0; + } + + int m_AnimationHash; + int m_TransitionHash; + NetworkWriter m_ParameterWriter; + float m_SendTimer; + + // tracking - these should probably move to a Preview component. + public string param0; + public string param1; + public string param2; + public string param3; + public string param4; + public string param5; + + bool sendMessagesAllowed + { + get + { + if (isServer) + { + if (!localPlayerAuthority) + return true; + + // This is a special case where we have localPlayerAuthority set + // on a NetworkIdentity but we have not assigned the client who has + // authority over it, no animator data will be sent over the network by the server. + // + // So we check here for a clientAuthorityOwner and if it is null we will + // let the server send animation data until we receive an owner. + if (netIdentity != null && netIdentity.clientAuthorityOwner == null) + return true; + } + + if (hasAuthority) + return true; + + return false; + } + } + + internal void ResetParameterOptions() + { + Debug.Log("ResetParameterOptions"); + m_ParameterSendBits = 0; + } + + void FixedUpdate() + { + if (!sendMessagesAllowed) + return; + + if (m_ParameterWriter == null) + m_ParameterWriter = new NetworkWriter(); + + CheckSendRate(); + + int stateHash; + float normalizedTime; + if (!CheckAnimStateChanged(out stateHash, out normalizedTime)) + { + return; + } + + var animMsg = new AnimationMessage(); + animMsg.netId = netId; + animMsg.stateHash = stateHash; + animMsg.normalizedTime = normalizedTime; + + m_ParameterWriter.SeekZero(); + WriteParameters(m_ParameterWriter, false); + animMsg.parameters = m_ParameterWriter.ToArray(); + + SendMessage(MsgType.Animation, animMsg); + } + + bool CheckAnimStateChanged(out int stateHash, out float normalizedTime) + { + stateHash = 0; + normalizedTime = 0; + + if (m_Animator.IsInTransition(0)) + { + AnimatorTransitionInfo tt = m_Animator.GetAnimatorTransitionInfo(0); + if (tt.fullPathHash != m_TransitionHash) + { + // first time in this transition + m_TransitionHash = tt.fullPathHash; + m_AnimationHash = 0; + return true; + } + return false; + } + + AnimatorStateInfo st = m_Animator.GetCurrentAnimatorStateInfo(0); + if (st.fullPathHash != m_AnimationHash) + { + // first time in this animation state + if (m_AnimationHash != 0) + { + // came from another animation directly - from Play() + stateHash = st.fullPathHash; + normalizedTime = st.normalizedTime; + } + m_TransitionHash = 0; + m_AnimationHash = st.fullPathHash; + return true; + } + return false; + } + + void CheckSendRate() + { + if (sendMessagesAllowed && GetNetworkSendInterval() != 0 && m_SendTimer < Time.time) + { + m_SendTimer = Time.time + GetNetworkSendInterval(); + + var animMsg = new AnimationParametersMessage(); + animMsg.netId = netId; + + m_ParameterWriter.SeekZero(); + WriteParameters(m_ParameterWriter, true); + animMsg.parameters = m_ParameterWriter.ToArray(); + + SendMessage(MsgType.AnimationParameters, animMsg); + } + } + + void SendMessage(short type, MessageBase msg) + { + if (isServer) + { + NetworkServer.SendToReady(gameObject, type, msg); + } + else + { + if (ClientScene.readyConnection != null) + { + ClientScene.readyConnection.Send(type, msg); + } + } + } + + void SetSendTrackingParam(string p, int i) + { + p = "Sent Param: " + p; + if (i == 0) param0 = p; + if (i == 1) param1 = p; + if (i == 2) param2 = p; + if (i == 3) param3 = p; + if (i == 4) param4 = p; + if (i == 5) param5 = p; + } + + void SetRecvTrackingParam(string p, int i) + { + p = "Recv Param: " + p; + if (i == 0) param0 = p; + if (i == 1) param1 = p; + if (i == 2) param2 = p; + if (i == 3) param3 = p; + if (i == 4) param4 = p; + if (i == 5) param5 = p; + } + + internal void HandleAnimMsg(AnimationMessage msg, NetworkReader reader) + { + if (hasAuthority) + return; + + // usually transitions will be triggered by parameters, if not, play anims directly. + // NOTE: this plays "animations", not transitions, so any transitions will be skipped. + // NOTE: there is no API to play a transition(?) + if (msg.stateHash != 0) + { + m_Animator.Play(msg.stateHash, 0, msg.normalizedTime); + } + + ReadParameters(reader, false); + } + + internal void HandleAnimParamsMsg(AnimationParametersMessage msg, NetworkReader reader) + { + if (hasAuthority) + return; + + ReadParameters(reader, true); + } + + internal void HandleAnimTriggerMsg(int hash) + { + m_Animator.SetTrigger(hash); + } + + void WriteParameters(NetworkWriter writer, bool autoSend) + { + for (int i = 0; i < m_Animator.parameters.Length; i++) + { + if (autoSend && !GetParameterAutoSend(i)) + continue; + + AnimatorControllerParameter par = m_Animator.parameters[i]; + if (par.type == AnimatorControllerParameterType.Int) + { + writer.WritePackedUInt32((uint)m_Animator.GetInteger(par.nameHash)); + + SetSendTrackingParam(par.name + ":" + m_Animator.GetInteger(par.nameHash), i); + } + + if (par.type == AnimatorControllerParameterType.Float) + { + writer.Write(m_Animator.GetFloat(par.nameHash)); + + SetSendTrackingParam(par.name + ":" + m_Animator.GetFloat(par.nameHash), i); + } + + if (par.type == AnimatorControllerParameterType.Bool) + { + writer.Write(m_Animator.GetBool(par.nameHash)); + + SetSendTrackingParam(par.name + ":" + m_Animator.GetBool(par.nameHash), i); + } + } + } + + void ReadParameters(NetworkReader reader, bool autoSend) + { + for (int i = 0; i < m_Animator.parameters.Length; i++) + { + if (autoSend && !GetParameterAutoSend(i)) + continue; + + AnimatorControllerParameter par = m_Animator.parameters[i]; + if (par.type == AnimatorControllerParameterType.Int) + { + int newValue = (int)reader.ReadPackedUInt32(); + m_Animator.SetInteger(par.nameHash, newValue); + + SetRecvTrackingParam(par.name + ":" + newValue, i); + } + + if (par.type == AnimatorControllerParameterType.Float) + { + float newFloatValue = reader.ReadSingle(); + m_Animator.SetFloat(par.nameHash, newFloatValue); + + SetRecvTrackingParam(par.name + ":" + newFloatValue, i); + } + + if (par.type == AnimatorControllerParameterType.Bool) + { + bool newBoolValue = reader.ReadBoolean(); + m_Animator.SetBool(par.nameHash, newBoolValue); + + SetRecvTrackingParam(par.name + ":" + newBoolValue, i); + } + } + } + + public override bool OnSerialize(NetworkWriter writer, bool forceAll) + { + if (forceAll) + { + if (m_Animator.IsInTransition(0)) + { + AnimatorStateInfo st = m_Animator.GetNextAnimatorStateInfo(0); + writer.Write(st.fullPathHash); + writer.Write(st.normalizedTime); + } + else + { + AnimatorStateInfo st = m_Animator.GetCurrentAnimatorStateInfo(0); + writer.Write(st.fullPathHash); + writer.Write(st.normalizedTime); + } + WriteParameters(writer, false); + return true; + } + return false; + } + + public override void OnDeserialize(NetworkReader reader, bool initialState) + { + if (initialState) + { + int stateHash = reader.ReadInt32(); + float normalizedTime = reader.ReadSingle(); + ReadParameters(reader, false); + m_Animator.Play(stateHash, 0, normalizedTime); + } + } + + /// + /// Causes an animation trigger to be invoked for a networked object. + /// If local authority is set, and this is called from the client, then the trigger will be invoked on the server and all clients. If not, then this is called on the server, and the trigger will be called on all clients. + /// + /// Name of trigger. + public void SetTrigger(string triggerName) + { + SetTrigger(Animator.StringToHash(triggerName)); + } + + /// + /// + /// + /// Hash id of trigger (from the Animator). + public void SetTrigger(int hash) + { + var animMsg = new AnimationTriggerMessage(); + animMsg.netId = netId; + animMsg.hash = hash; + + if (hasAuthority && localPlayerAuthority) + { + if (NetworkClient.allClients.Count > 0) + { + var client = ClientScene.readyConnection; + if (client != null) + { + client.Send(MsgType.AnimationTrigger, animMsg); + } + } + return; + } + + if (isServer && !localPlayerAuthority) + { + NetworkServer.SendToReady(gameObject, MsgType.AnimationTrigger, animMsg); + } + } + + // ------------------ server message handlers ------------------- + + static internal void OnAnimationServerMessage(NetworkMessage netMsg) + { + netMsg.ReadMessage(s_AnimationMessage); + + if (LogFilter.logDev) { Debug.Log("OnAnimationMessage for netId=" + s_AnimationMessage.netId + " conn=" + netMsg.conn); } + + GameObject go = NetworkServer.FindLocalObject(s_AnimationMessage.netId); + if (go == null) + { + return; + } + NetworkAnimator animSync = go.GetComponent(); + if (animSync != null) + { + NetworkReader reader = new NetworkReader(s_AnimationMessage.parameters); + animSync.HandleAnimMsg(s_AnimationMessage, reader); + + NetworkServer.SendToReady(go, MsgType.Animation, s_AnimationMessage); + } + } + + static internal void OnAnimationParametersServerMessage(NetworkMessage netMsg) + { + netMsg.ReadMessage(s_AnimationParametersMessage); + + if (LogFilter.logDev) { Debug.Log("OnAnimationParametersMessage for netId=" + s_AnimationParametersMessage.netId + " conn=" + netMsg.conn); } + + GameObject go = NetworkServer.FindLocalObject(s_AnimationParametersMessage.netId); + if (go == null) + { + return; + } + NetworkAnimator animSync = go.GetComponent(); + if (animSync != null) + { + NetworkReader reader = new NetworkReader(s_AnimationParametersMessage.parameters); + animSync.HandleAnimParamsMsg(s_AnimationParametersMessage, reader); + NetworkServer.SendToReady(go, MsgType.AnimationParameters, s_AnimationParametersMessage); + } + } + + static internal void OnAnimationTriggerServerMessage(NetworkMessage netMsg) + { + netMsg.ReadMessage(s_AnimationTriggerMessage); + + if (LogFilter.logDev) { Debug.Log("OnAnimationTriggerMessage for netId=" + s_AnimationTriggerMessage.netId + " conn=" + netMsg.conn); } + + GameObject go = NetworkServer.FindLocalObject(s_AnimationTriggerMessage.netId); + if (go == null) + { + return; + } + NetworkAnimator animSync = go.GetComponent(); + if (animSync != null) + { + animSync.HandleAnimTriggerMsg(s_AnimationTriggerMessage.hash); + + NetworkServer.SendToReady(go, MsgType.AnimationTrigger, s_AnimationTriggerMessage); + } + } + + // ------------------ client message handlers ------------------- + + static internal void OnAnimationClientMessage(NetworkMessage netMsg) + { + netMsg.ReadMessage(s_AnimationMessage); + GameObject go = ClientScene.FindLocalObject(s_AnimationMessage.netId); + if (go == null) + { + return; + } + var animSync = go.GetComponent(); + if (animSync != null) + { + var reader = new NetworkReader(s_AnimationMessage.parameters); + animSync.HandleAnimMsg(s_AnimationMessage, reader); + } + } + + static internal void OnAnimationParametersClientMessage(NetworkMessage netMsg) + { + netMsg.ReadMessage(s_AnimationParametersMessage); + GameObject go = ClientScene.FindLocalObject(s_AnimationParametersMessage.netId); + if (go == null) + { + return; + } + var animSync = go.GetComponent(); + if (animSync != null) + { + var reader = new NetworkReader(s_AnimationParametersMessage.parameters); + animSync.HandleAnimParamsMsg(s_AnimationParametersMessage, reader); + } + } + + static internal void OnAnimationTriggerClientMessage(NetworkMessage netMsg) + { + netMsg.ReadMessage(s_AnimationTriggerMessage); + GameObject go = ClientScene.FindLocalObject(s_AnimationTriggerMessage.netId); + if (go == null) + { + return; + } + var animSync = go.GetComponent(); + if (animSync != null) + { + animSync.HandleAnimTriggerMsg(s_AnimationTriggerMessage.hash); + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkBehaviour.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkBehaviour.cs new file mode 100644 index 00000000..25997366 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkBehaviour.cs @@ -0,0 +1,884 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; + +namespace UnityEngine.Networking +{ + /// + /// Base class which should be inherited by scripts which contain networking functionality. + /// This is a MonoBehaviour class so scripts which need to use the networking feature should inherit this class instead of MonoBehaviour. It allows you to invoke networked actions, receive various callbacks, and automatically synchronize state from server-to-client. + /// The NetworkBehaviour component requires a NetworkIdentity on the game object. There can be multiple NetworkBehaviours on a single game object. For an object with sub-components in a hierarchy, the NetworkIdentity must be on the root object, and NetworkBehaviour scripts must also be on the root object. + /// Some of the built-in components of the networking system are derived from NetworkBehaviour, including NetworkTransport, NetworkAnimator and NetworkProximityChecker. + /// + [RequireComponent(typeof(NetworkIdentity))] + [AddComponentMenu("")] + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class NetworkBehaviour : MonoBehaviour + { + uint m_SyncVarDirtyBits; + float m_LastSendTime; + + // this prevents recursion when SyncVar hook functions are called. + bool m_SyncVarGuard; + + /// + /// This value is set on the NetworkIdentity and is accessible here for convenient access for scripts. + /// + public bool localPlayerAuthority { get { return myView.localPlayerAuthority; } } + /// + /// Returns true if this object is active on an active server. + /// This is only true if the object has been spawned. This is different from NetworkServer.active, which is true if the server itself is active rather than this object being active. + /// + public bool isServer { get { return myView.isServer; } } + /// + /// Returns true if running as a client and this object was spawned by a server. + /// + public bool isClient { get { return myView.isClient; } } + /// + /// This returns true if this object is the one that represents the player on the local machine. + /// In multiplayer games, there are multiple instances of the Player object. The client needs to know which one is for "themselves" so that only that player processes input and potentially has a camera attached. The IsLocalPlayer function will return true only for the player instance that belongs to the player on the local machine, so it can be used to filter out input for non-local players. + /// This example shows processing input for only the local player. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class Player : NetworkBehaviour + /// { + /// int moveX = 0; + /// int moveY = 0; + /// + /// void Update() + /// { + /// if (!isLocalPlayer) + /// { + /// return; + /// } + /// // input handling for local player only + /// int oldMoveX = moveX; + /// int oldMoveY = moveY; + /// moveX = 0; + /// moveY = 0; + /// if (Input.GetKey(KeyCode.LeftArrow)) + /// { + /// moveX -= 1; + /// } + /// if (Input.GetKey(KeyCode.RightArrow)) + /// { + /// moveX += 1; + /// } + /// if (Input.GetKey(KeyCode.UpArrow)) + /// { + /// moveY += 1; + /// } + /// if (Input.GetKey(KeyCode.DownArrow)) + /// { + /// moveY -= 1; + /// } + /// if (moveX != oldMoveX || moveY != oldMoveY) + /// { + /// CmdMove(moveX, moveY); + /// } + /// } + /// + /// [Command] + /// void CmdMove(int dx, int dy) + /// { + /// // move here + /// } + /// } + /// + /// + public bool isLocalPlayer { get { return myView.isLocalPlayer; } } + /// + /// This returns true if this object is the authoritative version of the object in the distributed network application. + /// The localPlayerAuthority value on the NetworkIdentity determines how authority is determined. For most objects, authority is held by the server / host. For objects with localPlayerAuthority set, authority is held by the client of that player. + /// + public bool hasAuthority { get { return myView.hasAuthority; } } + /// + /// The unique network Id of this object. + /// This is assigned at runtime by the network server and will be unique for all objects for that network session. + /// + public NetworkInstanceId netId { get { return myView.netId; } } + /// + /// The NetworkConnection associated with this NetworkIdentity. This is only valid for player objects on the server. + /// + public NetworkConnection connectionToServer { get { return myView.connectionToServer; } } + /// + /// The NetworkConnection associated with this NetworkIdentity. This is only valid for player objects on the server. + /// + /// //Attach this script to a GameObject + /// //Attach a TextMesh to the GameObject. To do this click the GameObject, click the Add Component button in the Inspector window, and go to Mesh>Text Mesh. + /// //Attach a NetworkIdentity to the GameObject by clicking Add Component, then go to Network>NetworkIdentity. In the component that was added, check the Local Player Authority checkbox. + /// //Next, create an empty GameObject. Attach a NetworkManager to it by clicking the GameObject, clicking Add Component going to Network>NetworkManager. Also add a NetworkManagerHUD the same way. + /// + /// //This script outputs the Connection ID and address to the console when the Client is started + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class ConnectionToClientExample : NetworkBehaviour + /// { + /// //This is a TextMesh component that you attach to the child of the NetworkIdentity GameObject + /// TextMesh m_TextMesh; + /// + /// void Start() + /// { + /// //Output the connection ID and IP address of the connection by using connectionToClient + /// Debug.Log("Connection ID : " + connectionToClient.connectionId); + /// Debug.Log("Connection Address : " + connectionToClient.address); + /// //Check that the connection is marked as ready + /// if (connectionToClient.isReady) + /// { + /// Debug.Log("Ready!"); + /// } + /// //Enter the child of your GameObject (the GameObject with the TextMesh you attach) + /// //Fetch the TextMesh component of it + /// m_TextMesh = GetComponentInChildren(typeof(TextMesh)) as TextMesh; + /// //Change the Text of the TextMesh to show the netId + /// m_TextMesh.text = "ID : " + netId; + /// //Output the connection to Client + /// } + /// } + /// + /// + public NetworkConnection connectionToClient { get { return myView.connectionToClient; } } + /// + /// The id of the player associated with the behaviour. + /// This is only valid if the GameObject is a local player. + /// The HLAPI treats players and clients as separate GameObjects. In most cases, there is a single player for each client, but in some situations (for example, when there are multiple controllers connected to a console system) there might be multiple player GameObjects for a single connection. When there are multiple players for a single connection, use the playerControllerId property to tell them apart. This is an identifier that is scoped to the connection, so that it maps to the id of the controller associated with the player on that client. + /// + public short playerControllerId { get { return myView.playerControllerId; } } + protected uint syncVarDirtyBits { get { return m_SyncVarDirtyBits; } } + protected bool syncVarHookGuard { get { return m_SyncVarGuard; } set { m_SyncVarGuard = value; }} + + internal NetworkIdentity netIdentity { get { return myView; } } + + const float k_DefaultSendInterval = 0.1f; + + NetworkIdentity m_MyView; + NetworkIdentity myView + { + get + { + if (m_MyView == null) + { + m_MyView = GetComponent(); + if (m_MyView == null) + { + if (LogFilter.logError) { Debug.LogError("There is no NetworkIdentity on this object. Please add one."); } + } + return m_MyView; + } + return m_MyView; + } + } + + // ----------------------------- Commands -------------------------------- + + [EditorBrowsable(EditorBrowsableState.Never)] + protected void SendCommandInternal(NetworkWriter writer, int channelId, string cmdName) + { + // local players can always send commands, regardless of authority, other objects must have authority. + if (!(isLocalPlayer || hasAuthority)) + { + if (LogFilter.logWarn) { Debug.LogWarning("Trying to send command for object without authority."); } + return; + } + + if (ClientScene.readyConnection == null) + { + if (LogFilter.logError) { Debug.LogError("Send command attempted with no client running [client=" + connectionToServer + "]."); } + return; + } + + writer.FinishMessage(); + ClientScene.readyConnection.SendWriter(writer, channelId); + +#if UNITY_EDITOR + Profiler.IncrementStatOutgoing(MsgType.Command, cmdName); +#endif + } + + /// + /// Manually invoke a Command. + /// + /// Hash of the Command name. + /// Parameters to pass to the command. + /// Returns true if successful. + [EditorBrowsable(EditorBrowsableState.Never)] + public virtual bool InvokeCommand(int cmdHash, NetworkReader reader) + { + if (InvokeCommandDelegate(cmdHash, reader)) + { + return true; + } + return false; + } + + // ----------------------------- Client RPCs -------------------------------- + + [EditorBrowsable(EditorBrowsableState.Never)] + protected void SendRPCInternal(NetworkWriter writer, int channelId, string rpcName) + { + // This cannot use NetworkServer.active, as that is not specific to this object. + if (!isServer) + { + if (LogFilter.logWarn) { Debug.LogWarning("ClientRpc call on un-spawned object"); } + return; + } + + writer.FinishMessage(); + NetworkServer.SendWriterToReady(gameObject, writer, channelId); + +#if UNITY_EDITOR + Profiler.IncrementStatOutgoing(MsgType.Rpc, rpcName); +#endif + } + + [EditorBrowsable(EditorBrowsableState.Never)] + protected void SendTargetRPCInternal(NetworkConnection conn, NetworkWriter writer, int channelId, string rpcName) + { + // This cannot use NetworkServer.active, as that is not specific to this object. + if (!isServer) + { + if (LogFilter.logWarn) { Debug.LogWarning("TargetRpc call on un-spawned object"); } + return; + } + + writer.FinishMessage(); + + conn.SendWriter(writer, channelId); + +#if UNITY_EDITOR + Profiler.IncrementStatOutgoing(MsgType.Rpc, rpcName); +#endif + } + + /// + /// Manually invoke an RPC function. + /// + /// Hash of the RPC name. + /// Parameters to pass to the RPC function. + /// Returns true if successful. + [EditorBrowsable(EditorBrowsableState.Never)] + public virtual bool InvokeRPC(int cmdHash, NetworkReader reader) + { + if (InvokeRpcDelegate(cmdHash, reader)) + { + return true; + } + return false; + } + + // ----------------------------- Sync Events -------------------------------- + + [EditorBrowsable(EditorBrowsableState.Never)] + protected void SendEventInternal(NetworkWriter writer, int channelId, string eventName) + { + if (!NetworkServer.active) + { + if (LogFilter.logWarn) { Debug.LogWarning("SendEvent no server?"); } + return; + } + + writer.FinishMessage(); + NetworkServer.SendWriterToReady(gameObject, writer, channelId); + +#if UNITY_EDITOR + Profiler.IncrementStatOutgoing(MsgType.SyncEvent, eventName); +#endif + } + + /// + /// Manually invoke a SyncEvent. + /// + /// Hash of the SyncEvent name. + /// Parameters to pass to the SyncEvent. + /// Returns true if successful. + [EditorBrowsable(EditorBrowsableState.Never)] + public virtual bool InvokeSyncEvent(int cmdHash, NetworkReader reader) + { + if (InvokeSyncEventDelegate(cmdHash, reader)) + { + return true; + } + return false; + } + + // ----------------------------- Sync Lists -------------------------------- + + [EditorBrowsable(EditorBrowsableState.Never)] + public virtual bool InvokeSyncList(int cmdHash, NetworkReader reader) + { + if (InvokeSyncListDelegate(cmdHash, reader)) + { + return true; + } + return false; + } + + // ----------------------------- Code Gen Path Helpers -------------------------------- + /// + /// Delegate for Command functions. + /// + /// + /// + public delegate void CmdDelegate(NetworkBehaviour obj, NetworkReader reader); + /// + /// Delegate for Event functions. + /// + /// + /// + protected delegate void EventDelegate(List targets, NetworkReader reader); + + protected enum UNetInvokeType + { + Command, + ClientRpc, + SyncEvent, + SyncList + }; + + protected class Invoker + { + public UNetInvokeType invokeType; + public Type invokeClass; + public CmdDelegate invokeFunction; + + public string DebugString() + { + return invokeType + ":" + + invokeClass + ":" + + invokeFunction.GetMethodName(); + } + }; + + static Dictionary s_CmdHandlerDelegates = new Dictionary(); + + [EditorBrowsable(EditorBrowsableState.Never)] + static protected void RegisterCommandDelegate(Type invokeClass, int cmdHash, CmdDelegate func) + { + if (s_CmdHandlerDelegates.ContainsKey(cmdHash)) + { + return; + } + Invoker inv = new Invoker(); + inv.invokeType = UNetInvokeType.Command; + inv.invokeClass = invokeClass; + inv.invokeFunction = func; + s_CmdHandlerDelegates[cmdHash] = inv; + if (LogFilter.logDev) { Debug.Log("RegisterCommandDelegate hash:" + cmdHash + " " + func.GetMethodName()); } + } + + [EditorBrowsable(EditorBrowsableState.Never)] + static protected void RegisterRpcDelegate(Type invokeClass, int cmdHash, CmdDelegate func) + { + if (s_CmdHandlerDelegates.ContainsKey(cmdHash)) + { + return; + } + Invoker inv = new Invoker(); + inv.invokeType = UNetInvokeType.ClientRpc; + inv.invokeClass = invokeClass; + inv.invokeFunction = func; + s_CmdHandlerDelegates[cmdHash] = inv; + if (LogFilter.logDev) { Debug.Log("RegisterRpcDelegate hash:" + cmdHash + " " + func.GetMethodName()); } + } + + [EditorBrowsable(EditorBrowsableState.Never)] + static protected void RegisterEventDelegate(Type invokeClass, int cmdHash, CmdDelegate func) + { + if (s_CmdHandlerDelegates.ContainsKey(cmdHash)) + { + return; + } + Invoker inv = new Invoker(); + inv.invokeType = UNetInvokeType.SyncEvent; + inv.invokeClass = invokeClass; + inv.invokeFunction = func; + s_CmdHandlerDelegates[cmdHash] = inv; + if (LogFilter.logDev) { Debug.Log("RegisterEventDelegate hash:" + cmdHash + " " + func.GetMethodName()); } + } + + [EditorBrowsable(EditorBrowsableState.Never)] + static protected void RegisterSyncListDelegate(Type invokeClass, int cmdHash, CmdDelegate func) + { + if (s_CmdHandlerDelegates.ContainsKey(cmdHash)) + { + return; + } + Invoker inv = new Invoker(); + inv.invokeType = UNetInvokeType.SyncList; + inv.invokeClass = invokeClass; + inv.invokeFunction = func; + s_CmdHandlerDelegates[cmdHash] = inv; + if (LogFilter.logDev) { Debug.Log("RegisterSyncListDelegate hash:" + cmdHash + " " + func.GetMethodName()); } + } + + internal static string GetInvoker(int cmdHash) + { + if (!s_CmdHandlerDelegates.ContainsKey(cmdHash)) + { + return null; + } + + Invoker inv = s_CmdHandlerDelegates[cmdHash]; + return inv.DebugString(); + } + + // wrapper fucntions for each type of network operation + internal static bool GetInvokerForHashCommand(int cmdHash, out Type invokeClass, out CmdDelegate invokeFunction) + { + return GetInvokerForHash(cmdHash, UNetInvokeType.Command, out invokeClass, out invokeFunction); + } + + internal static bool GetInvokerForHashClientRpc(int cmdHash, out Type invokeClass, out CmdDelegate invokeFunction) + { + return GetInvokerForHash(cmdHash, UNetInvokeType.ClientRpc, out invokeClass, out invokeFunction); + } + + internal static bool GetInvokerForHashSyncList(int cmdHash, out Type invokeClass, out CmdDelegate invokeFunction) + { + return GetInvokerForHash(cmdHash, UNetInvokeType.SyncList, out invokeClass, out invokeFunction); + } + + internal static bool GetInvokerForHashSyncEvent(int cmdHash, out Type invokeClass, out CmdDelegate invokeFunction) + { + return GetInvokerForHash(cmdHash, UNetInvokeType.SyncEvent, out invokeClass, out invokeFunction); + } + + static bool GetInvokerForHash(int cmdHash, NetworkBehaviour.UNetInvokeType invokeType, out Type invokeClass, out CmdDelegate invokeFunction) + { + Invoker invoker = null; + if (!s_CmdHandlerDelegates.TryGetValue(cmdHash, out invoker)) + { + if (LogFilter.logDev) { Debug.Log("GetInvokerForHash hash:" + cmdHash + " not found"); } + invokeClass = null; + invokeFunction = null; + return false; + } + + if (invoker == null) + { + if (LogFilter.logDev) { Debug.Log("GetInvokerForHash hash:" + cmdHash + " invoker null"); } + invokeClass = null; + invokeFunction = null; + return false; + } + + if (invoker.invokeType != invokeType) + { + if (LogFilter.logError) { Debug.LogError("GetInvokerForHash hash:" + cmdHash + " mismatched invokeType"); } + invokeClass = null; + invokeFunction = null; + return false; + } + + invokeClass = invoker.invokeClass; + invokeFunction = invoker.invokeFunction; + return true; + } + + internal static void DumpInvokers() + { + Debug.Log("DumpInvokers size:" + s_CmdHandlerDelegates.Count); + foreach (var inv in s_CmdHandlerDelegates) + { + Debug.Log(" Invoker:" + inv.Value.invokeClass + ":" + inv.Value.invokeFunction.GetMethodName() + " " + inv.Value.invokeType + " " + inv.Key); + } + } + + internal bool ContainsCommandDelegate(int cmdHash) + { + return s_CmdHandlerDelegates.ContainsKey(cmdHash); + } + + internal bool InvokeCommandDelegate(int cmdHash, NetworkReader reader) + { + if (!s_CmdHandlerDelegates.ContainsKey(cmdHash)) + { + return false; + } + + Invoker inv = s_CmdHandlerDelegates[cmdHash]; + if (inv.invokeType != UNetInvokeType.Command) + { + return false; + } + + if (GetType() != inv.invokeClass) + { + if (GetType().IsSubclassOf(inv.invokeClass)) + { + // allowed, commands function is on a base class. + } + else + { + return false; + } + } + + inv.invokeFunction(this, reader); + return true; + } + + internal bool InvokeRpcDelegate(int cmdHash, NetworkReader reader) + { + if (!s_CmdHandlerDelegates.ContainsKey(cmdHash)) + { + return false; + } + + Invoker inv = s_CmdHandlerDelegates[cmdHash]; + if (inv.invokeType != UNetInvokeType.ClientRpc) + { + return false; + } + + if (GetType() != inv.invokeClass) + { + if (GetType().IsSubclassOf(inv.invokeClass)) + { + // allowed, rpc function is on a base class. + } + else + { + return false; + } + } + + inv.invokeFunction(this, reader); + return true; + } + + internal bool InvokeSyncEventDelegate(int cmdHash, NetworkReader reader) + { + if (!s_CmdHandlerDelegates.ContainsKey(cmdHash)) + { + return false; + } + + Invoker inv = s_CmdHandlerDelegates[cmdHash]; + if (inv.invokeType != UNetInvokeType.SyncEvent) + { + return false; + } + + inv.invokeFunction(this, reader); + return true; + } + + internal bool InvokeSyncListDelegate(int cmdHash, NetworkReader reader) + { + if (!s_CmdHandlerDelegates.ContainsKey(cmdHash)) + { + return false; + } + + Invoker inv = s_CmdHandlerDelegates[cmdHash]; + if (inv.invokeType != UNetInvokeType.SyncList) + { + return false; + } + + if (GetType() != inv.invokeClass) + { + return false; + } + + inv.invokeFunction(this, reader); + return true; + } + + static internal string GetCmdHashHandlerName(int cmdHash) + { + if (!s_CmdHandlerDelegates.ContainsKey(cmdHash)) + { + return cmdHash.ToString(); + } + Invoker inv = s_CmdHandlerDelegates[cmdHash]; + return inv.invokeType + ":" + inv.invokeFunction.GetMethodName(); + } + + static string GetCmdHashPrefixName(int cmdHash, string prefix) + { + if (!s_CmdHandlerDelegates.ContainsKey(cmdHash)) + { + return cmdHash.ToString(); + } + Invoker inv = s_CmdHandlerDelegates[cmdHash]; + var name = inv.invokeFunction.GetMethodName(); + + int index = name.IndexOf(prefix); + if (index > -1) + { + name = name.Substring(prefix.Length); + } + return name; + } + + internal static string GetCmdHashCmdName(int cmdHash) + { + return GetCmdHashPrefixName(cmdHash, "InvokeCmd"); + } + + internal static string GetCmdHashRpcName(int cmdHash) + { + return GetCmdHashPrefixName(cmdHash, "InvokeRpc"); + } + + internal static string GetCmdHashEventName(int cmdHash) + { + return GetCmdHashPrefixName(cmdHash, "InvokeSyncEvent"); + } + + internal static string GetCmdHashListName(int cmdHash) + { + return GetCmdHashPrefixName(cmdHash, "InvokeSyncList"); + } + + // ----------------------------- Helpers -------------------------------- + + [EditorBrowsable(EditorBrowsableState.Never)] + protected void SetSyncVarGameObject(GameObject newGameObject, ref GameObject gameObjectField, uint dirtyBit, ref NetworkInstanceId netIdField) + { + if (m_SyncVarGuard) + return; + + NetworkInstanceId newGameObjectNetId = new NetworkInstanceId(); + if (newGameObject != null) + { + var uv = newGameObject.GetComponent(); + if (uv != null) + { + newGameObjectNetId = uv.netId; + if (newGameObjectNetId.IsEmpty()) + { + if (LogFilter.logWarn) { Debug.LogWarning("SetSyncVarGameObject GameObject " + newGameObject + " has a zero netId. Maybe it is not spawned yet?"); } + } + } + } + + NetworkInstanceId oldGameObjectNetId = new NetworkInstanceId(); + if (gameObjectField != null) + { + oldGameObjectNetId = gameObjectField.GetComponent().netId; + } + + if (newGameObjectNetId != oldGameObjectNetId) + { + if (LogFilter.logDev) { Debug.Log("SetSyncVar GameObject " + GetType().Name + " bit [" + dirtyBit + "] netfieldId:" + oldGameObjectNetId + "->" + newGameObjectNetId); } + SetDirtyBit(dirtyBit); + gameObjectField = newGameObject; + netIdField = newGameObjectNetId; + } + } + + [EditorBrowsable(EditorBrowsableState.Never)] + protected void SetSyncVar(T value, ref T fieldValue, uint dirtyBit) + { + bool changed = false; + if (value == null) + { + if (fieldValue != null) + changed = true; + } + else + { + changed = !value.Equals(fieldValue); + } + if (changed) + { + if (LogFilter.logDev) { Debug.Log("SetSyncVar " + GetType().Name + " bit [" + dirtyBit + "] " + fieldValue + "->" + value); } + SetDirtyBit(dirtyBit); + fieldValue = value; + } + } + + /// + /// Used to set the behaviour as dirty, so that a network update will be sent for the object. + /// + /// Bit mask to set. + // these are masks, not bit numbers, ie. 0x004 not 2 + public void SetDirtyBit(uint dirtyBit) + { + m_SyncVarDirtyBits |= dirtyBit; + } + + /// + /// This clears all the dirty bits that were set on this script by SetDirtyBits(); + /// This is automatically invoked when an update is sent for this object, but can be called manually as well. + /// + public void ClearAllDirtyBits() + { + m_LastSendTime = Time.time; + m_SyncVarDirtyBits = 0; + } + + internal int GetDirtyChannel() + { + if (Time.time - m_LastSendTime > GetNetworkSendInterval()) + { + if (m_SyncVarDirtyBits != 0) + { + return GetNetworkChannel(); + } + } + return -1; + } + + /// + /// Virtual function to override to send custom serialization data. The corresponding function to send serialization data is OnDeserialize(). + /// The initialState flag is useful to differentiate between the first time an object is serialized and when incremental updates can be sent. The first time an object is sent to a client, it must include a full state snapshot, but subsequent updates can save on bandwidth by including only incremental changes. Note that SyncVar hook functions are not called when initialState is true, only for incremental updates. + /// If a class has SyncVars, then an implementation of this function and OnDeserialize() are added automatically to the class. So a class that has SyncVars cannot also have custom serialization functions. + /// The OnSerialize function should return true to indicate that an update should be sent. If it returns true, then the dirty bits for that script are set to zero, if it returns false then the dirty bits are not changed. This allows multiple changes to a script to be accumulated over time and sent when the system is ready, instead of every frame. + /// + /// Writer to use to write to the stream. + /// If this is being called to send initial state. + /// True if data was written. + public virtual bool OnSerialize(NetworkWriter writer, bool initialState) + { + if (!initialState) + { + writer.WritePackedUInt32(0); + } + return false; + } + + /// + /// Virtual function to override to receive custom serialization data. The corresponding function to send serialization data is OnSerialize(). + /// + /// Reader to read from the stream. + /// True if being sent initial state. + public virtual void OnDeserialize(NetworkReader reader, bool initialState) + { + if (!initialState) + { + reader.ReadPackedUInt32(); + } + } + + /// + /// An internal method called on client objects to resolve GameObject references. + /// It is not safe to put user code in this function as it may be replaced by the network system's code generation process. + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public virtual void PreStartClient() + { + } + + /// + /// This is invoked on clients when the server has caused this object to be destroyed. + /// This can be used as a hook to invoke effects or do client specific cleanup. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// class Bomb : NetworkBehaviour + /// { + /// public override void OnNetworkDestroy() + /// { + /// // play explosion sound + /// } + /// } + /// + /// + public virtual void OnNetworkDestroy() + { + } + + /// + /// This is invoked for NetworkBehaviour objects when they become active on the server. + /// This could be triggered by NetworkServer.Listen() for objects in the scene, or by NetworkServer.Spawn() for objects that are dynamically created. + /// This will be called for objects on a "host" as well as for object on a dedicated server. + /// + public virtual void OnStartServer() + { + } + + /// + /// Called on every NetworkBehaviour when it is activated on a client. + /// Objects on the host have this function called, as there is a local client on the host. The values of SyncVars on object are guaranteed to be initialized correctly with the latest state from the server when this function is called on the client. + /// + public virtual void OnStartClient() + { + } + + /// + /// Called when the local player object has been set up. + /// This happens after OnStartClient(), as it is triggered by an ownership message from the server. This is an appropriate place to activate components or functionality that should only be active for the local player, such as cameras and input. + /// + public virtual void OnStartLocalPlayer() + { + } + + /// + /// This is invoked on behaviours that have authority, based on context and 'NetworkIdentity.localPlayerAuthority.' + /// This is called after OnStartServer and OnStartClient. + /// When NetworkIdentity.AssignClientAuthority is called on the server, this will be called on the client that owns the object. When an object is spawned with NetworkServer.SpawnWithClientAuthority, this will be called on the client that owns the object. + /// + public virtual void OnStartAuthority() + { + } + + /// + /// This is invoked on behaviours when authority is removed. + /// When NetworkIdentity.RemoveClientAuthority is called on the server, this will be called on the client that owns the object. + /// + public virtual void OnStopAuthority() + { + } + + /// + /// Callback used by the visibility system to (re)construct the set of observers that can see this object. + /// Implementations of this callback should add network connections of players that can see this object to the observers set. + /// + /// The new set of observers for this object. + /// True if the set of observers is being built for the first time. + /// Return true if this function did work. + public virtual bool OnRebuildObservers(HashSet observers, bool initialize) + { + return false; + } + + /// + /// Callback used by the visibility system for objects on a host. + /// Objects on a host (with a local client) cannot be disabled or destroyed when they are not visibile to the local client. So this function is called to allow custom code to hide these objects. A typical implementation will disable renderer components on the object. This is only called on local clients on a host. + /// + /// New visibility state. + public virtual void OnSetLocalVisibility(bool vis) + { + } + + /// + /// Callback used by the visibility system to determine if an observer (player) can see this object. + /// If this function returns true, the network connection will be added as an observer. + /// + /// Network connection of a player. + /// True if the player can see this object. + public virtual bool OnCheckObserver(NetworkConnection conn) + { + return true; + } + + /// + /// This virtual function is used to specify the QoS channel to use for SyncVar updates for this script. + /// Using the NetworkSettings custom attribute causes this function to be implemented for this script, but developers can also implement it themselves. + /// + /// The QoS channel for this script. + public virtual int GetNetworkChannel() + { + return Channels.DefaultReliable; + } + + /// + /// This virtual function is used to specify the send interval to use for SyncVar updates for this script. + /// Using the NetworkSettings custom attribute causes this function to be implemented for this script, but developers can also implement it themselves. + /// + /// The time in seconds between updates. + public virtual float GetNetworkSendInterval() + { + return k_DefaultSendInterval; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkBuffer.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkBuffer.cs new file mode 100644 index 00000000..9b0f63e1 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkBuffer.cs @@ -0,0 +1,248 @@ +#if ENABLE_UNET +using System; +using System.Runtime.InteropServices; + +namespace UnityEngine.Networking +{ + // A growable buffer class used by NetworkReader and NetworkWriter. + // this is used instead of MemoryStream and BinaryReader/BinaryWriter to avoid allocations. + class NetBuffer + { + byte[] m_Buffer; + uint m_Pos; + const int k_InitialSize = 64; + const float k_GrowthFactor = 1.5f; + const int k_BufferSizeWarning = 1024 * 1024 * 128; + + public uint Position { get { return m_Pos; } } + public int Length { get { return m_Buffer.Length; } } + + public NetBuffer() + { + m_Buffer = new byte[k_InitialSize]; + } + + // this does NOT copy the buffer + public NetBuffer(byte[] buffer) + { + m_Buffer = buffer; + } + + public byte ReadByte() + { + if (m_Pos >= m_Buffer.Length) + { + throw new IndexOutOfRangeException("NetworkReader:ReadByte out of range:" + ToString()); + } + + return m_Buffer[m_Pos++]; + } + + public void ReadBytes(byte[] buffer, uint count) + { + if (m_Pos + count > m_Buffer.Length) + { + throw new IndexOutOfRangeException("NetworkReader:ReadBytes out of range: (" + count + ") " + ToString()); + } + + for (ushort i = 0; i < count; i++) + { + buffer[i] = m_Buffer[m_Pos + i]; + } + m_Pos += count; + } + + internal ArraySegment AsArraySegment() + { + return new ArraySegment(m_Buffer, 0, (int)m_Pos); + } + + public void WriteByte(byte value) + { + WriteCheckForSpace(1); + m_Buffer[m_Pos] = value; + m_Pos += 1; + } + + public void WriteByte2(byte value0, byte value1) + { + WriteCheckForSpace(2); + m_Buffer[m_Pos] = value0; + m_Buffer[m_Pos + 1] = value1; + m_Pos += 2; + } + + public void WriteByte4(byte value0, byte value1, byte value2, byte value3) + { + WriteCheckForSpace(4); + m_Buffer[m_Pos] = value0; + m_Buffer[m_Pos + 1] = value1; + m_Buffer[m_Pos + 2] = value2; + m_Buffer[m_Pos + 3] = value3; + m_Pos += 4; + } + + public void WriteByte8(byte value0, byte value1, byte value2, byte value3, byte value4, byte value5, byte value6, byte value7) + { + WriteCheckForSpace(8); + m_Buffer[m_Pos] = value0; + m_Buffer[m_Pos + 1] = value1; + m_Buffer[m_Pos + 2] = value2; + m_Buffer[m_Pos + 3] = value3; + m_Buffer[m_Pos + 4] = value4; + m_Buffer[m_Pos + 5] = value5; + m_Buffer[m_Pos + 6] = value6; + m_Buffer[m_Pos + 7] = value7; + m_Pos += 8; + } + + // every other Write() function in this class writes implicitly at the end-marker m_Pos. + // this is the only Write() function that writes to a specific location within the buffer + public void WriteBytesAtOffset(byte[] buffer, ushort targetOffset, ushort count) + { + uint newEnd = (uint)(count + targetOffset); + + WriteCheckForSpace((ushort)newEnd); + + if (targetOffset == 0 && count == buffer.Length) + { + buffer.CopyTo(m_Buffer, (int)m_Pos); + } + else + { + //CopyTo doesnt take a count :( + for (int i = 0; i < count; i++) + { + m_Buffer[targetOffset + i] = buffer[i]; + } + } + + // although this writes within the buffer, it could move the end-marker + if (newEnd > m_Pos) + { + m_Pos = newEnd; + } + } + + public void WriteBytes(byte[] buffer, ushort count) + { + WriteCheckForSpace(count); + + if (count == buffer.Length) + { + buffer.CopyTo(m_Buffer, (int)m_Pos); + } + else + { + //CopyTo doesnt take a count :( + for (int i = 0; i < count; i++) + { + m_Buffer[m_Pos + i] = buffer[i]; + } + } + m_Pos += count; + } + + void WriteCheckForSpace(ushort count) + { + if (m_Pos + count < m_Buffer.Length) + return; + + int newLen = (int)Math.Ceiling(m_Buffer.Length * k_GrowthFactor); + while (m_Pos + count >= newLen) + { + newLen = (int)Math.Ceiling(newLen * k_GrowthFactor); + if (newLen > k_BufferSizeWarning) + { + Debug.LogWarning("NetworkBuffer size is " + newLen + " bytes!"); + } + } + + // only do the copy once, even if newLen is increased multiple times + byte[] tmp = new byte[newLen]; + m_Buffer.CopyTo(tmp, 0); + m_Buffer = tmp; + } + + public void FinishMessage() + { + // two shorts (size and msgType) are in header. + ushort sz = (ushort)(m_Pos - (sizeof(ushort) * 2)); + m_Buffer[0] = (byte)(sz & 0xff); + m_Buffer[1] = (byte)((sz >> 8) & 0xff); + } + + public void SeekZero() + { + m_Pos = 0; + } + + public void Replace(byte[] buffer) + { + m_Buffer = buffer; + m_Pos = 0; + } + + public override string ToString() + { + return String.Format("NetBuf sz:{0} pos:{1}", m_Buffer.Length, m_Pos); + } + } // end NetBuffer + + // -- helpers for float conversion -- + [StructLayout(LayoutKind.Explicit)] + internal struct UIntFloat + { + [FieldOffset(0)] + public float floatValue; + + [FieldOffset(0)] + public uint intValue; + + [FieldOffset(0)] + public double doubleValue; + + [FieldOffset(0)] + public ulong longValue; + } + + [StructLayout(LayoutKind.Explicit)] + internal struct UIntDecimal + { + [FieldOffset(0)] + public ulong longValue1; + + [FieldOffset(8)] + public ulong longValue2; + + [FieldOffset(0)] + public decimal decimalValue; + } + + internal class FloatConversion + { + public static float ToSingle(uint value) + { + UIntFloat uf = new UIntFloat(); + uf.intValue = value; + return uf.floatValue; + } + + public static double ToDouble(ulong value) + { + UIntFloat uf = new UIntFloat(); + uf.longValue = value; + return uf.doubleValue; + } + + public static decimal ToDecimal(ulong value1, ulong value2) + { + UIntDecimal uf = new UIntDecimal(); + uf.longValue1 = value1; + uf.longValue2 = value2; + return uf.decimalValue; + } + } +} + +#endif diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkCRC.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkCRC.cs new file mode 100644 index 00000000..65e0a498 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkCRC.cs @@ -0,0 +1,142 @@ +using System; +using System.Collections.Generic; +using System.Reflection; +using UnityEngine.Networking.NetworkSystem; + +namespace UnityEngine.Networking +{ + /// + /// This class holds information about which networked scripts use which QoS channels for updates. + /// This channel information is used to ensure that clients and servers are using compatible HLAPI script configurations. + /// + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class NetworkCRC + { + internal static NetworkCRC s_Singleton; + + Dictionary m_Scripts = new Dictionary(); + bool m_ScriptCRCCheck; + + static internal NetworkCRC singleton + { + get + { + if (s_Singleton == null) + { + s_Singleton = new NetworkCRC(); + } + return s_Singleton; + } + } + /// + /// A dictionary of script QoS channels. + /// This is used to compare script network configurations between clients and servers. + /// + public Dictionary scripts { get { return m_Scripts; } } + + /// + /// Enables a CRC check between server and client that ensures the NetworkBehaviour scripts match. + /// This may not be appropriate in some cases, such a when the client and server are different Unity projects. + /// + static public bool scriptCRCCheck + { + get + { + return singleton.m_ScriptCRCCheck; + } + set + { + singleton.m_ScriptCRCCheck = value; + } + } + + /// + /// This can be used to reinitialize the set of script CRCs. + /// This is very rarely required - only when NetworkBehaviour scripts are dynamically loaded. + /// + /// + // The NetworkCRC cache contain entries from + static public void ReinitializeScriptCRCs(Assembly callingAssembly) + { + singleton.m_Scripts.Clear(); + + var types = callingAssembly.GetTypes(); + for (int i = 0; i < types.Length; i++) + { + var t = types[i]; + if (t.GetBaseType() == typeof(NetworkBehaviour)) + { + var cctor = t.GetMethod(".cctor", BindingFlags.Static); + if (cctor != null) + { + cctor.Invoke(null, new object[] {}); + } + } + } + } + + /// + /// This is used to setup script network settings CRC data. + /// + /// Script name. + /// QoS Channel. + static public void RegisterBehaviour(string name, int channel) + { + singleton.m_Scripts[name] = channel; + } + + internal static bool Validate(CRCMessageEntry[] scripts, int numChannels) + { + return singleton.ValidateInternal(scripts, numChannels); + } + + bool ValidateInternal(CRCMessageEntry[] remoteScripts, int numChannels) + { + // check count against my channels + if (m_Scripts.Count != remoteScripts.Length) + { + if (LogFilter.logWarn) { Debug.LogWarning("Network configuration mismatch detected. The number of networked scripts on the client does not match the number of networked scripts on the server. This could be caused by lazy loading of scripts on the client. This warning can be disabled by the checkbox in NetworkManager Script CRC Check."); } + Dump(remoteScripts); + return false; + } + + // check each script + for (int i = 0; i < remoteScripts.Length; i++) + { + var script = remoteScripts[i]; + if (LogFilter.logDebug) { Debug.Log("Script: " + script.name + " Channel: " + script.channel); } + + if (m_Scripts.ContainsKey(script.name)) + { + int localChannel = m_Scripts[script.name]; + if (localChannel != script.channel) + { + if (LogFilter.logError) { Debug.LogError("HLAPI CRC Channel Mismatch. Script: " + script.name + " LocalChannel: " + localChannel + " RemoteChannel: " + script.channel); } + Dump(remoteScripts); + return false; + } + } + if (script.channel >= numChannels) + { + if (LogFilter.logError) { Debug.LogError("HLAPI CRC channel out of range! Script: " + script.name + " Channel: " + script.channel); } + Dump(remoteScripts); + return false; + } + } + return true; + } + + void Dump(CRCMessageEntry[] remoteScripts) + { + foreach (var script in m_Scripts.Keys) + { + Debug.Log("CRC Local Dump " + script + " : " + m_Scripts[script]); + } + + foreach (var remote in remoteScripts) + { + Debug.Log("CRC Remote Dump " + remote.name + " : " + remote.channel); + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkCallbacks.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkCallbacks.cs new file mode 100644 index 00000000..3382b731 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkCallbacks.cs @@ -0,0 +1,15 @@ +using UnityEngine; +using UnityEngine.Networking; + +#pragma warning disable 618 +namespace UnityEngine.Networking +{ + public class NetworkCallbacks : MonoBehaviour + { + void LateUpdate() + { + NetworkIdentity.UNetStaticUpdate(); + } + } +} +#pragma warning restore 618 \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkClient.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkClient.cs new file mode 100644 index 00000000..aa1d1d55 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkClient.cs @@ -0,0 +1,1299 @@ +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Sockets; +using UnityEngine.Networking.Match; +using UnityEngine.Networking.NetworkSystem; + +namespace UnityEngine.Networking +{ + /// + /// This is a network client class used by the networking system. It contains a NetworkConnection that is used to connect to a network server. + /// The NetworkClient handle connection state, messages handlers, and connection configuration. There can be many NetworkClient instances in a process at a time, but only one that is connected to a game server (NetworkServer) that uses spawned objects. + /// NetworkClient has an internal update function where it handles events from the transport layer. This includes asynchronous connect events, disconnect events and incoming data from a server. + /// The NetworkManager has a NetworkClient instance that it uses for games that it starts, but the NetworkClient may be used by itself. + /// + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class NetworkClient + { + Type m_NetworkConnectionClass = typeof(NetworkConnection); + + const int k_MaxEventsPerFrame = 500; + + static List s_Clients = new List(); + static bool s_IsActive; + + /// + /// A list of all the active network clients in the current process. + /// This is NOT a list of all clients that are connected to the remote server, it is client instances on the local game. + /// + public static List allClients { get { return s_Clients; } } + /// + /// True if a network client is currently active. + /// + public static bool active { get { return s_IsActive; } } + + HostTopology m_HostTopology; + int m_HostPort; + + bool m_UseSimulator; + int m_SimulatedLatency; + float m_PacketLoss; + + string m_ServerIp = ""; + int m_ServerPort; + int m_ClientId = -1; + int m_ClientConnectionId = -1; + //int m_RelaySlotId = -1; + + int m_StatResetTime; + + EndPoint m_RemoteEndPoint; + + // static message objects to avoid runtime-allocations + static CRCMessage s_CRCMessage = new CRCMessage(); + + NetworkMessageHandlers m_MessageHandlers = new NetworkMessageHandlers(); + protected NetworkConnection m_Connection; + + byte[] m_MsgBuffer; + NetworkReader m_MsgReader; + + protected enum ConnectState + { + None, + Resolving, + Resolved, + Connecting, + Connected, + Disconnected, + Failed + } + protected ConnectState m_AsyncConnect = ConnectState.None; + string m_RequestedServerHost = ""; + + internal void SetHandlers(NetworkConnection conn) + { + conn.SetHandlers(m_MessageHandlers); + } + + /// + /// The IP address of the server that this client is connected to. + /// This will be empty if the client has not connected yet. + /// + public string serverIp { get { return m_ServerIp; } } + /// + /// The port of the server that this client is connected to. + /// This will be zero if the client has not connected yet. + /// + public int serverPort { get { return m_ServerPort; } } + /// + /// The NetworkConnection object this client is using. + /// + public NetworkConnection connection { get { return m_Connection; } } + + [Obsolete("Moved to NetworkMigrationManager.")] + public PeerInfoMessage[] peers { get { return null; } } + + internal int hostId { get { return m_ClientId; } } + /// + /// The registered network message handlers. + /// + public Dictionary handlers { get { return m_MessageHandlers.GetHandlers(); } } + /// + /// The number of QoS channels currently configured for this client. + /// + public int numChannels { get { return m_HostTopology.DefaultConfig.ChannelCount; } } + /// + /// The host topology that this client is using. + /// This is read-only once the client is started. + /// + public HostTopology hostTopology { get { return m_HostTopology; }} + /// + /// The local port that the network client uses to connect to the server. + /// It defaults to 0, which means the network client will use a free port of system choice. + /// + public int hostPort + { + get { return m_HostPort; } + set + { + if (value < 0) + throw new ArgumentException("Port must not be a negative number."); + + if (value > 65535) + throw new ArgumentException("Port must not be greater than 65535."); + + m_HostPort = value; + } + } + + /// + /// This gives the current connection status of the client. + /// + public bool isConnected { get { return m_AsyncConnect == ConnectState.Connected; }} + + /// + /// The class to use when creating new NetworkConnections. + /// This can be set with SetNetworkConnectionClass. This allows custom classes that do special processing of data from the transport layer to be used with the NetworkClient. + /// See NetworkConnection.TransportSend and NetworkConnection.TransportReceive for details. + /// + public Type networkConnectionClass + { + get { return m_NetworkConnectionClass; } + } + + /// + /// This sets the class that is used when creating new network connections. + /// The class must be derived from NetworkConnection. + /// + /// + public void SetNetworkConnectionClass() where T : NetworkConnection + { + m_NetworkConnectionClass = typeof(T); + } + + /// + /// Creates a new NetworkClient instance. + /// + public NetworkClient() + { + if (LogFilter.logDev) { Debug.Log("Client created version " + Version.Current); } + m_MsgBuffer = new byte[NetworkMessage.MaxMessageSize]; + m_MsgReader = new NetworkReader(m_MsgBuffer); + AddClient(this); + } + + public NetworkClient(NetworkConnection conn) + { + if (LogFilter.logDev) { Debug.Log("Client created version " + Version.Current); } + m_MsgBuffer = new byte[NetworkMessage.MaxMessageSize]; + m_MsgReader = new NetworkReader(m_MsgBuffer); + AddClient(this); + + SetActive(true); + m_Connection = conn; + m_AsyncConnect = ConnectState.Connected; + conn.SetHandlers(m_MessageHandlers); + RegisterSystemHandlers(false); + } + + /// + /// This configures the transport layer settings for a client. + /// The settings in the ConnectionConfig or HostTopology object will be used to configure the transport layer connection used by this client. This must match the configuration of the server. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class Example : MonoBehaviour + /// { + /// void DoConnect() + /// { + /// ConnectionConfig config = new ConnectionConfig(); + /// config.AddChannel(QosType.ReliableSequenced); + /// config.AddChannel(QosType.UnreliableSequenced); + /// config.PacketSize = 500; + /// NetworkClient client = new NetworkClient(); + /// client.Configure(config, 1); + /// client.Connect("127.0.0.1", 7070); + /// } + /// }; + /// + /// + /// Transport layer configuration object. + /// The maximum number of connections to allow. + /// True if the configuration was successful. + public bool Configure(ConnectionConfig config, int maxConnections) + { + HostTopology top = new HostTopology(config, maxConnections); + return Configure(top); + } + + /// + /// This configures the transport layer settings for a client. + /// The settings in the ConnectionConfig or HostTopology object will be used to configure the transport layer connection used by this client. This must match the configuration of the server. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class Example : MonoBehaviour + /// { + /// void DoConnect() + /// { + /// ConnectionConfig config = new ConnectionConfig(); + /// config.AddChannel(QosType.ReliableSequenced); + /// config.AddChannel(QosType.UnreliableSequenced); + /// config.PacketSize = 500; + /// NetworkClient client = new NetworkClient(); + /// client.Configure(config, 1); + /// client.Connect("127.0.0.1", 7070); + /// } + /// }; + /// + /// + /// Transport layer topology object. + /// True if the configuration was successful. + public bool Configure(HostTopology topology) + { + //NOTE: this maxConnections is across all clients that use this tuner, so it is + // effectively the number of _clients_. + m_HostTopology = topology; + return true; + } + + public void Connect(MatchInfo matchInfo) + { + PrepareForConnect(); + ConnectWithRelay(matchInfo); + } + + /// + /// This is used by a client that has lost the connection to the old host, to reconnect to the new host of a game. + /// + /// The IP address of the new host. + /// The port of the new host. + /// True if able to reconnect. + public bool ReconnectToNewHost(string serverIp, int serverPort) + { + if (!NetworkClient.active) + { + if (LogFilter.logError) { Debug.LogError("Reconnect - NetworkClient must be active"); } + return false; + } + + if (m_Connection == null) + { + if (LogFilter.logError) { Debug.LogError("Reconnect - no old connection exists"); } + return false; + } + + if (LogFilter.logInfo) { Debug.Log("NetworkClient Reconnect " + serverIp + ":" + serverPort); } + + ClientScene.HandleClientDisconnect(m_Connection); + ClientScene.ClearLocalPlayers(); + + m_Connection.Disconnect(); + m_Connection = null; + m_ClientId = NetworkManager.activeTransport.AddHost(m_HostTopology, m_HostPort, null); + + string hostnameOrIp = serverIp; + m_ServerPort = serverPort; + + //TODO: relay reconnect + /* + if (Match.NetworkMatch.matchSingleton != null) + { + hostnameOrIp = Match.NetworkMatch.matchSingleton.address; + m_ServerPort = Match.NetworkMatch.matchSingleton.port; + }*/ + + if (UnityEngine.Application.platform == RuntimePlatform.WebGLPlayer) + { + m_ServerIp = hostnameOrIp; + m_AsyncConnect = ConnectState.Resolved; + } + else if (serverIp.Equals("127.0.0.1") || serverIp.Equals("localhost")) + { + m_ServerIp = "127.0.0.1"; + m_AsyncConnect = ConnectState.Resolved; + } + else + { + if (LogFilter.logDebug) { Debug.Log("Async DNS START:" + hostnameOrIp); } + m_AsyncConnect = ConnectState.Resolving; + Dns.BeginGetHostAddresses(hostnameOrIp, new AsyncCallback(GetHostAddressesCallback), this); + } + return true; + } + + public bool ReconnectToNewHost(EndPoint secureTunnelEndPoint) + { + if (!NetworkClient.active) + { + if (LogFilter.logError) { Debug.LogError("Reconnect - NetworkClient must be active"); } + return false; + } + + if (m_Connection == null) + { + if (LogFilter.logError) { Debug.LogError("Reconnect - no old connection exists"); } + return false; + } + + if (LogFilter.logInfo) { Debug.Log("NetworkClient Reconnect to remoteSockAddr"); } + + ClientScene.HandleClientDisconnect(m_Connection); + ClientScene.ClearLocalPlayers(); + + m_Connection.Disconnect(); + m_Connection = null; + m_ClientId = NetworkManager.activeTransport.AddHost(m_HostTopology, m_HostPort, null); + + if (secureTunnelEndPoint == null) + { + if (LogFilter.logError) { Debug.LogError("Reconnect failed: null endpoint passed in"); } + m_AsyncConnect = ConnectState.Failed; + return false; + } + + // Make sure it's either IPv4 or IPv6 + if (secureTunnelEndPoint.AddressFamily != AddressFamily.InterNetwork && secureTunnelEndPoint.AddressFamily != AddressFamily.InterNetworkV6) + { + if (LogFilter.logError) { Debug.LogError("Reconnect failed: Endpoint AddressFamily must be either InterNetwork or InterNetworkV6"); } + m_AsyncConnect = ConnectState.Failed; + return false; + } + + // Make sure it's an Endpoint we know what to do with + string endPointType = secureTunnelEndPoint.GetType().FullName; + if (endPointType == "System.Net.IPEndPoint") + { + IPEndPoint tmp = (IPEndPoint)secureTunnelEndPoint; + Connect(tmp.Address.ToString(), tmp.Port); + return m_AsyncConnect != ConnectState.Failed; + } + if ((endPointType != "UnityEngine.XboxOne.XboxOneEndPoint") && (endPointType != "UnityEngine.PS4.SceEndPoint")) + { + if (LogFilter.logError) { Debug.LogError("Reconnect failed: invalid Endpoint (not IPEndPoint or XboxOneEndPoint or SceEndPoint)"); } + m_AsyncConnect = ConnectState.Failed; + return false; + } + + byte error = 0; + // regular non-relay connect + m_RemoteEndPoint = secureTunnelEndPoint; + m_AsyncConnect = ConnectState.Connecting; + + try + { + m_ClientConnectionId = NetworkManager.activeTransport.ConnectEndPoint(m_ClientId, m_RemoteEndPoint, 0, out error); + } + catch (Exception ex) + { + if (LogFilter.logError) { Debug.LogError("Reconnect failed: Exception when trying to connect to EndPoint: " + ex); } + m_AsyncConnect = ConnectState.Failed; + return false; + } + if (m_ClientConnectionId == 0) + { + if (LogFilter.logError) { Debug.LogError("Reconnect failed: Unable to connect to EndPoint (" + error + ")"); } + m_AsyncConnect = ConnectState.Failed; + return false; + } + + m_Connection = (NetworkConnection)Activator.CreateInstance(m_NetworkConnectionClass); + m_Connection.SetHandlers(m_MessageHandlers); + m_Connection.Initialize(m_ServerIp, m_ClientId, m_ClientConnectionId, m_HostTopology); + return true; + } + + /// + /// Connect client to a NetworkServer instance with simulated latency and packet loss. + /// + /// Target IP address or hostname. + /// Target port number. + /// Simulated latency in milliseconds. + /// Simulated packet loss percentage. + public void ConnectWithSimulator(string serverIp, int serverPort, int latency, float packetLoss) + { + m_UseSimulator = true; + m_SimulatedLatency = latency; + m_PacketLoss = packetLoss; + Connect(serverIp, serverPort); + } + + static bool IsValidIpV6(string address) + { + for (int i = 0; i < address.Length; i++) + { + var c = address[i]; + if ( + (c == ':') || + (c >= '0' && c <= '9') || + (c >= 'a' && c <= 'f') || + (c >= 'A' && c <= 'F') + ) + { + continue; + } + return false; + } + return true; + } + + /// + /// Connect client to a NetworkServer instance. + /// Connecting to a server is asynchronous. There is connection message that is fired when the client connects. If the connection fails, a MsgType.Error message will be generated. Once a connection is established you are able to send messages on the connection using NetworkClient.Send(). If using other features of the high level api, the client should call NetworkClient.IsReady() once it is ready to participate in the game. At that point the client will be sent spawned objects and state update messages. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class NetClient + /// { + /// NetworkClient myClient; + /// + /// public void OnConnected(NetworkConnection conn, NetworkReader reader) + /// { + /// Debug.Log("Connected to server"); + /// } + /// + /// public void OnDisconnected(NetworkConnection conn, NetworkReader reader) + /// { + /// Debug.Log("Disconnected from server"); + /// } + /// + /// public void OnError(NetworkConnection conn, NetworkReader reader) + /// { + /// SystemErrorMessage errorMsg = reader.SmartRead<SystemErrorMessage>(); + /// Debug.Log("Error connecting with code " + errorMsg.errorCode); + /// } + /// + /// public void Start() + /// { + /// myClient = NetworkClient.Instance; + /// myClient.RegisterHandler(MsgType.SYSTEM_CONNECT, OnConnected); + /// myClient.RegisterHandler(MsgType.SYSTEM_DISCONNECT, OnDisconnected); + /// myClient.RegisterHandler(MsgType.SYSTEM_ERROR, OnError); + /// myClient.Connect("127.0.0.1", 8888); + /// } + /// } + /// + /// + /// Target IP address or hostname. + /// Target port number. + public void Connect(string serverIp, int serverPort) + { + PrepareForConnect(); + + if (LogFilter.logDebug) { Debug.Log("Client Connect: " + serverIp + ":" + serverPort); } + + string hostnameOrIp = serverIp; + m_ServerPort = serverPort; + + if (UnityEngine.Application.platform == RuntimePlatform.WebGLPlayer) + { + m_ServerIp = hostnameOrIp; + m_AsyncConnect = ConnectState.Resolved; + } + else if (serverIp.Equals("127.0.0.1") || serverIp.Equals("localhost")) + { + m_ServerIp = "127.0.0.1"; + m_AsyncConnect = ConnectState.Resolved; + } + else if (serverIp.IndexOf(":") != -1 && IsValidIpV6(serverIp)) + { + m_ServerIp = serverIp; + m_AsyncConnect = ConnectState.Resolved; + } + else + { + if (LogFilter.logDebug) { Debug.Log("Async DNS START:" + hostnameOrIp); } + m_RequestedServerHost = hostnameOrIp; + m_AsyncConnect = ConnectState.Resolving; + Dns.BeginGetHostAddresses(hostnameOrIp, GetHostAddressesCallback, this); + } + } + + public void Connect(EndPoint secureTunnelEndPoint) + { + bool usePlatformSpecificProtocols = NetworkManager.activeTransport.DoesEndPointUsePlatformProtocols(secureTunnelEndPoint); + PrepareForConnect(usePlatformSpecificProtocols); + + if (LogFilter.logDebug) { Debug.Log("Client Connect to remoteSockAddr"); } + + if (secureTunnelEndPoint == null) + { + if (LogFilter.logError) { Debug.LogError("Connect failed: null endpoint passed in"); } + m_AsyncConnect = ConnectState.Failed; + return; + } + + // Make sure it's either IPv4 or IPv6 + if (secureTunnelEndPoint.AddressFamily != AddressFamily.InterNetwork && secureTunnelEndPoint.AddressFamily != AddressFamily.InterNetworkV6) + { + if (LogFilter.logError) { Debug.LogError("Connect failed: Endpoint AddressFamily must be either InterNetwork or InterNetworkV6"); } + m_AsyncConnect = ConnectState.Failed; + return; + } + + // Make sure it's an Endpoint we know what to do with + string endPointType = secureTunnelEndPoint.GetType().FullName; + if (endPointType == "System.Net.IPEndPoint") + { + IPEndPoint tmp = (IPEndPoint)secureTunnelEndPoint; + Connect(tmp.Address.ToString(), tmp.Port); + return; + } + if ((endPointType != "UnityEngine.XboxOne.XboxOneEndPoint") && (endPointType != "UnityEngine.PS4.SceEndPoint")) + { + if (LogFilter.logError) { Debug.LogError("Connect failed: invalid Endpoint (not IPEndPoint or XboxOneEndPoint or SceEndPoint)"); } + m_AsyncConnect = ConnectState.Failed; + return; + } + + byte error = 0; + // regular non-relay connect + m_RemoteEndPoint = secureTunnelEndPoint; + m_AsyncConnect = ConnectState.Connecting; + + try + { + m_ClientConnectionId = NetworkManager.activeTransport.ConnectEndPoint(m_ClientId, m_RemoteEndPoint, 0, out error); + } + catch (Exception ex) + { + if (LogFilter.logError) { Debug.LogError("Connect failed: Exception when trying to connect to EndPoint: " + ex); } + m_AsyncConnect = ConnectState.Failed; + return; + } + if (m_ClientConnectionId == 0) + { + if (LogFilter.logError) { Debug.LogError("Connect failed: Unable to connect to EndPoint (" + error + ")"); } + m_AsyncConnect = ConnectState.Failed; + return; + } + + m_Connection = (NetworkConnection)Activator.CreateInstance(m_NetworkConnectionClass); + m_Connection.SetHandlers(m_MessageHandlers); + m_Connection.Initialize(m_ServerIp, m_ClientId, m_ClientConnectionId, m_HostTopology); + } + + void PrepareForConnect() + { + PrepareForConnect(false); + } + + void PrepareForConnect(bool usePlatformSpecificProtocols) + { + SetActive(true); + RegisterSystemHandlers(false); + + if (m_HostTopology == null) + { + var config = new ConnectionConfig(); + config.AddChannel(QosType.ReliableSequenced); + config.AddChannel(QosType.Unreliable); + config.UsePlatformSpecificProtocols = usePlatformSpecificProtocols; + m_HostTopology = new HostTopology(config, 8); + } + + if (m_UseSimulator) + { + int minTimeout = (m_SimulatedLatency / 3) - 1; + if (minTimeout < 1) + { + minTimeout = 1; + } + int maxTimeout = m_SimulatedLatency * 3; + + if (LogFilter.logDebug) { Debug.Log("AddHost Using Simulator " + minTimeout + "/" + maxTimeout); } + m_ClientId = NetworkManager.activeTransport.AddHostWithSimulator(m_HostTopology, minTimeout, maxTimeout, m_HostPort); + } + else + { + m_ClientId = NetworkManager.activeTransport.AddHost(m_HostTopology, m_HostPort, null); + } + } + + // this called in another thread! Cannot call Update() here. + internal static void GetHostAddressesCallback(IAsyncResult ar) + { + try + { + IPAddress[] ip = Dns.EndGetHostAddresses(ar); + NetworkClient client = (NetworkClient)ar.AsyncState; + + if (ip.Length == 0) + { + if (LogFilter.logError) { Debug.LogError("DNS lookup failed for:" + client.m_RequestedServerHost); } + client.m_AsyncConnect = ConnectState.Failed; + return; + } + + client.m_ServerIp = ip[0].ToString(); + client.m_AsyncConnect = ConnectState.Resolved; + if (LogFilter.logDebug) { Debug.Log("Async DNS Result:" + client.m_ServerIp + " for " + client.m_RequestedServerHost + ": " + client.m_ServerIp); } + } + catch (SocketException e) + { + NetworkClient client = (NetworkClient)ar.AsyncState; + if (LogFilter.logError) { Debug.LogError("DNS resolution failed: " + e.GetErrorCode()); } + if (LogFilter.logDebug) { Debug.Log("Exception:" + e); } + client.m_AsyncConnect = ConnectState.Failed; + } + } + + internal void ContinueConnect() + { + byte error; + // regular non-relay connect + if (m_UseSimulator) + { + int simLatency = m_SimulatedLatency / 3; + if (simLatency < 1) + { + simLatency = 1; + } + + if (LogFilter.logDebug) { Debug.Log("Connect Using Simulator " + (m_SimulatedLatency / 3) + "/" + m_SimulatedLatency); } + var simConfig = new ConnectionSimulatorConfig( + simLatency, + m_SimulatedLatency, + simLatency, + m_SimulatedLatency, + m_PacketLoss); + + m_ClientConnectionId = NetworkManager.activeTransport.ConnectWithSimulator(m_ClientId, m_ServerIp, m_ServerPort, 0, out error, simConfig); + } + else + { + m_ClientConnectionId = NetworkManager.activeTransport.Connect(m_ClientId, m_ServerIp, m_ServerPort, 0, out error); + } + + m_Connection = (NetworkConnection)Activator.CreateInstance(m_NetworkConnectionClass); + m_Connection.SetHandlers(m_MessageHandlers); + m_Connection.Initialize(m_ServerIp, m_ClientId, m_ClientConnectionId, m_HostTopology); + } + + void ConnectWithRelay(MatchInfo info) + { + m_AsyncConnect = ConnectState.Connecting; + + Update(); + + byte error; + m_ClientConnectionId = NetworkManager.activeTransport.ConnectToNetworkPeer( + m_ClientId, + info.address, + info.port, + 0, + 0, + info.networkId, + Utility.GetSourceID(), + info.nodeId, + out error); + + m_Connection = (NetworkConnection)Activator.CreateInstance(m_NetworkConnectionClass); + m_Connection.SetHandlers(m_MessageHandlers); + m_Connection.Initialize(info.address, m_ClientId, m_ClientConnectionId, m_HostTopology); + + if (error != 0) { Debug.LogError("ConnectToNetworkPeer Error: " + error); } + } + + /// + /// Disconnect from server. + /// The disconnect message will be invoked. + /// + public virtual void Disconnect() + { + m_AsyncConnect = ConnectState.Disconnected; + ClientScene.HandleClientDisconnect(m_Connection); + if (m_Connection != null) + { + m_Connection.Disconnect(); + m_Connection.Dispose(); + m_Connection = null; + if (m_ClientId != -1) + { + NetworkManager.activeTransport.RemoveHost(m_ClientId); + m_ClientId = -1; + } + } + } + + /// + /// This sends a network message with a message Id to the server. This message is sent on channel zero, which by default is the reliable channel. + /// The message must be an instance of a class derived from MessageBase. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class RegisterHostMessage : MessageBase + /// { + /// public string gameName; + /// public string comment; + /// public bool passwordProtected; + /// } + /// + /// public class MasterClient + /// { + /// public NetworkClient client; + /// + /// public const short RegisterHostMsgId = 888; + /// + /// public void RegisterHost(string name) + /// { + /// RegisterHostMessage msg = new RegisterHostMessage(); + /// msg.gameName = name; + /// msg.comment = "test"; + /// msg.passwordProtected = false; + /// client.Send(RegisterHostMsgId, msg); + /// } + /// } + /// + /// The message id passed to Send() is used to identify the handler function to invoke on the server when the message is received. + /// + /// The id of the message to send. + /// A message instance to send. + /// True if message was sent. + public bool Send(short msgType, MessageBase msg) + { + if (m_Connection != null) + { + if (m_AsyncConnect != ConnectState.Connected) + { + if (LogFilter.logError) { Debug.LogError("NetworkClient Send when not connected to a server"); } + return false; + } +#if UNITY_EDITOR + Profiler.IncrementStatOutgoing(MsgType.UserMessage, msgType + ":" + msg.GetType().Name); +#endif + return m_Connection.Send(msgType, msg); + } + if (LogFilter.logError) { Debug.LogError("NetworkClient Send with no connection"); } + return false; + } + + /// + /// This sends the contents of the NetworkWriter's buffer to the connected server on the specified channel. + /// The format of the data in the writer must be properly formatted for it to be processed as a message by the server. The functions StartMessage() and FinishMessage() can be used to properly format messages: + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class TestClient + /// { + /// public NetworkClient client; + /// + /// public const int RegisterHostMsgId = 888; + /// + /// public void RegisterHost(string name) + /// { + /// NetworkWriter writer = new NetworkWriter(); + /// writer.StartMessage(RegisterHostMsgId); + /// writer.Write(name); + /// writer.FinishMessage(); + /// client.SendWriter(writer, Channels.DefaultReliable); + /// } + /// } + /// + /// + /// Writer object containing data to send. + /// QoS channel to send data on. + /// True if data successfully sent. + public bool SendWriter(NetworkWriter writer, int channelId) + { + if (m_Connection != null) + { + if (m_AsyncConnect != ConnectState.Connected) + { + if (LogFilter.logError) { Debug.LogError("NetworkClient SendWriter when not connected to a server"); } + return false; + } + return m_Connection.SendWriter(writer, channelId); + } + if (LogFilter.logError) { Debug.LogError("NetworkClient SendWriter with no connection"); } + return false; + } + + /// + /// This sends the data in an array of bytes to the server that the client is connected to. + /// The data must be properly formatted. + /// + /// Data to send. + /// Number of bytes of data. + /// The QoS channel to send data on. + /// True if successfully sent. + public bool SendBytes(byte[] data, int numBytes, int channelId) + { + if (m_Connection != null) + { + if (m_AsyncConnect != ConnectState.Connected) + { + if (LogFilter.logError) { Debug.LogError("NetworkClient SendBytes when not connected to a server"); } + return false; + } + return m_Connection.SendBytes(data, numBytes, channelId); + } + if (LogFilter.logError) { Debug.LogError("NetworkClient SendBytes with no connection"); } + return false; + } + + /// + /// This sends a network message with a message Id to the server on channel one, which by default is the unreliable channel. + /// This does the same thing as NetworkClient.Send(), except that it send on the unreliable channel. + /// + /// The message id to send. + /// The message to send. + /// True if the message was sent. + public bool SendUnreliable(short msgType, MessageBase msg) + { + if (m_Connection != null) + { + if (m_AsyncConnect != ConnectState.Connected) + { + if (LogFilter.logError) { Debug.LogError("NetworkClient SendUnreliable when not connected to a server"); } + return false; + } +#if UNITY_EDITOR + Profiler.IncrementStatOutgoing(MsgType.UserMessage, msgType + ":" + msg.GetType().Name); +#endif + return m_Connection.SendUnreliable(msgType, msg); + } + if (LogFilter.logError) { Debug.LogError("NetworkClient SendUnreliable with no connection"); } + return false; + } + + /// + /// This sends a network message with a message Id to the server on a specific channel. + /// This does the same thing as NetworkClient.Send(), but allows a transport layer QoS channel to be specified. + /// + /// The id of the message to send. + /// The message to send. + /// The channel to send the message on. + /// True if the message was sent. + public bool SendByChannel(short msgType, MessageBase msg, int channelId) + { +#if UNITY_EDITOR + Profiler.IncrementStatOutgoing(MsgType.UserMessage, msgType + ":" + msg.GetType().Name); +#endif + if (m_Connection != null) + { + if (m_AsyncConnect != ConnectState.Connected) + { + if (LogFilter.logError) { Debug.LogError("NetworkClient SendByChannel when not connected to a server"); } + return false; + } + return m_Connection.SendByChannel(msgType, msg, channelId); + } + if (LogFilter.logError) { Debug.LogError("NetworkClient SendByChannel with no connection"); } + return false; + } + + /// + /// Set the maximum amount of time that can pass for transmitting the send buffer. + /// + /// Delay in seconds. + public void SetMaxDelay(float seconds) + { + if (m_Connection == null) + { + if (LogFilter.logWarn) { Debug.LogWarning("SetMaxDelay failed, not connected."); } + return; + } + m_Connection.SetMaxDelay(seconds); + } + + /// + /// Shut down a client. + /// This should be done when a client is no longer going to be used. + /// + public void Shutdown() + { + if (LogFilter.logDebug) Debug.Log("Shutting down client " + m_ClientId); + if (m_ClientId != -1) + { + NetworkManager.activeTransport.RemoveHost(m_ClientId); + m_ClientId = -1; + } + RemoveClient(this); + if (s_Clients.Count == 0) + { + SetActive(false); + } + } + + internal virtual void Update() + { + if (m_ClientId == -1) + { + return; + } + + switch (m_AsyncConnect) + { + case ConnectState.None: + case ConnectState.Resolving: + case ConnectState.Disconnected: + return; + + case ConnectState.Failed: + GenerateConnectError((int)NetworkError.DNSFailure); + m_AsyncConnect = ConnectState.Disconnected; + return; + + case ConnectState.Resolved: + m_AsyncConnect = ConnectState.Connecting; + ContinueConnect(); + return; + + case ConnectState.Connecting: + case ConnectState.Connected: + { + break; + } + } + + if (m_Connection != null) + { + if ((int)Time.time != m_StatResetTime) + { + m_Connection.ResetStats(); + m_StatResetTime = (int)Time.time; + } + } + + int numEvents = 0; + NetworkEventType networkEvent; + do + { + int connectionId; + int channelId; + int receivedSize; + byte error; + + networkEvent = NetworkManager.activeTransport.ReceiveFromHost(m_ClientId, out connectionId, out channelId, m_MsgBuffer, (ushort)m_MsgBuffer.Length, out receivedSize, out error); + if (m_Connection != null) m_Connection.lastError = (NetworkError)error; + + if (networkEvent != NetworkEventType.Nothing) + { + if (LogFilter.logDev) { Debug.Log("Client event: host=" + m_ClientId + " event=" + networkEvent + " error=" + error); } + } + + switch (networkEvent) + { + case NetworkEventType.ConnectEvent: + + if (LogFilter.logDebug) { Debug.Log("Client connected"); } + + if (error != 0) + { + GenerateConnectError(error); + return; + } + + m_AsyncConnect = ConnectState.Connected; + m_Connection.InvokeHandlerNoData(MsgType.Connect); + break; + + case NetworkEventType.DataEvent: + if (error != 0) + { + GenerateDataError(error); + return; + } + +#if UNITY_EDITOR + Profiler.IncrementStatIncoming(MsgType.LLAPIMsg); +#endif + + m_MsgReader.SeekZero(); + m_Connection.TransportReceive(m_MsgBuffer, receivedSize, channelId); + break; + + case NetworkEventType.DisconnectEvent: + if (LogFilter.logDebug) { Debug.Log("Client disconnected"); } + + m_AsyncConnect = ConnectState.Disconnected; + + if (error != 0) + { + if ((NetworkError)error != NetworkError.Timeout) + { + GenerateDisconnectError(error); + } + } + ClientScene.HandleClientDisconnect(m_Connection); + if (m_Connection != null) + { + m_Connection.InvokeHandlerNoData(MsgType.Disconnect); + } + break; + + case NetworkEventType.Nothing: + break; + + default: + if (LogFilter.logError) { Debug.LogError("Unknown network message type received: " + networkEvent); } + break; + } + + if (++numEvents >= k_MaxEventsPerFrame) + { + if (LogFilter.logDebug) { Debug.Log("MaxEventsPerFrame hit (" + k_MaxEventsPerFrame + ")"); } + break; + } + if (m_ClientId == -1) + { + break; + } + } + while (networkEvent != NetworkEventType.Nothing); + + if (m_Connection != null && m_AsyncConnect == ConnectState.Connected) + m_Connection.FlushChannels(); + } + + void GenerateConnectError(int error) + { + if (LogFilter.logError) { Debug.LogError("UNet Client Error Connect Error: " + error); } + GenerateError(error); + } + + void GenerateDataError(int error) + { + NetworkError dataError = (NetworkError)error; + if (LogFilter.logError) { Debug.LogError("UNet Client Data Error: " + dataError); } + GenerateError(error); + } + + void GenerateDisconnectError(int error) + { + NetworkError disconnectError = (NetworkError)error; + if (LogFilter.logError) { Debug.LogError("UNet Client Disconnect Error: " + disconnectError); } + GenerateError(error); + } + + void GenerateError(int error) + { + NetworkMessageDelegate msgDelegate = m_MessageHandlers.GetHandler(MsgType.Error); + if (msgDelegate == null) + { + msgDelegate = m_MessageHandlers.GetHandler(MsgType.Error); + } + if (msgDelegate != null) + { + ErrorMessage msg = new ErrorMessage(); + msg.errorCode = error; + + // write the message to a local buffer + byte[] errorBuffer = new byte[200]; + NetworkWriter writer = new NetworkWriter(errorBuffer); + msg.Serialize(writer); + + // pass a reader (attached to local buffer) to handler + NetworkReader reader = new NetworkReader(errorBuffer); + + NetworkMessage netMsg = new NetworkMessage(); + netMsg.msgType = MsgType.Error; + netMsg.reader = reader; + netMsg.conn = m_Connection; + netMsg.channelId = 0; + msgDelegate(netMsg); + } + } + + /// + /// Get outbound network statistics for the client. + /// + /// Number of messages sent so far (including collated messages send through buffer). + /// Number of messages sent through buffer. + /// Number of bytes sent so far. + /// Number of messages buffered for sending per second. + public void GetStatsOut(out int numMsgs, out int numBufferedMsgs, out int numBytes, out int lastBufferedPerSecond) + { + numMsgs = 0; + numBufferedMsgs = 0; + numBytes = 0; + lastBufferedPerSecond = 0; + + if (m_Connection != null) + { + m_Connection.GetStatsOut(out numMsgs, out numBufferedMsgs, out numBytes, out lastBufferedPerSecond); + } + } + + /// + /// Get inbound network statistics for the client. + /// + /// Number of messages received so far. + /// Number of bytes received so far. + public void GetStatsIn(out int numMsgs, out int numBytes) + { + numMsgs = 0; + numBytes = 0; + + if (m_Connection != null) + { + m_Connection.GetStatsIn(out numMsgs, out numBytes); + } + } + + /// + /// Retrieves statistics about the network packets sent on this connection. + /// + /// Dictionary of packet statistics for the client's connection. + public Dictionary GetConnectionStats() + { + if (m_Connection == null) + return null; + + return m_Connection.packetStats; + } + + /// + /// Resets the statistics return by NetworkClient.GetConnectionStats() to zero values. + /// Useful when building per-second network statistics. + /// + public void ResetConnectionStats() + { + if (m_Connection == null) + return; + + m_Connection.ResetStats(); + } + + /// + /// Gets the Return Trip Time for this connection. + /// This value is calculated by the transport layer. + /// + /// Return trip time in milliseconds. + public int GetRTT() + { + if (m_ClientId == -1) + return 0; + + byte err; + return NetworkManager.activeTransport.GetCurrentRTT(m_ClientId, m_ClientConnectionId, out err); + } + + internal void RegisterSystemHandlers(bool localClient) + { + ClientScene.RegisterSystemHandlers(this, localClient); + RegisterHandlerSafe(MsgType.CRC, OnCRC); + RegisterHandlerSafe(MsgType.Fragment, NetworkConnection.OnFragment); + } + + void OnCRC(NetworkMessage netMsg) + { + netMsg.ReadMessage(s_CRCMessage); + NetworkCRC.Validate(s_CRCMessage.scripts, numChannels); + } + + /// + /// Register a handler for a particular message type. + /// There are several system message types which you can add handlers for. You can also add your own message types. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class Server : MonoBehaviour + /// { + /// void Start() + /// { + /// NetworkServer.Listen(7070); + /// Debug.Log("Registering server callbacks"); + /// NetworkClient client = new NetworkClient(); + /// client.RegisterHandler(MsgType.Connect, OnConnected); + /// } + /// + /// void OnConnected(NetworkMessage netMsg) + /// { + /// Debug.Log("Client connected"); + /// } + /// } + /// + /// + /// Message type number. + /// Function handler which will be invoked for when this message type is received. + public void RegisterHandler(short msgType, NetworkMessageDelegate handler) + { + m_MessageHandlers.RegisterHandler(msgType, handler); + } + + public void RegisterHandlerSafe(short msgType, NetworkMessageDelegate handler) + { + m_MessageHandlers.RegisterHandlerSafe(msgType, handler); + } + + /// + /// Unregisters a network message handler. + /// + /// The message type to unregister. + public void UnregisterHandler(short msgType) + { + m_MessageHandlers.UnregisterHandler(msgType); + } + + /// + /// Retrieves statistics about the network packets sent on all connections. + /// + /// Dictionary of stats. + static public Dictionary GetTotalConnectionStats() + { + Dictionary stats = new Dictionary(); + for (int i = 0; i < s_Clients.Count; i++) + { + var client = s_Clients[i]; + var clientStats = client.GetConnectionStats(); + foreach (short k in clientStats.Keys) + { + if (stats.ContainsKey(k)) + { + NetworkConnection.PacketStat s = stats[k]; + s.count += clientStats[k].count; + s.bytes += clientStats[k].bytes; + stats[k] = s; + } + else + { + stats[k] = new NetworkConnection.PacketStat(clientStats[k]); + } + } + } + return stats; + } + + internal static void AddClient(NetworkClient client) + { + s_Clients.Add(client); + } + + internal static bool RemoveClient(NetworkClient client) + { + return s_Clients.Remove(client); + } + + static internal void UpdateClients() + { + for (int i = 0; i < s_Clients.Count; ++i) + { + if (s_Clients[i] != null) + s_Clients[i].Update(); + else + s_Clients.RemoveAt(i); + } + } + + /// + /// Shuts down all network clients. + /// This also shuts down the transport layer. + /// + static public void ShutdownAll() + { + while (s_Clients.Count != 0) + { + s_Clients[0].Shutdown(); + } + s_Clients = new List(); + s_IsActive = false; + ClientScene.Shutdown(); +#if UNITY_EDITOR + Profiler.ResetAll(); +#endif + } + + internal static void SetActive(bool state) + { + // what is this check? + //if (state == false && s_Clients.Count != 0) + // return; + + if (!s_IsActive && state) + { + NetworkManager.activeTransport.Init(); + } + s_IsActive = state; + } + }; +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkConnection.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkConnection.cs new file mode 100644 index 00000000..548e49f6 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkConnection.cs @@ -0,0 +1,968 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace UnityEngine.Networking +{ + /// + /// A High level network connection. This is used for connections from client-to-server and for connection from server-to-client. + /// A NetworkConnection corresponds to a specific connection for a host in the transport layer. It has a connectionId that is assigned by the transport layer and passed to the Initialize function. + /// A NetworkClient has one NetworkConnection. A NetworkServerSimple manages multiple NetworkConnections. The NetworkServer has multiple "remote" connections and a "local" connection for the local client. + /// The NetworkConnection class provides message sending and handling facilities. For sending data over a network, there are methods to send message objects, byte arrays, and NetworkWriter objects. To handle data arriving from the network, handler functions can be registered for message Ids, byte arrays can be processed by HandleBytes(), and NetworkReader object can be processed by HandleReader(). + /// NetworkConnection objects also act as observers for networked objects. When a connection is an observer of a networked object with a NetworkIdentity, then the object will be visible to corresponding client for the connection, and incremental state changes will be sent to the client. + /// NetworkConnection objects can "own" networked game objects. Owned objects will be destroyed on the server by default when the connection is destroyed. A connection owns the player objects created by its client, and other objects with client-authority assigned to the corresponding client. + /// There are many virtual functions on NetworkConnection that allow its behaviour to be customized. NetworkClient and NetworkServer can both be made to instantiate custom classes derived from NetworkConnection by setting their networkConnectionClass member variable. + /// + /* + * wire protocol is a list of : size | msgType | payload + * (short) (variable) (buffer) + */ + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class NetworkConnection : IDisposable + { + ChannelBuffer[] m_Channels; + List m_PlayerControllers = new List(); + NetworkMessage m_NetMsg = new NetworkMessage(); + HashSet m_VisList = new HashSet(); + internal HashSet visList { get { return m_VisList; } } + NetworkWriter m_Writer; + + Dictionary m_MessageHandlersDict; + NetworkMessageHandlers m_MessageHandlers; + + HashSet m_ClientOwnedObjects; + NetworkMessage m_MessageInfo = new NetworkMessage(); + + const int k_MaxMessageLogSize = 150; + private NetworkError error; + + /// + /// Transport level host ID for this connection. + /// This is assigned by the transport layer and passed to the connection instance through the Initialize function. + /// + public int hostId = -1; + /// + /// Unique identifier for this connection that is assigned by the transport layer. + /// On a server, this Id is unique for every connection on the server. On a client this Id is local to the client, it is not the same as the Id on the server for this connection. + /// Transport layers connections begin at one. So on a client with a single connection to a server, the connectionId of that connection will be one. In NetworkServer, the connectionId of the local connection is zero. + /// Clients do not know their connectionId on the server, and do not know the connectionId of other clients on the server. + /// + public int connectionId = -1; + /// + /// Flag that tells if the connection has been marked as "ready" by a client calling ClientScene.Ready(). + /// This property is read-only. It is set by the system on the client when ClientScene.Ready() is called, and set by the system on the server when a ready message is received from a client. + /// A client that is ready is sent spawned objects by the server and updates to the state of spawned objects. A client that is not ready is not sent spawned objects. + /// + public bool isReady; + /// + /// The IP address associated with the connection. + /// + public string address; + /// + /// The last time that a message was received on this connection. + /// This includes internal system messages (such as Commands and ClientRpc calls) and user messages. + /// + public float lastMessageTime; + /// + /// The list of players for this connection. + /// In most cases this will be a single player. But, for "Couch Multiplayer" there could be multiple players for a single client. To see the players on your own client see ClientScene.localPlayers list. + /// + public List playerControllers { get { return m_PlayerControllers; } } + /// + /// A list of the NetworkIdentity objects owned by this connection. + /// This includes the player object for the connection - if it has localPlayerAutority set, and any objects spawned with local authority or set with AssignLocalAuthority. This list is read only. + /// This list can be used to validate messages from clients, to ensure that clients are only trying to control objects that they own. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class Handler + /// { + /// static public void HandleTransform(NetworkMessage netMsg) + /// { + /// NetworkInstanceId netId = netMsg.reader.ReadNetworkId(); + /// GameObject foundObj = NetworkServer.FindLocalObject(netId); + /// if (foundObj == null) + /// { + /// return; + /// } + /// NetworkTransform foundSync = foundObj.GetComponent<NetworkTransform>(); + /// if (foundSync == null) + /// { + /// return; + /// } + /// if (!foundSync.localPlayerAuthority) + /// { + /// return; + /// } + /// if (netMsg.conn.clientOwnedObjects.Contains(netId)) + /// { + /// // process message + /// } + /// else + /// { + /// // error + /// } + /// } + /// } + /// + /// + public HashSet clientOwnedObjects { get { return m_ClientOwnedObjects; } } + /// + /// Setting this to true will log the contents of network message to the console. + /// Warning: this can be a lot of data and can be very slow. Both incoming and outgoing messages are logged. The format of the logs is: + /// ConnectionSend con:1 bytes:11 msgId:5 FB59D743FD120000000000 ConnectionRecv con:1 bytes:27 msgId:8 14F21000000000016800AC3FE090C240437846403CDDC0BD3B0000 + /// Note that these are application-level network messages, not protocol-level packets. There will typically be multiple network messages combined in a single protocol packet. + /// + public bool logNetworkMessages = false; + /// + /// True if the connection is connected to a remote end-point. + /// This applies to NetworkServer and NetworkClient connections. When not connected, the hostID will be -1. When connected, the hostID will be a positive integer. + /// + public bool isConnected { get { return hostId != -1; }} + + + /// + /// Structure used to track the number and size of packets of each packets type. + /// + public class PacketStat + { + public PacketStat() + { + msgType = 0; + count = 0; + bytes = 0; + } + + public PacketStat(PacketStat s) + { + msgType = s.msgType; + count = s.count; + bytes = s.bytes; + } + + /// + /// The message type these stats are for. + /// + public short msgType; + /// + /// The total number of messages of this type. + /// + public int count; + /// + /// Total bytes of all messages of this type. + /// + public int bytes; + + public override string ToString() + { + return MsgType.MsgTypeToString(msgType) + ": count=" + count + " bytes=" + bytes; + } + } + + /// + /// The last error associated with this connection. + /// Retrieve the last error that occurred on the connection, this value is set every time an event is received from the NetworkTransport. + /// In the following example, OnServerDisconnect is overridden from NetworkManager: + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class ExampleScript : NetworkManager + /// { + /// public override void OnServerDisconnect(NetworkConnection conn) + /// { + /// if (conn.lastError != NetworkError.Ok) + /// { + /// if (LogFilter.logError) + /// { + /// Debug.LogError("ServerDisconnected due to error: " + conn.lastError); + /// } + /// } + /// } + /// } + /// + /// + public NetworkError lastError { get { return error; } internal set { error = value; } } + + Dictionary m_PacketStats = new Dictionary(); + internal Dictionary packetStats { get { return m_PacketStats; }} + +#if UNITY_EDITOR + static int s_MaxPacketStats = 255;//the same as maximum message types +#endif + + /// + /// This inializes the internal data structures of a NetworkConnection object, including channel buffers. + /// This is called by NetworkServer and NetworkClient on connection objects, but if used outside of that context, this function should be called before the connection is used. + /// This function can be overriden to perform additional initialization for the connection, but the base class Initialize function should always be called as it is required to setup internal state. + /// + /// The host or IP connected to. + /// The transport hostId for the connection. + /// The transport connectionId for the connection. + /// The topology to be used. + public virtual void Initialize(string networkAddress, int networkHostId, int networkConnectionId, HostTopology hostTopology) + { + m_Writer = new NetworkWriter(); + address = networkAddress; + hostId = networkHostId; + connectionId = networkConnectionId; + + int numChannels = hostTopology.DefaultConfig.ChannelCount; + int packetSize = hostTopology.DefaultConfig.PacketSize; + + if ((hostTopology.DefaultConfig.UsePlatformSpecificProtocols) && (UnityEngine.Application.platform != RuntimePlatform.PS4)) + throw new ArgumentOutOfRangeException("Platform specific protocols are not supported on this platform"); + + m_Channels = new ChannelBuffer[numChannels]; + for (int i = 0; i < numChannels; i++) + { + var qos = hostTopology.DefaultConfig.Channels[i]; + int actualPacketSize = packetSize; + if (qos.QOS == QosType.ReliableFragmented || qos.QOS == QosType.UnreliableFragmented) + { + actualPacketSize = hostTopology.DefaultConfig.FragmentSize * 128; + } + m_Channels[i] = new ChannelBuffer(this, actualPacketSize, (byte)i, IsReliableQoS(qos.QOS), IsSequencedQoS(qos.QOS)); + } + } + + // Track whether Dispose has been called. + bool m_Disposed; + + ~NetworkConnection() + { + Dispose(false); + } + + /// + /// Disposes of this connection, releasing channel buffers that it holds. + /// + public void Dispose() + { + Dispose(true); + // Take yourself off the Finalization queue + // to prevent finalization code for this object + // from executing a second time. + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing) + { + // Check to see if Dispose has already been called. + if (!m_Disposed && m_Channels != null) + { + for (int i = 0; i < m_Channels.Length; i++) + { + m_Channels[i].Dispose(); + } + } + m_Channels = null; + + if (m_ClientOwnedObjects != null) + { + foreach (var netId in m_ClientOwnedObjects) + { + var obj = NetworkServer.FindLocalObject(netId); + if (obj != null) + { + obj.GetComponent().ClearClientOwner(); + } + } + } + m_ClientOwnedObjects = null; + + m_Disposed = true; + } + + static bool IsSequencedQoS(QosType qos) + { + return (qos == QosType.ReliableSequenced || qos == QosType.UnreliableSequenced); + } + + static bool IsReliableQoS(QosType qos) + { + return (qos == QosType.Reliable || qos == QosType.ReliableFragmented || qos == QosType.ReliableSequenced || qos == QosType.ReliableStateUpdate); + } + + /// + /// This sets an option on the network channel. + /// Channel options are usually advanced tuning parameters. + /// + /// The channel the option will be set on. + /// The option to set. + /// The value for the option. + /// True if the option was set. + public bool SetChannelOption(int channelId, ChannelOption option, int value) + { + if (m_Channels == null) + return false; + + if (channelId < 0 || channelId >= m_Channels.Length) + return false; + + return m_Channels[channelId].SetOption(option, value); + } + + public NetworkConnection() + { + m_Writer = new NetworkWriter(); + } + + /// + /// Disconnects this connection. + /// + public void Disconnect() + { + address = ""; + isReady = false; + ClientScene.HandleClientDisconnect(this); + if (hostId == -1) + { + return; + } + byte error; + NetworkManager.activeTransport.Disconnect(hostId, connectionId, out error); + + RemoveObservers(); + } + + internal void SetHandlers(NetworkMessageHandlers handlers) + { + m_MessageHandlers = handlers; + m_MessageHandlersDict = handlers.GetHandlers(); + } + + /// + /// This function checks if there is a message handler registered for the message ID. + /// This is usually not required, as InvokeHandler handles message IDs without handlers. + /// + /// The message ID of the handler to look for. + /// True if a handler function was found. + public bool CheckHandler(short msgType) + { + return m_MessageHandlersDict.ContainsKey(msgType); + } + + /// + /// This function invokes the registered handler function for a message, without any message data. + /// This is useful to invoke handlers that dont have any additional data, such as the handlers for MsgType.Connect. + /// + /// The message ID of the handler to invoke. + /// True if a handler function was found and invoked. + public bool InvokeHandlerNoData(short msgType) + { + return InvokeHandler(msgType, null, 0); + } + + /// + /// This function invokes the registered handler function for a message. + /// Network connections used by the NetworkClient and NetworkServer use this function for handling network messages. + /// + /// The message type of the handler to use. + /// The stream to read the contents of the message from. + /// The channel that the message arrived on. + /// True if a handler function was found and invoked. + public bool InvokeHandler(short msgType, NetworkReader reader, int channelId) + { + if (m_MessageHandlersDict.ContainsKey(msgType)) + { + m_MessageInfo.msgType = msgType; + m_MessageInfo.conn = this; + m_MessageInfo.reader = reader; + m_MessageInfo.channelId = channelId; + + NetworkMessageDelegate msgDelegate = m_MessageHandlersDict[msgType]; + if (msgDelegate == null) + { + if (LogFilter.logError) { Debug.LogError("NetworkConnection InvokeHandler no handler for " + msgType); } + return false; + } + msgDelegate(m_MessageInfo); + return true; + } + return false; + } + + /// + /// This function invokes the registered handler function for a message. + /// Network connections used by the NetworkClient and NetworkServer use this function for handling network messages. + /// + /// The message object to process. + /// True if a handler function was found and invoked. + public bool InvokeHandler(NetworkMessage netMsg) + { + if (m_MessageHandlersDict.ContainsKey(netMsg.msgType)) + { + NetworkMessageDelegate msgDelegate = m_MessageHandlersDict[netMsg.msgType]; + msgDelegate(netMsg); + return true; + } + return false; + } + + internal void HandleFragment(NetworkReader reader, int channelId) + { + if (channelId < 0 || channelId >= m_Channels.Length) + { + return; + } + + var channel = m_Channels[channelId]; + if (channel.HandleFragment(reader)) + { + NetworkReader msgReader = new NetworkReader(channel.fragmentBuffer.AsArraySegment().Array); + msgReader.ReadInt16(); // size + short msgType = msgReader.ReadInt16(); + InvokeHandler(msgType, msgReader, channelId); + } + } + + /// + /// This registers a handler function for a message Id. + /// + /// The message ID to register. + /// The handler function to register. + public void RegisterHandler(short msgType, NetworkMessageDelegate handler) + { + m_MessageHandlers.RegisterHandler(msgType, handler); + } + + /// + /// This removes the handler registered for a message Id. + /// + /// The message ID to unregister. + public void UnregisterHandler(short msgType) + { + m_MessageHandlers.UnregisterHandler(msgType); + } + + internal void SetPlayerController(PlayerController player) + { + while (player.playerControllerId >= m_PlayerControllers.Count) + { + m_PlayerControllers.Add(new PlayerController()); + } + + m_PlayerControllers[player.playerControllerId] = player; + } + + internal void RemovePlayerController(short playerControllerId) + { + int count = m_PlayerControllers.Count; + while (count >= 0) + { + if (playerControllerId == count && playerControllerId == m_PlayerControllers[count].playerControllerId) + { + m_PlayerControllers[count] = new PlayerController(); + return; + } + count -= 1; + } + if (LogFilter.logError) { Debug.LogError("RemovePlayer player at playerControllerId " + playerControllerId + " not found"); } + } + + // Get player controller from connection's list + internal bool GetPlayerController(short playerControllerId, out PlayerController playerController) + { + playerController = null; + if (playerControllers.Count > 0) + { + for (int i = 0; i < playerControllers.Count; i++) + { + if (playerControllers[i].IsValid && playerControllers[i].playerControllerId == playerControllerId) + { + playerController = playerControllers[i]; + return true; + } + } + return false; + } + return false; + } + + /// + /// This causes the channels of the network connection to flush their data to the transport layer. + /// This is called automatically by connections used by NetworkServer and NetworkClient, but can be called manually for connections used in other contexts. + /// + public void FlushChannels() + { + if (m_Channels == null) + { + return; + } + for (int channelId = 0; channelId < m_Channels.Length; channelId++) + { + m_Channels[channelId].CheckInternalBuffer(); + } + } + + /// + /// The maximum time in seconds that messages are buffered before being sent. + /// If this is set to zero, then there will be no buffering of messages before they are sent to the transport layer. This may reduce latency but can lead to packet queue overflow issues if many small packets are being sent. + /// + /// Time in seconds. + public void SetMaxDelay(float seconds) + { + if (m_Channels == null) + { + return; + } + for (int channelId = 0; channelId < m_Channels.Length; channelId++) + { + m_Channels[channelId].maxDelay = seconds; + } + } + + /// + /// This sends a network message with a message ID on the connection. This message is sent on channel zero, which by default is the reliable channel. + /// + /// The ID of the message to send. + /// The message to send. + /// True if the message was sent. + public virtual bool Send(short msgType, MessageBase msg) + { + return SendByChannel(msgType, msg, Channels.DefaultReliable); + } + + /// + /// This sends a network message with a message ID on the connection. This message is sent on channel one, which by default is the unreliable channel. + /// + /// The message ID to send. + /// The message to send. + /// True if the message was sent. + public virtual bool SendUnreliable(short msgType, MessageBase msg) + { + return SendByChannel(msgType, msg, Channels.DefaultUnreliable); + } + + /// + /// This sends a network message on the connection using a specific transport layer channel. + /// + /// The message ID to send. + /// The message to send. + /// The transport layer channel to send on. + /// True if the message was sent. + public virtual bool SendByChannel(short msgType, MessageBase msg, int channelId) + { + m_Writer.StartMessage(msgType); + msg.Serialize(m_Writer); + m_Writer.FinishMessage(); + return SendWriter(m_Writer, channelId); + } + + /// + /// This sends an array of bytes on the connection. + /// + /// The array of data to be sent. + /// The number of bytes in the array to be sent. + /// The transport channel to send on. + /// Success if data was sent. + public virtual bool SendBytes(byte[] bytes, int numBytes, int channelId) + { + if (logNetworkMessages) + { + LogSend(bytes); + } + return CheckChannel(channelId) && m_Channels[channelId].SendBytes(bytes, numBytes); + } + + /// + /// This sends the contents of a NetworkWriter object on the connection. + /// The example below constructs a writer and sends it on a connection. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class ExampleScript : MonoBehaviour + /// { + /// public bool Send(short msgType, MessageBase msg, NetworkConnection conn) + /// { + /// NetworkWriter writer = new NetworkWriter(); + /// writer.StartMessage(msgType); + /// msg.Serialize(writer); + /// writer.FinishMessage(); + /// return conn.SendWriter(writer, Channels.DefaultReliable); + /// } + /// } + /// + /// + /// A writer object containing data to send. + /// The transport channel to send on. + /// True if the data was sent. + public virtual bool SendWriter(NetworkWriter writer, int channelId) + { + if (logNetworkMessages) + { + LogSend(writer.ToArray()); + } + return CheckChannel(channelId) && m_Channels[channelId].SendWriter(writer); + } + + void LogSend(byte[] bytes) + { + NetworkReader reader = new NetworkReader(bytes); + var msgSize = reader.ReadUInt16(); + var msgId = reader.ReadUInt16(); + + const int k_PayloadStartPosition = 4; + + StringBuilder msg = new StringBuilder(); + for (int i = k_PayloadStartPosition; i < k_PayloadStartPosition + msgSize; i++) + { + msg.AppendFormat("{0:X2}", bytes[i]); + if (i > k_MaxMessageLogSize) break; + } + Debug.Log("ConnectionSend con:" + connectionId + " bytes:" + msgSize + " msgId:" + msgId + " " + msg); + } + + bool CheckChannel(int channelId) + { + if (m_Channels == null) + { + if (LogFilter.logWarn) { Debug.LogWarning("Channels not initialized sending on id '" + channelId); } + return false; + } + if (channelId < 0 || channelId >= m_Channels.Length) + { + if (LogFilter.logError) { Debug.LogError("Invalid channel when sending buffered data, '" + channelId + "'. Current channel count is " + m_Channels.Length); } + return false; + } + return true; + } + + /// + /// Resets the statistics that are returned from NetworkClient.GetConnectionStats(). + /// + public void ResetStats() + { +#if UNITY_EDITOR + for (short i = 0; i < s_MaxPacketStats; i++) + { + if (m_PacketStats.ContainsKey(i)) + { + var value = m_PacketStats[i]; + value.count = 0; + value.bytes = 0; + NetworkManager.activeTransport.SetPacketStat(0, i, 0, 0); + NetworkManager.activeTransport.SetPacketStat(1, i, 0, 0); + } + } +#endif + } + + /// + /// This makes the connection process the data contained in the buffer, and call handler functions. + /// The data is assumed to have come from the network, and contains network messages. + /// This function is used by network connections when they receive data. + /// + /// Data to process. + /// Size of the data to process. + /// Channel the data was recieved on. + protected void HandleBytes( + byte[] buffer, + int receivedSize, + int channelId) + { + // build the stream form the buffer passed in + NetworkReader reader = new NetworkReader(buffer); + + HandleReader(reader, receivedSize, channelId); + } + + /// + /// This makes the connection process the data contained in the stream, and call handler functions. + /// The data in the stream is assumed to have come from the network, and contains network messages. + /// This function is used by network connections when they receive data. + /// + /// Stream that contains data. + /// Size of the data. + /// Channel the data was received on. + protected void HandleReader( + NetworkReader reader, + int receivedSize, + int channelId) + { + // read until size is reached. + // NOTE: stream.Capacity is 1300, NOT the size of the available data + while (reader.Position < receivedSize) + { + // the reader passed to user code has a copy of bytes from the real stream. user code never touches the real stream. + // this ensures it can never get out of sync if user code reads less or more than the real amount. + ushort sz = reader.ReadUInt16(); + short msgType = reader.ReadInt16(); + + // create a reader just for this message + //TODO: Allocation!! + byte[] msgBuffer = reader.ReadBytes(sz); + NetworkReader msgReader = new NetworkReader(msgBuffer); + + if (logNetworkMessages) + { + StringBuilder msg = new StringBuilder(); + for (int i = 0; i < sz; i++) + { + msg.AppendFormat("{0:X2}", msgBuffer[i]); + if (i > k_MaxMessageLogSize) break; + } + Debug.Log("ConnectionRecv con:" + connectionId + " bytes:" + sz + " msgId:" + msgType + " " + msg); + } + + NetworkMessageDelegate msgDelegate = null; + if (m_MessageHandlersDict.ContainsKey(msgType)) + { + msgDelegate = m_MessageHandlersDict[msgType]; + } + if (msgDelegate != null) + { + m_NetMsg.msgType = msgType; + m_NetMsg.reader = msgReader; + m_NetMsg.conn = this; + m_NetMsg.channelId = channelId; + msgDelegate(m_NetMsg); + lastMessageTime = Time.time; + +#if UNITY_EDITOR + Profiler.IncrementStatIncoming(MsgType.HLAPIMsg); + + if (msgType > MsgType.Highest) + { + Profiler.IncrementStatIncoming(MsgType.UserMessage, msgType + ":" + msgType.GetType().Name); + } +#endif + +#if UNITY_EDITOR + if (m_PacketStats.ContainsKey(msgType)) + { + PacketStat stat = m_PacketStats[msgType]; + stat.count += 1; + stat.bytes += sz; + } + else + { + PacketStat stat = new PacketStat(); + stat.msgType = msgType; + stat.count += 1; + stat.bytes += sz; + m_PacketStats[msgType] = stat; + } +#endif + } + else + { + //NOTE: this throws away the rest of the buffer. Need moar error codes + if (LogFilter.logError) { Debug.LogError("Unknown message ID " + msgType + " connId:" + connectionId); } + break; + } + } + } + + /// + /// Get statistics for outgoing traffic. + /// + /// Number of messages sent. + /// Number of messages currently buffered for sending. + /// Number of bytes sent. + /// How many messages were buffered in the last second. + public virtual void GetStatsOut(out int numMsgs, out int numBufferedMsgs, out int numBytes, out int lastBufferedPerSecond) + { + numMsgs = 0; + numBufferedMsgs = 0; + numBytes = 0; + lastBufferedPerSecond = 0; + + for (int channelId = 0; channelId < m_Channels.Length; channelId++) + { + var channel = m_Channels[channelId]; + numMsgs += channel.numMsgsOut; + numBufferedMsgs += channel.numBufferedMsgsOut; + numBytes += channel.numBytesOut; + lastBufferedPerSecond += channel.lastBufferedPerSecond; + } + } + + /// + /// Get statistics for incoming traffic. + /// + /// Number of messages received. + /// Number of bytes received. + public virtual void GetStatsIn(out int numMsgs, out int numBytes) + { + numMsgs = 0; + numBytes = 0; + + for (int channelId = 0; channelId < m_Channels.Length; channelId++) + { + var channel = m_Channels[channelId]; + numMsgs += channel.numMsgsIn; + numBytes += channel.numBytesIn; + } + } + + /// + /// Returns a string representation of the NetworkConnection object state. + /// + /// + public override string ToString() + { + return string.Format("hostId: {0} connectionId: {1} isReady: {2} channel count: {3}", hostId, connectionId, isReady, (m_Channels != null ? m_Channels.Length : 0)); + } + + internal void AddToVisList(NetworkIdentity uv) + { + m_VisList.Add(uv); + + // spawn uv for this conn + NetworkServer.ShowForConnection(uv, this); + } + + internal void RemoveFromVisList(NetworkIdentity uv, bool isDestroyed) + { + m_VisList.Remove(uv); + + if (!isDestroyed) + { + // hide uv for this conn + NetworkServer.HideForConnection(uv, this); + } + } + + internal void RemoveObservers() + { + foreach (var uv in m_VisList) + { + uv.RemoveObserverInternal(this); + } + m_VisList.Clear(); + } + + /// + /// This virtual function allows custom network connection classes to process data from the network before it is passed to the application. + /// The default implementation of this function calls HandleBytes() on the received data. Custom implmentations can also use HandleBytes(), but can pass modified versions of the data received or other data. + /// This example logs the data received to the console, then passes it to HandleBytes. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// using System; + /// using System.Text; + /// public class DebugConnection : NetworkConnection + /// { + /// public override void TransportReceive(byte[] bytes, int numBytes, int channelId) + /// { + /// StringBuilder msg = new StringBuilder(); + /// for (int i = 0; i < numBytes; i++) { + /// { + /// var s = String.Format("{0:X2}", bytes[i]); + /// msg.Append(s); + /// if (i > 50) break; + /// } + /// UnityEngine.Debug.LogError("TransportReceive h:" + hostId + " con:" + connectionId + " bytes:" + numBytes + " " + msg); + /// HandleBytes(bytes, numBytes, channelId); + /// } + /// } + /// + /// Other uses for this function could be data compression or data encryption. + /// Custom network connection classes are used by setting NetworkServer.NetworkConnectionClass and NetworkClient.NetworkConnectionClass. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class SpaceManager : NetworkManager + /// { + /// void Start() + /// { + /// NetworkServer.networkConnectionClass = typeof(DebugConnection); + /// NetworkClient.networkConnectionClass = typeof(DebugConnection); + /// } + /// } + /// + /// + /// The data recieved. + /// The size of the data recieved. + /// The channel that the data was received on. + public virtual void TransportReceive(byte[] bytes, int numBytes, int channelId) + { + HandleBytes(bytes, numBytes, channelId); + } + + [Obsolete("TransportRecieve has been deprecated. Use TransportReceive instead.", false)] + public virtual void TransportRecieve(byte[] bytes, int numBytes, int channelId) + { + TransportReceive(bytes, numBytes, channelId); + } + + /// + /// This virtual function allows custom network connection classes to process data send by the application before it goes to the network transport layer. + /// The default implementation of this function calls NetworkTransport.Send() with the supplied data, but custom implementations can pass modified versions of the data. This example logs the sent data to the console: + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// using System; + /// using System.Text; + /// + /// class DebugConnection : NetworkConnection + /// { + /// public override bool TransportSend(byte[] bytes, int numBytes, int channelId, out byte error) + /// { + /// StringBuilder msg = new StringBuilder(); + /// for (int i = 0; i < numBytes; i++) + /// { + /// var s = String.Format("{0:X2}", bytes[i]); + /// msg.Append(s); + /// if (i > 50) break; + /// } + /// UnityEngine.Debug.LogError("TransportSend h:" + hostId + " con:" + connectionId + " bytes:" + numBytes + " " + msg); + /// return NetworkTransport.Send(hostId, connectionId, channelId, bytes, numBytes, out error); + /// } + /// } + /// + /// Other uses for this function could be data compression or data encryption. + /// Custom network connection classes are used by setting NetworkServer.NetworkConnectionClass and NetworkClient.NetworkConnectionClass. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class SpaceManager : NetworkManager + /// { + /// void Start() + /// { + /// NetworkServer.networkConnectionClass = typeof(DebugConnection); + /// NetworkClient.networkConnectionClass = typeof(DebugConnection); + /// } + /// } + /// + /// + /// Data to send. + /// Size of data to send. + /// Channel to send data on. + /// Error code for send. + /// True if data was sent. + public virtual bool TransportSend(byte[] bytes, int numBytes, int channelId, out byte error) + { + return NetworkManager.activeTransport.Send(hostId, connectionId, channelId, bytes, numBytes, out error); + } + + internal void AddOwnedObject(NetworkIdentity obj) + { + if (m_ClientOwnedObjects == null) + { + m_ClientOwnedObjects = new HashSet(); + } + m_ClientOwnedObjects.Add(obj.netId); + } + + internal void RemoveOwnedObject(NetworkIdentity obj) + { + if (m_ClientOwnedObjects == null) + { + return; + } + m_ClientOwnedObjects.Remove(obj.netId); + } + + internal static void OnFragment(NetworkMessage netMsg) + { + netMsg.conn.HandleFragment(netMsg.reader, netMsg.channelId); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkDiscovery.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkDiscovery.cs new file mode 100644 index 00000000..75970a90 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkDiscovery.cs @@ -0,0 +1,541 @@ +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace UnityEngine.Networking +{ + /// + /// A structure that contains data from a NetworkDiscovery server broadcast. + /// + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public struct NetworkBroadcastResult + { + /// + /// The IP address of the server that broadcasts this data. + /// + public string serverAddress; + /// + /// The data broadcast by the server. + /// + public byte[] broadcastData; + } + + /// + /// The NetworkDiscovery component allows Unity games to find each other on a local network. It can broadcast presence and listen for broadcasts, and optionally join matching games using the NetworkManager. + /// This component can run in server mode (by calling StartAsServer) where it broadcasts to other computers on the local network, or in client mode (by calling StartAsClient) where it listens for broadcasts from a server. This class should be override to receive calls from OnReceivedBroadcast. + /// Note : Do not use void Update() in a class that inherits from NetworkDiscovery. If needed, you must override it and call base.Update() instead. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// using System.Collections; + /// + /// public class OverriddenNetworkDiscovery : NetworkDiscovery + /// { + /// public override void OnReceivedBroadcast(string fromAddress, string data) + /// { + /// NetworkManager.singleton.networkAddress = fromAddress; + /// NetworkManager.singleton.StartClient(); + /// } + /// } + /// + /// + [DisallowMultipleComponent] + [AddComponentMenu("Network/NetworkDiscovery")] + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class NetworkDiscovery : MonoBehaviour + { + const int k_MaxBroadcastMsgSize = 1024; + + // config data + [SerializeField] + int m_BroadcastPort = 47777; + + [SerializeField] + int m_BroadcastKey = 2222; + + [SerializeField] + int m_BroadcastVersion = 1; + + [SerializeField] + int m_BroadcastSubVersion = 1; + + [SerializeField] + int m_BroadcastInterval = 1000; + + [SerializeField] + bool m_UseNetworkManager = false; + + [SerializeField] + string m_BroadcastData = "HELLO"; + + [SerializeField] + bool m_ShowGUI = true; + + [SerializeField] + int m_OffsetX; + + [SerializeField] + int m_OffsetY; + + // runtime data + int m_HostId = -1; + bool m_Running; + + bool m_IsServer; + bool m_IsClient; + + byte[] m_MsgOutBuffer; + byte[] m_MsgInBuffer; + HostTopology m_DefaultTopology; + Dictionary m_BroadcastsReceived; + + /// + /// The network port to broadcast on and listen to. + /// + public int broadcastPort + { + get { return m_BroadcastPort; } + set { m_BroadcastPort = value; } + } + + /// + /// A key to identify this application in broadcasts. + /// + public int broadcastKey + { + get { return m_BroadcastKey; } + set { m_BroadcastKey = value; } + } + + /// + /// The version of the application to broadcast. This is used to match versions of the same application. + /// + public int broadcastVersion + { + get { return m_BroadcastVersion; } + set { m_BroadcastVersion = value; } + } + + /// + /// The sub-version of the application to broadcast. This is used to match versions of the same application. + /// + public int broadcastSubVersion + { + get { return m_BroadcastSubVersion; } + set { m_BroadcastSubVersion = value; } + } + + /// + /// How often in milliseconds to broadcast when running as a server. + /// + public int broadcastInterval + { + get { return m_BroadcastInterval; } + set { m_BroadcastInterval = value; } + } + + /// + /// True to integrate with the NetworkManager. + /// When running as a server, this will include the NetworkManager's address in broadcast messages. When running as a client, this will be able to join matching games found by using the NetworkManager. + /// + public bool useNetworkManager + { + get { return m_UseNetworkManager; } + set { m_UseNetworkManager = value; } + } + + /// + /// The data to include in the broadcast message when running as a server. + /// If using NetworkManager integration, this will be overriden with the NetworkManager's address. + /// + public string broadcastData + { + get { return m_BroadcastData; } + set + { + m_BroadcastData = value; + m_MsgOutBuffer = StringToBytes(m_BroadcastData); + if (m_UseNetworkManager) + { + if (LogFilter.logWarn) { Debug.LogWarning("NetworkDiscovery broadcast data changed while using NetworkManager. This can prevent clients from finding the server. The format of the broadcast data must be 'NetworkManager:IPAddress:Port'."); } + } + } + } + + /// + /// True to draw the default Broacast control UI. + /// + public bool showGUI + { + get { return m_ShowGUI; } + set { m_ShowGUI = value; } + } + + /// + /// The horizontal offset of the GUI if active. + /// + public int offsetX + { + get { return m_OffsetX; } + set { m_OffsetX = value; } + } + + /// + /// The vertical offset of the GUI if active. + /// + public int offsetY + { + get { return m_OffsetY; } + set { m_OffsetY = value; } + } + + /// + /// The TransportLayer hostId being used (read-only). + /// + public int hostId + { + get { return m_HostId; } + set { m_HostId = value; } + } + + /// + /// True is broadcasting or listening (read-only). + /// + public bool running + { + get { return m_Running; } + set { m_Running = value; } + } + + /// + /// True if running in server mode (read-only). + /// + public bool isServer + { + get { return m_IsServer; } + set { m_IsServer = value; } + } + + /// + /// True if running in client mode (read-only). + /// + public bool isClient + { + get { return m_IsClient; } + set { m_IsClient = value; } + } + + /// + /// A dictionary of broadcasts received from servers. + /// The key is the server address, and the value is a NetworkBroadcastResult object that contains the data sent by the server. + /// + public Dictionary broadcastsReceived + { + get { return m_BroadcastsReceived; } + } + + static byte[] StringToBytes(string str) + { + byte[] bytes = new byte[str.Length * sizeof(char)]; + Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length); + return bytes; + } + + static string BytesToString(byte[] bytes) + { + char[] chars = new char[bytes.Length / sizeof(char)]; + Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length); + return new string(chars); + } + + /// + /// Initializes the NetworkDiscovery component. + /// + /// Return true if the network port was available. + public bool Initialize() + { + if (m_BroadcastData.Length >= k_MaxBroadcastMsgSize) + { + if (LogFilter.logError) { Debug.LogError("NetworkDiscovery Initialize - data too large. max is " + k_MaxBroadcastMsgSize); } + return false; + } + + if (!NetworkManager.activeTransport.IsStarted) + { + NetworkManager.activeTransport.Init(); + } + + if (m_UseNetworkManager && NetworkManager.singleton != null) + { + m_BroadcastData = "NetworkManager:" + NetworkManager.singleton.networkAddress + ":" + NetworkManager.singleton.networkPort; + if (LogFilter.logInfo) { Debug.Log("NetworkDiscovery set broadcast data to:" + m_BroadcastData); } + } + + m_MsgOutBuffer = StringToBytes(m_BroadcastData); + m_MsgInBuffer = new byte[k_MaxBroadcastMsgSize]; + m_BroadcastsReceived = new Dictionary(); + + ConnectionConfig cc = new ConnectionConfig(); + cc.AddChannel(QosType.Unreliable); + m_DefaultTopology = new HostTopology(cc, 1); + + if (m_IsServer) + StartAsServer(); + + if (m_IsClient) + StartAsClient(); + + return true; + } + + /// + /// Starts listening for broadcasts messages. + /// + /// True is able to listen. + // listen for broadcasts + public bool StartAsClient() + { + if (m_HostId != -1 || m_Running) + { + if (LogFilter.logWarn) { Debug.LogWarning("NetworkDiscovery StartAsClient already started"); } + return false; + } + + if (m_MsgInBuffer == null) + { + if (LogFilter.logError) { Debug.LogError("NetworkDiscovery StartAsClient, NetworkDiscovery is not initialized"); } + return false; + } + + m_HostId = NetworkManager.activeTransport.AddHost(m_DefaultTopology, m_BroadcastPort, null); + if (m_HostId == -1) + { + if (LogFilter.logError) { Debug.LogError("NetworkDiscovery StartAsClient - addHost failed"); } + return false; + } + + NetworkTransport.SetMulticastLock(true); + + byte error; + NetworkManager.activeTransport.SetBroadcastCredentials(m_HostId, m_BroadcastKey, m_BroadcastVersion, m_BroadcastSubVersion, out error); + + m_Running = true; + m_IsClient = true; + if (LogFilter.logDebug) { Debug.Log("StartAsClient Discovery listening"); } + return true; + } + + /// + /// Starts sending broadcast messages. + /// + /// True is able to broadcast. + // perform actual broadcasts + public bool StartAsServer() + { + if (m_HostId != -1 || m_Running) + { + if (LogFilter.logWarn) { Debug.LogWarning("NetworkDiscovery StartAsServer already started"); } + return false; + } + + m_HostId = NetworkManager.activeTransport.AddHost(m_DefaultTopology, 0, null); + if (m_HostId == -1) + { + if (LogFilter.logError) { Debug.LogError("NetworkDiscovery StartAsServer - addHost failed"); } + return false; + } + + NetworkTransport.SetMulticastLock(true); + + byte err; + if (!NetworkManager.activeTransport.StartBroadcastDiscovery(m_HostId, m_BroadcastPort, m_BroadcastKey, m_BroadcastVersion, m_BroadcastSubVersion, m_MsgOutBuffer, m_MsgOutBuffer.Length, m_BroadcastInterval, out err)) + { + NetworkTransport.RemoveHost(m_HostId); + m_HostId = -1; + if (LogFilter.logError) { Debug.LogError("NetworkDiscovery StartBroadcast failed err: " + err); } + return false; + } + + m_Running = true; + m_IsServer = true; + if (LogFilter.logDebug) { Debug.Log("StartAsServer Discovery broadcasting"); } + DontDestroyOnLoad(gameObject); + return true; + } + + /// + /// Stops listening and broadcasting. + /// + public void StopBroadcast() + { + if (m_HostId == -1) + { + if (LogFilter.logError) { Debug.LogError("NetworkDiscovery StopBroadcast not initialized"); } + return; + } + + if (!m_Running) + { + Debug.LogWarning("NetworkDiscovery StopBroadcast not started"); + return; + } + if (m_IsServer) + { + NetworkManager.activeTransport.StopBroadcastDiscovery(); + } + + NetworkManager.activeTransport.RemoveHost(m_HostId); + NetworkTransport.SetMulticastLock(false); + m_HostId = -1; + m_Running = false; + m_IsServer = false; + m_IsClient = false; + m_MsgInBuffer = null; + m_BroadcastsReceived = null; + if (LogFilter.logDebug) { Debug.Log("Stopped Discovery broadcasting"); } + } + + void Update() + { + if (m_HostId == -1) + return; + + if (m_IsServer) + return; + + NetworkEventType networkEvent; + do + { + int connectionId; + int channelId; + int receivedSize; + byte error; + networkEvent = NetworkManager.activeTransport.ReceiveFromHost(m_HostId, out connectionId, out channelId, m_MsgInBuffer, k_MaxBroadcastMsgSize, out receivedSize, out error); + + if (networkEvent == NetworkEventType.BroadcastEvent) + { + NetworkManager.activeTransport.GetBroadcastConnectionMessage(m_HostId, m_MsgInBuffer, k_MaxBroadcastMsgSize, out receivedSize, out error); + + string senderAddr; + int senderPort; + NetworkManager.activeTransport.GetBroadcastConnectionInfo(m_HostId, out senderAddr, out senderPort, out error); + + var recv = new NetworkBroadcastResult(); + recv.serverAddress = senderAddr; + recv.broadcastData = new byte[receivedSize]; + Buffer.BlockCopy(m_MsgInBuffer, 0, recv.broadcastData, 0, receivedSize); + m_BroadcastsReceived[senderAddr] = recv; + + OnReceivedBroadcast(senderAddr, BytesToString(m_MsgInBuffer)); + } + } + while (networkEvent != NetworkEventType.Nothing); + } + + void OnDestroy() + { + if (m_IsServer && m_Running && m_HostId != -1) + { + NetworkManager.activeTransport.StopBroadcastDiscovery(); + NetworkManager.activeTransport.RemoveHost(m_HostId); + } + + if (m_IsClient && m_Running && m_HostId != -1) + { + NetworkManager.activeTransport.RemoveHost(m_HostId); + } + + if (m_Running) + NetworkTransport.SetMulticastLock(false); + } + + /// + /// This is a virtual function that can be implemented to handle broadcast messages when running as a client. + /// + /// The IP address of the server. + /// The data broadcast by the server. + public virtual void OnReceivedBroadcast(string fromAddress, string data) + { + //Debug.Log("Got broadcast from [" + fromAddress + "] " + data); + } + + void OnGUI() + { + if (!m_ShowGUI) + return; + + int xpos = 10 + m_OffsetX; + int ypos = 40 + m_OffsetY; + const int spacing = 24; + + if (UnityEngine.Application.platform == RuntimePlatform.WebGLPlayer) + { + GUI.Box(new Rect(xpos, ypos, 200, 20), "( WebGL cannot broadcast )"); + return; + } + + if (m_MsgInBuffer == null) + { + if (GUI.Button(new Rect(xpos, ypos, 200, 20), "Initialize Broadcast")) + { + Initialize(); + } + return; + } + string suffix = ""; + if (m_IsServer) + suffix = " (server)"; + if (m_IsClient) + suffix = " (client)"; + + GUI.Label(new Rect(xpos, ypos, 200, 20), "initialized" + suffix); + ypos += spacing; + + if (m_Running) + { + if (GUI.Button(new Rect(xpos, ypos, 200, 20), "Stop")) + { + StopBroadcast(); + } + ypos += spacing; + + if (m_BroadcastsReceived != null) + { + foreach (var addr in m_BroadcastsReceived.Keys) + { + var value = m_BroadcastsReceived[addr]; + if (GUI.Button(new Rect(xpos, ypos + 20, 200, 20), "Game at " + addr) && m_UseNetworkManager) + { + string dataString = BytesToString(value.broadcastData); + var items = dataString.Split(':'); + if (items.Length == 3 && items[0] == "NetworkManager") + { + if (NetworkManager.singleton != null && NetworkManager.singleton.client == null) + { + NetworkManager.singleton.networkAddress = items[1]; + NetworkManager.singleton.networkPort = Convert.ToInt32(items[2]); + NetworkManager.singleton.StartClient(); + } + } + } + ypos += spacing; + } + } + } + else + { + if (GUI.Button(new Rect(xpos, ypos, 200, 20), "Start Broadcasting")) + { + StartAsServer(); + } + ypos += spacing; + + if (GUI.Button(new Rect(xpos, ypos, 200, 20), "Listen for Broadcast")) + { + StartAsClient(); + } + ypos += spacing; + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkHash128.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkHash128.cs new file mode 100644 index 00000000..bc6cf2e4 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkHash128.cs @@ -0,0 +1,140 @@ +using System; + +namespace UnityEngine.Networking +{ + /// + /// A 128 bit number used to represent assets in a networking context. + /// + // unrolled for your pleasure. + [Serializable] + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public struct NetworkHash128 + { + // struct cannot have embedded arrays.. + public byte i0; + public byte i1; + public byte i2; + public byte i3; + public byte i4; + public byte i5; + public byte i6; + public byte i7; + public byte i8; + public byte i9; + public byte i10; + public byte i11; + public byte i12; + public byte i13; + public byte i14; + public byte i15; + + /// + /// Resets the value of a NetworkHash to zero (invalid). + /// + public void Reset() + { + i0 = 0; + i1 = 0; + i2 = 0; + i3 = 0; + i4 = 0; + i5 = 0; + i6 = 0; + i7 = 0; + i8 = 0; + i9 = 0; + i10 = 0; + i11 = 0; + i12 = 0; + i13 = 0; + i14 = 0; + i15 = 0; + } + + /// + /// A valid NetworkHash has a non-zero value. + /// + /// True if the value is non-zero. + public bool IsValid() + { + return (i0 | i1 | i2 | i3 | i4 | i5 | i6 | i7 | i8 | i9 | i10 | i11 | i12 | i13 | i14 | i15) != 0; + } + + static int HexToNumber(char c) + { + if (c >= '0' && c <= '9') + return c - '0'; + if (c >= 'a' && c <= 'f') + return c - 'a' + 10; + if (c >= 'A' && c <= 'F') + return c - 'A' + 10; + return 0; + } + + /// + /// This parses the string representation of a NetworkHash into a binary object. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// class HashTest : MonoBehaviour + /// { + /// const string assetString = "0176acd452adc180"; + /// NetworkHash128 assetId = NetworkHash128.Parse(assetString); + /// + /// void Start() + /// { + /// Debug.Log("asset:" + assetId); + /// } + /// } + /// + /// + /// A hex string to parse. + /// A 128 bit network hash object. + public static NetworkHash128 Parse(string text) + { + NetworkHash128 hash; + + // add leading zeros if required + int l = text.Length; + if (l < 32) + { + string tmp = ""; + for (int i = 0; i < 32 - l; i++) + { + tmp += "0"; + } + text = (tmp + text); + } + + hash.i0 = (byte)(HexToNumber(text[0]) * 16 + HexToNumber(text[1])); + hash.i1 = (byte)(HexToNumber(text[2]) * 16 + HexToNumber(text[3])); + hash.i2 = (byte)(HexToNumber(text[4]) * 16 + HexToNumber(text[5])); + hash.i3 = (byte)(HexToNumber(text[6]) * 16 + HexToNumber(text[7])); + hash.i4 = (byte)(HexToNumber(text[8]) * 16 + HexToNumber(text[9])); + hash.i5 = (byte)(HexToNumber(text[10]) * 16 + HexToNumber(text[11])); + hash.i6 = (byte)(HexToNumber(text[12]) * 16 + HexToNumber(text[13])); + hash.i7 = (byte)(HexToNumber(text[14]) * 16 + HexToNumber(text[15])); + hash.i8 = (byte)(HexToNumber(text[16]) * 16 + HexToNumber(text[17])); + hash.i9 = (byte)(HexToNumber(text[18]) * 16 + HexToNumber(text[19])); + hash.i10 = (byte)(HexToNumber(text[20]) * 16 + HexToNumber(text[21])); + hash.i11 = (byte)(HexToNumber(text[22]) * 16 + HexToNumber(text[23])); + hash.i12 = (byte)(HexToNumber(text[24]) * 16 + HexToNumber(text[25])); + hash.i13 = (byte)(HexToNumber(text[26]) * 16 + HexToNumber(text[27])); + hash.i14 = (byte)(HexToNumber(text[28]) * 16 + HexToNumber(text[29])); + hash.i15 = (byte)(HexToNumber(text[30]) * 16 + HexToNumber(text[31])); + + return hash; + } + + /// + /// Returns a string representation of a NetworkHash object. + /// + /// A hex asset string. + public override string ToString() + { + return String.Format("{0:x2}{1:x2}{2:x2}{3:x2}{4:x2}{5:x2}{6:x2}{7:x2}{8:x2}{9:x2}{10:x2}{11:x2}{12:x2}{13:x2}{14:x2}{15:x2}", + i0, i1, i2, i3, i4, i5, i6, i7, i8, i9, i10, i11, i12, i13, i14, i15); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkIdentity.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkIdentity.cs new file mode 100644 index 00000000..0bd6ec00 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkIdentity.cs @@ -0,0 +1,1253 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using UnityEngine.Networking.NetworkSystem; + +#if UNITY_EDITOR +using UnityEditor; +#endif + +namespace UnityEngine.Networking +{ + /// + /// The NetworkIdentity identifies objects across the network, between server and clients. Its primary data is a NetworkInstanceId which is allocated by the server and then set on clients. This is used in network communications to be able to lookup game objects on different machines. + /// The NetworkIdentity is used to synchronize information in the object with the network. Only the server should create instances of objects which have NetworkIdentity as otherwise they will not be properly connected to the system. + /// For complex objects with a hierarchy of subcomponents, the NetworkIdentity must be on the root of the hierarchy. It is not supported to have multiple NetworkIdentity components on subcomponents of a hierarchy. + /// NetworkBehaviour scripts require a NetworkIdentity on the game object to be able to function. + /// The NetworkIdentity manages the dirty state of the NetworkBehaviours of the object. When it discovers that NetworkBehaviours are dirty, it causes an update packet to be created and sent to clients. + /// The flow for serialization updates managed by the NetworkIdentity is: + /// * Each NetworkBehaviour has a dirty mask. This mask is available inside OnSerialize as syncVarDirtyBits + /// * Each SyncVar in a NetworkBehaviour script is assigned a bit in the dirty mask. + /// * Changing the value of SyncVars causes the bit for that SyncVar to be set in the dirty mask + /// * Alternatively, calling SetDirtyBit() writes directly to the dirty mask + /// * NetworkIdentity objects are checked on the server as part of it's update loop + /// * If any NetworkBehaviours on a NetworkIdentity are dirty, then an UpdateVars packet is created for that object + /// * The UpdateVars packet is populated by calling OnSerialize on each NetworkBehaviour on the object + /// * NetworkBehaviours that are NOT dirty write a zero to the packet for their dirty bits + /// * NetworkBehaviours that are dirty write their dirty mask, then the values for the SyncVars that have changed + /// * If OnSerialize returns true for a NetworkBehaviour, the dirty mask is reset for that NetworkBehaviour, so it will not send again until its value changes. + /// * The UpdateVars packet is sent to ready clients that are observing the object + /// On the client: + /// * an UpdateVars packet is received for an object + /// * The OnDeserialize function is called for each NetworkBehaviour script on the object + /// * Each NetworkBehaviour script on the object reads a dirty mask. + /// * If the dirty mask for a NetworkBehaviour is zero, the OnDeserialize functions returns without reading any more + /// * If the dirty mask is non-zero value, then the OnDeserialize function reads the values for the SyncVars that correspond to the dirty bits that are set + /// * If there are SyncVar hook functions, those are invoked with the value read from the stream. + /// + [ExecuteInEditMode] + [DisallowMultipleComponent] + [AddComponentMenu("Network/NetworkIdentity")] + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public sealed class NetworkIdentity : MonoBehaviour + { + // configuration + [SerializeField] NetworkSceneId m_SceneId; + [SerializeField] NetworkHash128 m_AssetId; + [SerializeField] bool m_ServerOnly; + [SerializeField] bool m_LocalPlayerAuthority; + + // runtime data + bool m_IsClient; + bool m_IsServer; + bool m_HasAuthority; + + NetworkInstanceId m_NetId; + bool m_IsLocalPlayer; + NetworkConnection m_ConnectionToServer; + NetworkConnection m_ConnectionToClient; + short m_PlayerId = -1; + NetworkBehaviour[] m_NetworkBehaviours; + + // there is a list AND a hashSet of connections, for fast verification of dupes, but the main operation is iteration over the list. + HashSet m_ObserverConnections; + List m_Observers; + NetworkConnection m_ClientAuthorityOwner; + + // member used to mark a identity for future reset + // check MarkForReset for more information. + bool m_Reset = false; + // properties + /// + /// Returns true if running as a client and this object was spawned by a server. + /// + public bool isClient { get { return m_IsClient; } } + + /// + /// Returns true if running as a server, which spawned the object. + /// + public bool isServer + { + get + { + // if server has stopped, should not still return true here + return m_IsServer && NetworkServer.active; + } + } + + /// + /// This returns true if this object is the authoritative version of the object in the distributed network application. + /// This value is determined at runtime, as opposed to localPlayerAuthority which is set on the prefab. For most objects, authority is held by the server / host. For objects with localPlayerAuthority set, authority is held by the client of that player. + /// For objects that had their authority set by AssignClientAuthority on the server, this will be true on the client that owns the object. NOT on other clients. + /// + public bool hasAuthority { get { return m_HasAuthority; } } + + /// + /// Unique identifier for this particular object instance, used for tracking objects between networked clients and the server. + /// This is a unique identifier for this particular GameObject instance. Use it to track GameObjects between networked clients and the server. + /// + /// //For this example to work, attach a NetworkIdentity component to your GameObject. + /// //Then, create a new empty GameObject and drag it under your NetworkIdentity GameObject in the Hierarchy. This makes it the child of the GameObject. //Next, attach a TextMesh component to the child GameObject. You can then place this TextMesh GameObject to be above your GameObject in the Scene. + /// //Attach this script to the parent GameObject, and it changes the text of the TextMesh to the identity of your GameObject. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class NetworkIdentityNetID : MonoBehaviour + /// { + /// NetworkIdentity m_Identity; + /// //This is a TextMesh component that you attach to the child of the NetworkIdentity GameObject + /// TextMesh m_TextMesh; + /// + /// void Start() + /// { + /// //Fetch the NetworkIdentity component of the GameObject + /// m_Identity = GetComponent<NetworkIdentity>(); + /// //Enter the child of your GameObject (the GameObject with the TextMesh you attach) + /// //Fetch the TextMesh component of it + /// m_TextMesh = GetComponentInChildren(typeof(TextMesh)) as TextMesh; + /// //Change the Text of the TextMesh to show the netId + /// m_TextMesh.text = "ID : " + m_Identity.netId; + /// } + /// } + /// + /// + public NetworkInstanceId netId { get { return m_NetId; } } + /// + /// A unique identifier for NetworkIdentity objects within a scene. + /// This is used for spawning scene objects on clients. + /// + public NetworkSceneId sceneId { get { return m_SceneId; } } + /// + /// Flag to make this object only exist when the game is running as a server (or host). + /// + public bool serverOnly { get { return m_ServerOnly; } set { m_ServerOnly = value; } } + /// + /// localPlayerAuthority means that the client of the "owning" player has authority over their own player object. + /// Authority for this object will be on the player's client. So hasAuthority will be true on that client - and false on the server and on other clients. + /// + public bool localPlayerAuthority { get { return m_LocalPlayerAuthority; } set { m_LocalPlayerAuthority = value; } } + /// + /// The client that has authority for this object. This will be null if no client has authority. + /// This is set for player objects with localPlayerAuthority, and for objects set with AssignClientAuthority, and spawned with SpawnWithClientAuthority. + /// + public NetworkConnection clientAuthorityOwner { get { return m_ClientAuthorityOwner; }} + + /// + /// Unique identifier used to find the source assets when server spawns the on clients. + /// + public NetworkHash128 assetId + { + get + { +#if UNITY_EDITOR + // This is important because sometimes OnValidate does not run (like when adding view to prefab with no child links) + if (!m_AssetId.IsValid()) + SetupIDs(); +#endif + return m_AssetId; + } + } + internal void SetDynamicAssetId(NetworkHash128 newAssetId) + { + if (!m_AssetId.IsValid() || m_AssetId.Equals(newAssetId)) + { + m_AssetId = newAssetId; + } + else + { + if (LogFilter.logWarn) { Debug.LogWarning("SetDynamicAssetId object already has an assetId <" + m_AssetId + ">"); } + } + } + + // used when adding players + internal void SetClientOwner(NetworkConnection conn) + { + if (m_ClientAuthorityOwner != null) + { + if (LogFilter.logError) { Debug.LogError("SetClientOwner m_ClientAuthorityOwner already set!"); } + } + m_ClientAuthorityOwner = conn; + m_ClientAuthorityOwner.AddOwnedObject(this); + } + + // used during dispose after disconnect + internal void ClearClientOwner() + { + m_ClientAuthorityOwner = null; + } + + internal void ForceAuthority(bool authority) + { + if (m_HasAuthority == authority) + { + return; + } + + m_HasAuthority = authority; + if (authority) + { + OnStartAuthority(); + } + else + { + OnStopAuthority(); + } + } + + /// + /// This returns true if this object is the one that represents the player on the local machine. + /// This is set when the server has spawned an object for this particular client. + /// + public bool isLocalPlayer { get { return m_IsLocalPlayer; } } + /// + /// The id of the player associated with this GameObject. + /// This is only valid if this GameObject is for a local player. + /// The HLAPI treats players and clients as separate GameObjects. In most cases, there is a single player for each client, but in some situations (for example, when there are multiple controllers connected to a console system) there might be multiple player GameObjects for a single connection. When there are multiple players for a single connection, use the playerControllerId property to tell them apart. This is an identifier that is scoped to the connection, so that it maps to the id of the controller associated with the player on that client. + /// + public short playerControllerId { get { return m_PlayerId; } } + /// + /// The UConnection associated with this NetworkIdentity. This is only valid for player objects on a local client. + /// + public NetworkConnection connectionToServer { get { return m_ConnectionToServer; } } + /// + /// The connection associated with this NetworkIdentity. This is only valid for player objects on the server. + /// Use it to return details such as the connection's identity, IP address and ready status. + /// + /// //For this example to work, attach a NetworkIdentity component to your GameObject. + /// //Make sure your Scene has a NetworkManager and NetworkManagerHUD + /// //Attach this script to the GameObject, and it outputs the connection of your GameObject to the console. + /// + /// using System.Collections; + /// using System.Collections.Generic; + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class NetworkIdentityNetID : MonoBehaviour + /// { + /// NetworkIdentity m_Identity; + /// //This is a TextMesh component that you attach to the child of the NetworkIdentity GameObject + /// + /// void Start() + /// { + /// //Fetch the NetworkIdentity component of the GameObject + /// m_Identity = GetComponent<NetworkIdentity>(); + /// //Output to the console the connection associated with this NetworkIdentity + /// Debug.Log("Connection : " + m_Identity.connectionToClient); + /// } + /// } + /// + /// + public NetworkConnection connectionToClient { get { return m_ConnectionToClient; } } + + /// + /// The set of network connections (players) that can see this object. + /// + public ReadOnlyCollection observers + { + get + { + if (m_Observers == null) + return null; + + return new ReadOnlyCollection(m_Observers); + } + } + + static uint s_NextNetworkId = 1; + static internal NetworkInstanceId GetNextNetworkId() + { + uint newId = s_NextNetworkId; + s_NextNetworkId += 1; + return new NetworkInstanceId(newId); + } + + static NetworkWriter s_UpdateWriter = new NetworkWriter(); + + void CacheBehaviours() + { + if (m_NetworkBehaviours == null) + { + m_NetworkBehaviours = GetComponents(); + } + } + + /// + /// The delegate type for the clientAuthorityCallback. + /// + /// The network connection that is gaining or losing authority. + /// The object whose client authority status is being changed. + /// The new state of client authority of the object for the connection. + public delegate void ClientAuthorityCallback(NetworkConnection conn, NetworkIdentity uv, bool authorityState); + /// + /// A callback that can be populated to be notified when the client-authority state of objects changes. + /// Whenever an object is spawned using SpawnWithClientAuthority, or the client authority status of an object is changed with AssignClientAuthority or RemoveClientAuthority, then this callback will be invoked. + /// This callback is used by the NetworkMigrationManager to distribute client authority state to peers for host migration. If the NetworkMigrationManager is not being used, this callback does not need to be populated. + /// + public static ClientAuthorityCallback clientAuthorityCallback; + + static internal void AddNetworkId(uint id) + { + if (id >= s_NextNetworkId) + { + s_NextNetworkId = (uint)(id + 1); + } + } + + // only used during spawning on clients to set the identity. + internal void SetNetworkInstanceId(NetworkInstanceId newNetId) + { + m_NetId = newNetId; + if (newNetId.Value == 0) + { + m_IsServer = false; + } + } + + /// + /// Force the scene ID to a specific value. + /// This can be used to fix an invalid scene ID. If you process all the NetworkIdentity components in a scene you can assign them new values starting from 1. + /// + /// The new scene ID. + // only used when fixing duplicate scene IDs duing post-processing + public void ForceSceneId(int newSceneId) + { + m_SceneId = new NetworkSceneId((uint)newSceneId); + } + + // only used in SetLocalObject + internal void UpdateClientServer(bool isClientFlag, bool isServerFlag) + { + m_IsClient |= isClientFlag; + m_IsServer |= isServerFlag; + } + + // used when the player object for a connection changes + internal void SetNotLocalPlayer() + { + m_IsLocalPlayer = false; + + if (NetworkServer.active && NetworkServer.localClientActive) + { + // dont change authority for objects on the host + return; + } + m_HasAuthority = false; + } + + // this is used when a connection is destroyed, since the "observers" property is read-only + internal void RemoveObserverInternal(NetworkConnection conn) + { + if (m_Observers != null) + { + m_Observers.Remove(conn); + m_ObserverConnections.Remove(conn.connectionId); + } + } + +#if UNITY_EDITOR + void OnValidate() + { + if (m_ServerOnly && m_LocalPlayerAuthority) + { + if (LogFilter.logWarn) { Debug.LogWarning("Disabling Local Player Authority for " + gameObject + " because it is server-only."); } + m_LocalPlayerAuthority = false; + } + + SetupIDs(); + } + + void AssignAssetID(GameObject prefab) + { + string path = AssetDatabase.GetAssetPath(prefab); + m_AssetId = NetworkHash128.Parse(AssetDatabase.AssetPathToGUID(path)); + } + + bool ThisIsAPrefab() + { + return PrefabUtility.IsPartOfPrefabAsset(gameObject); + } + + bool ThisIsASceneObjectWithThatReferencesPrefabAsset(out GameObject prefab) + { + prefab = null; + if (!PrefabUtility.IsPartOfNonAssetPrefabInstance(gameObject)) + return false; + prefab = (GameObject)PrefabUtility.GetCorrespondingObjectFromSource(gameObject); + if (prefab == null) + { + if (LogFilter.logError) { Debug.LogError("Failed to find prefab parent for scene object [name:" + gameObject.name + "]"); } + return false; + } + return true; + } + + void SetupIDs() + { + GameObject prefab; + if (ThisIsAPrefab()) + { + ForceSceneId(0); + AssignAssetID(gameObject); + } + else if (ThisIsASceneObjectWithThatReferencesPrefabAsset(out prefab)) + { + AssignAssetID(prefab); + } + else + { + m_AssetId.Reset(); + } + } + +#endif + void OnDestroy() + { + if (m_IsServer && NetworkServer.active) + { + NetworkServer.Destroy(gameObject); + } + } + + internal void OnStartServer(bool allowNonZeroNetId) + { + if (m_IsServer) + { + return; + } + m_IsServer = true; + + if (m_LocalPlayerAuthority) + { + // local player on server has NO authority + m_HasAuthority = false; + } + else + { + // enemy on server has authority + m_HasAuthority = true; + } + + m_Observers = new List(); + m_ObserverConnections = new HashSet(); + CacheBehaviours(); + + // If the instance/net ID is invalid here then this is an object instantiated from a prefab and the server should assign a valid ID + if (netId.IsEmpty()) + { + m_NetId = GetNextNetworkId(); + } + else + { + if (allowNonZeroNetId) + { + //allowed + } + else + { + if (LogFilter.logError) { Debug.LogError("Object has non-zero netId " + netId + " for " + gameObject); } + return; + } + } + + if (LogFilter.logDev) { Debug.Log("OnStartServer " + gameObject + " GUID:" + netId); } + NetworkServer.instance.SetLocalObjectOnServer(netId, gameObject); + + for (int i = 0; i < m_NetworkBehaviours.Length; i++) + { + NetworkBehaviour comp = m_NetworkBehaviours[i]; + try + { + comp.OnStartServer(); + } + catch (Exception e) + { + Debug.LogError("Exception in OnStartServer:" + e.Message + " " + e.StackTrace); + } + } + + if (NetworkClient.active && NetworkServer.localClientActive) + { + // there will be no spawn message, so start the client here too + ClientScene.SetLocalObject(netId, gameObject); + OnStartClient(); + } + + if (m_HasAuthority) + { + OnStartAuthority(); + } + } + + internal void OnStartClient() + { + if (!m_IsClient) + { + m_IsClient = true; + } + CacheBehaviours(); + + if (LogFilter.logDev) { Debug.Log("OnStartClient " + gameObject + " GUID:" + netId + " localPlayerAuthority:" + localPlayerAuthority); } + for (int i = 0; i < m_NetworkBehaviours.Length; i++) + { + NetworkBehaviour comp = m_NetworkBehaviours[i]; + try + { + comp.PreStartClient(); // generated startup to resolve object references + comp.OnStartClient(); // user implemented startup + } + catch (Exception e) + { + Debug.LogError("Exception in OnStartClient:" + e.Message + " " + e.StackTrace); + } + } + } + + internal void OnStartAuthority() + { + for (int i = 0; i < m_NetworkBehaviours.Length; i++) + { + NetworkBehaviour comp = m_NetworkBehaviours[i]; + try + { + comp.OnStartAuthority(); + } + catch (Exception e) + { + Debug.LogError("Exception in OnStartAuthority:" + e.Message + " " + e.StackTrace); + } + } + } + + internal void OnStopAuthority() + { + for (int i = 0; i < m_NetworkBehaviours.Length; i++) + { + NetworkBehaviour comp = m_NetworkBehaviours[i]; + try + { + comp.OnStopAuthority(); + } + catch (Exception e) + { + Debug.LogError("Exception in OnStopAuthority:" + e.Message + " " + e.StackTrace); + } + } + } + + internal void OnSetLocalVisibility(bool vis) + { + for (int i = 0; i < m_NetworkBehaviours.Length; i++) + { + NetworkBehaviour comp = m_NetworkBehaviours[i]; + try + { + comp.OnSetLocalVisibility(vis); + } + catch (Exception e) + { + Debug.LogError("Exception in OnSetLocalVisibility:" + e.Message + " " + e.StackTrace); + } + } + } + + internal bool OnCheckObserver(NetworkConnection conn) + { + for (int i = 0; i < m_NetworkBehaviours.Length; i++) + { + NetworkBehaviour comp = m_NetworkBehaviours[i]; + try + { + if (!comp.OnCheckObserver(conn)) + return false; + } + catch (Exception e) + { + Debug.LogError("Exception in OnCheckObserver:" + e.Message + " " + e.StackTrace); + } + } + return true; + } + + // happens on server + internal void UNetSerializeAllVars(NetworkWriter writer) + { + for (int i = 0; i < m_NetworkBehaviours.Length; i++) + { + NetworkBehaviour comp = m_NetworkBehaviours[i]; + comp.OnSerialize(writer, true); + } + } + + // happens on client + internal void HandleClientAuthority(bool authority) + { + if (!localPlayerAuthority) + { + if (LogFilter.logError) { Debug.LogError("HandleClientAuthority " + gameObject + " does not have localPlayerAuthority"); } + return; + } + + ForceAuthority(authority); + } + + // helper function for Handle** functions + bool GetInvokeComponent(int cmdHash, Type invokeClass, out NetworkBehaviour invokeComponent) + { + // dont use GetComponent(), already have a list - avoids an allocation + NetworkBehaviour foundComp = null; + for (int i = 0; i < m_NetworkBehaviours.Length; i++) + { + var comp = m_NetworkBehaviours[i]; + if (comp.GetType() == invokeClass || comp.GetType().IsSubclassOf(invokeClass)) + { + // found matching class + foundComp = comp; + break; + } + } + if (foundComp == null) + { + string errorCmdName = NetworkBehaviour.GetCmdHashHandlerName(cmdHash); + if (LogFilter.logError) { Debug.LogError("Found no behaviour for incoming [" + errorCmdName + "] on " + gameObject + ", the server and client should have the same NetworkBehaviour instances [netId=" + netId + "]."); } + invokeComponent = null; + return false; + } + invokeComponent = foundComp; + return true; + } + + // happens on client + internal void HandleSyncEvent(int cmdHash, NetworkReader reader) + { + // this doesn't use NetworkBehaviour.InvokeSyncEvent function (anymore). this method of calling is faster. + // The hash is only looked up once, insted of twice(!) per NetworkBehaviour on the object. + + if (gameObject == null) + { + string errorCmdName = NetworkBehaviour.GetCmdHashHandlerName(cmdHash); + if (LogFilter.logWarn) { Debug.LogWarning("SyncEvent [" + errorCmdName + "] received for deleted object [netId=" + netId + "]"); } + return; + } + + // find the matching SyncEvent function and networkBehaviour class + NetworkBehaviour.CmdDelegate invokeFunction; + Type invokeClass; + bool invokeFound = NetworkBehaviour.GetInvokerForHashSyncEvent(cmdHash, out invokeClass, out invokeFunction); + if (!invokeFound) + { + // We don't get a valid lookup of the command name when it doesn't exist... + string errorCmdName = NetworkBehaviour.GetCmdHashHandlerName(cmdHash); + if (LogFilter.logError) { Debug.LogError("Found no receiver for incoming [" + errorCmdName + "] on " + gameObject + ", the server and client should have the same NetworkBehaviour instances [netId=" + netId + "]."); } + return; + } + + // find the right component to invoke the function on + NetworkBehaviour invokeComponent; + if (!GetInvokeComponent(cmdHash, invokeClass, out invokeComponent)) + { + string errorCmdName = NetworkBehaviour.GetCmdHashHandlerName(cmdHash); + if (LogFilter.logWarn) { Debug.LogWarning("SyncEvent [" + errorCmdName + "] handler not found [netId=" + netId + "]"); } + return; + } + + invokeFunction(invokeComponent, reader); + +#if UNITY_EDITOR + Profiler.IncrementStatIncoming(MsgType.SyncEvent, NetworkBehaviour.GetCmdHashEventName(cmdHash)); +#endif + } + + // happens on client + internal void HandleSyncList(int cmdHash, NetworkReader reader) + { + // this doesn't use NetworkBehaviour.InvokSyncList function (anymore). this method of calling is faster. + // The hash is only looked up once, insted of twice(!) per NetworkBehaviour on the object. + + if (gameObject == null) + { + string errorCmdName = NetworkBehaviour.GetCmdHashHandlerName(cmdHash); + if (LogFilter.logWarn) { Debug.LogWarning("SyncList [" + errorCmdName + "] received for deleted object [netId=" + netId + "]"); } + return; + } + + // find the matching SyncList function and networkBehaviour class + NetworkBehaviour.CmdDelegate invokeFunction; + Type invokeClass; + bool invokeFound = NetworkBehaviour.GetInvokerForHashSyncList(cmdHash, out invokeClass, out invokeFunction); + if (!invokeFound) + { + // We don't get a valid lookup of the command name when it doesn't exist... + string errorCmdName = NetworkBehaviour.GetCmdHashHandlerName(cmdHash); + if (LogFilter.logError) { Debug.LogError("Found no receiver for incoming [" + errorCmdName + "] on " + gameObject + ", the server and client should have the same NetworkBehaviour instances [netId=" + netId + "]."); } + return; + } + + // find the right component to invoke the function on + NetworkBehaviour invokeComponent; + if (!GetInvokeComponent(cmdHash, invokeClass, out invokeComponent)) + { + string errorCmdName = NetworkBehaviour.GetCmdHashHandlerName(cmdHash); + if (LogFilter.logWarn) { Debug.LogWarning("SyncList [" + errorCmdName + "] handler not found [netId=" + netId + "]"); } + return; + } + + invokeFunction(invokeComponent, reader); + +#if UNITY_EDITOR + Profiler.IncrementStatIncoming(MsgType.SyncList, NetworkBehaviour.GetCmdHashListName(cmdHash)); +#endif + } + + // happens on server + internal void HandleCommand(int cmdHash, NetworkReader reader) + { + // this doesn't use NetworkBehaviour.InvokeCommand function (anymore). this method of calling is faster. + // The hash is only looked up once, insted of twice(!) per NetworkBehaviour on the object. + + if (gameObject == null) + { + string errorCmdName = NetworkBehaviour.GetCmdHashHandlerName(cmdHash); + if (LogFilter.logWarn) { Debug.LogWarning("Command [" + errorCmdName + "] received for deleted object [netId=" + netId + "]"); } + return; + } + + // find the matching Command function and networkBehaviour class + NetworkBehaviour.CmdDelegate invokeFunction; + Type invokeClass; + bool invokeFound = NetworkBehaviour.GetInvokerForHashCommand(cmdHash, out invokeClass, out invokeFunction); + if (!invokeFound) + { + // We don't get a valid lookup of the command name when it doesn't exist... + string errorCmdName = NetworkBehaviour.GetCmdHashHandlerName(cmdHash); + if (LogFilter.logError) { Debug.LogError("Found no receiver for incoming [" + errorCmdName + "] on " + gameObject + ", the server and client should have the same NetworkBehaviour instances [netId=" + netId + "]."); } + return; + } + + // find the right component to invoke the function on + NetworkBehaviour invokeComponent; + if (!GetInvokeComponent(cmdHash, invokeClass, out invokeComponent)) + { + string errorCmdName = NetworkBehaviour.GetCmdHashHandlerName(cmdHash); + if (LogFilter.logWarn) { Debug.LogWarning("Command [" + errorCmdName + "] handler not found [netId=" + netId + "]"); } + return; + } + + invokeFunction(invokeComponent, reader); + +#if UNITY_EDITOR + Profiler.IncrementStatIncoming(MsgType.Command, NetworkBehaviour.GetCmdHashCmdName(cmdHash)); +#endif + } + + // happens on client + internal void HandleRPC(int cmdHash, NetworkReader reader) + { + // this doesn't use NetworkBehaviour.InvokeClientRpc function (anymore). this method of calling is faster. + // The hash is only looked up once, insted of twice(!) per NetworkBehaviour on the object. + + if (gameObject == null) + { + string errorCmdName = NetworkBehaviour.GetCmdHashHandlerName(cmdHash); + if (LogFilter.logWarn) { Debug.LogWarning("ClientRpc [" + errorCmdName + "] received for deleted object [netId=" + netId + "]"); } + return; + } + + // find the matching ClientRpc function and networkBehaviour class + NetworkBehaviour.CmdDelegate invokeFunction; + Type invokeClass; + bool invokeFound = NetworkBehaviour.GetInvokerForHashClientRpc(cmdHash, out invokeClass, out invokeFunction); + if (!invokeFound) + { + // We don't get a valid lookup of the command name when it doesn't exist... + string errorCmdName = NetworkBehaviour.GetCmdHashHandlerName(cmdHash); + if (LogFilter.logError) { Debug.LogError("Found no receiver for incoming [" + errorCmdName + "] on " + gameObject + ", the server and client should have the same NetworkBehaviour instances [netId=" + netId + "]."); } + return; + } + + // find the right component to invoke the function on + NetworkBehaviour invokeComponent; + if (!GetInvokeComponent(cmdHash, invokeClass, out invokeComponent)) + { + string errorCmdName = NetworkBehaviour.GetCmdHashHandlerName(cmdHash); + if (LogFilter.logWarn) { Debug.LogWarning("ClientRpc [" + errorCmdName + "] handler not found [netId=" + netId + "]"); } + return; + } + + invokeFunction(invokeComponent, reader); + +#if UNITY_EDITOR + Profiler.IncrementStatIncoming(MsgType.Rpc, NetworkBehaviour.GetCmdHashRpcName(cmdHash)); +#endif + } + + // invoked by unity runtime immediately after the regular "Update()" function. + public void UNetUpdate() + { + // check if any behaviours are ready to send + uint dirtyChannelBits = 0; + for (int i = 0; i < m_NetworkBehaviours.Length; i++) + { + NetworkBehaviour comp = m_NetworkBehaviours[i]; + int channelId = comp.GetDirtyChannel(); + if (channelId != -1) + { + dirtyChannelBits |= (uint)(1 << channelId); + } + } + if (dirtyChannelBits == 0) + return; + + for (int channelId = 0; channelId < NetworkServer.numChannels; channelId++) + { + if ((dirtyChannelBits & (uint)(1 << channelId)) != 0) + { + s_UpdateWriter.StartMessage(MsgType.UpdateVars); + s_UpdateWriter.Write(netId); + + bool wroteData = false; + short oldPos; + NetworkBehaviour[] behaviourOfSameChannel = GetBehavioursOfSameChannel(channelId, false); + for (int i = 0; i < behaviourOfSameChannel.Length; i++) + { + oldPos = s_UpdateWriter.Position; + NetworkBehaviour comp = behaviourOfSameChannel[i]; + + if (comp.OnSerialize(s_UpdateWriter, false)) + { + comp.ClearAllDirtyBits(); + +#if UNITY_EDITOR + Profiler.IncrementStatOutgoing(MsgType.UpdateVars, comp.GetType().Name); +#endif + + wroteData = true; + } + if (s_UpdateWriter.Position - oldPos > NetworkServer.maxPacketSize) + { + if (LogFilter.logWarn) { Debug.LogWarning("Large state update of " + (s_UpdateWriter.Position - oldPos) + " bytes for netId:" + netId + " from script:" + comp); } + } + } + + if (!wroteData) + { + // nothing to send.. this could be a script with no OnSerialize function setting dirty bits + continue; + } + + s_UpdateWriter.FinishMessage(); + NetworkServer.SendWriterToReady(gameObject, s_UpdateWriter, channelId); + } + } + } + + private NetworkBehaviour[] GetBehavioursOfSameChannel(int channelId, bool initialState) + { + List channels = new List(); + if (initialState && m_NetworkBehaviours == null) + { + m_NetworkBehaviours = GetComponents(); + return m_NetworkBehaviours; + } + for (int itr = 0; itr < m_NetworkBehaviours.Length; itr++) + { + NetworkBehaviour comp = m_NetworkBehaviours[itr]; + if (comp.GetNetworkChannel() == channelId) + { + channels.Add(comp); + } + } + return channels.ToArray(); + } + + internal void OnUpdateVars(NetworkReader reader, bool initialState, NetworkMessage netMsg) + { + NetworkBehaviour[] behaviourOfSameChannel = GetBehavioursOfSameChannel(netMsg.channelId, initialState); + for (int i = 0; i < behaviourOfSameChannel.Length; i++) + { + NetworkBehaviour comp = behaviourOfSameChannel[i]; + +#if UNITY_EDITOR + var oldReadPos = reader.Position; +#endif + comp.OnDeserialize(reader, initialState); +#if UNITY_EDITOR + if (reader.Position - oldReadPos > 1) + { + Profiler.IncrementStatIncoming(MsgType.UpdateVars, comp.GetType().Name); + } +#endif + } + } + + internal void SetLocalPlayer(short localPlayerControllerId) + { + m_IsLocalPlayer = true; + m_PlayerId = localPlayerControllerId; + + // there is an ordering issue here that originAuthority solves. OnStartAuthority should only be called if m_HasAuthority was false when this function began, + // or it will be called twice for this object. But that state is lost by the time OnStartAuthority is called below, so the original value is cached + // here to be checked below. + bool originAuthority = m_HasAuthority; + if (localPlayerAuthority) + { + m_HasAuthority = true; + } + + for (int i = 0; i < m_NetworkBehaviours.Length; i++) + { + NetworkBehaviour comp = m_NetworkBehaviours[i]; + comp.OnStartLocalPlayer(); + + if (localPlayerAuthority && !originAuthority) + { + comp.OnStartAuthority(); + } + } + } + + internal void SetConnectionToServer(NetworkConnection conn) + { + m_ConnectionToServer = conn; + } + + internal void SetConnectionToClient(NetworkConnection conn, short newPlayerControllerId) + { + m_PlayerId = newPlayerControllerId; + m_ConnectionToClient = conn; + } + + internal void OnNetworkDestroy() + { + for (int i = 0; + m_NetworkBehaviours != null && i < m_NetworkBehaviours.Length; + i++) + { + NetworkBehaviour comp = m_NetworkBehaviours[i]; + comp.OnNetworkDestroy(); + } + m_IsServer = false; + } + + internal void ClearObservers() + { + if (m_Observers != null) + { + int count = m_Observers.Count; + for (int i = 0; i < count; i++) + { + var c = m_Observers[i]; + c.RemoveFromVisList(this, true); + } + m_Observers.Clear(); + m_ObserverConnections.Clear(); + } + } + + internal void AddObserver(NetworkConnection conn) + { + if (m_Observers == null) + { + if (LogFilter.logError) { Debug.LogError("AddObserver for " + gameObject + " observer list is null"); } + return; + } + + // uses hashset for better-than-list-iteration lookup performance. + if (m_ObserverConnections.Contains(conn.connectionId)) + { + if (LogFilter.logDebug) { Debug.Log("Duplicate observer " + conn.address + " added for " + gameObject); } + return; + } + + if (LogFilter.logDev) { Debug.Log("Added observer " + conn.address + " added for " + gameObject); } + + m_Observers.Add(conn); + m_ObserverConnections.Add(conn.connectionId); + conn.AddToVisList(this); + } + + internal void RemoveObserver(NetworkConnection conn) + { + if (m_Observers == null) + return; + + // NOTE this is linear performance now.. + m_Observers.Remove(conn); + m_ObserverConnections.Remove(conn.connectionId); + conn.RemoveFromVisList(this, false); + } + + /// + /// This causes the set of players that can see this object to be rebuild. The OnRebuildObservers callback function will be invoked on each NetworkBehaviour. + /// + /// True if this is the first time. + public void RebuildObservers(bool initialize) + { + if (m_Observers == null) + return; + + bool changed = false; + bool result = false; + HashSet newObservers = new HashSet(); + HashSet oldObservers = new HashSet(m_Observers); + + for (int i = 0; i < m_NetworkBehaviours.Length; i++) + { + NetworkBehaviour comp = m_NetworkBehaviours[i]; + result |= comp.OnRebuildObservers(newObservers, initialize); + } + if (!result) + { + // none of the behaviours rebuilt our observers, use built-in rebuild method + if (initialize) + { + for (int i = 0; i < NetworkServer.connections.Count; i++) + { + var conn = NetworkServer.connections[i]; + if (conn == null) continue; + if (conn.isReady) + AddObserver(conn); + } + + for (int i = 0; i < NetworkServer.localConnections.Count; i++) + { + var conn = NetworkServer.localConnections[i]; + if (conn == null) continue; + if (conn.isReady) + AddObserver(conn); + } + } + return; + } + + // apply changes from rebuild + foreach (var conn in newObservers) + { + if (conn == null) + { + continue; + } + + if (!conn.isReady) + { + if (LogFilter.logWarn) { Debug.LogWarning("Observer is not ready for " + gameObject + " " + conn); } + continue; + } + + if (initialize || !oldObservers.Contains(conn)) + { + // new observer + conn.AddToVisList(this); + if (LogFilter.logDebug) { Debug.Log("New Observer for " + gameObject + " " + conn); } + changed = true; + } + } + + foreach (var conn in oldObservers) + { + if (!newObservers.Contains(conn)) + { + // removed observer + conn.RemoveFromVisList(this, false); + if (LogFilter.logDebug) { Debug.Log("Removed Observer for " + gameObject + " " + conn); } + changed = true; + } + } + + // special case for local client. + if (initialize) + { + for (int i = 0; i < NetworkServer.localConnections.Count; i++) + { + if (!newObservers.Contains(NetworkServer.localConnections[i])) + { + OnSetLocalVisibility(false); + } + } + } + + if (!changed) + return; + + m_Observers = new List(newObservers); + + // rebuild hashset once we have the final set of new observers + m_ObserverConnections.Clear(); + for (int i = 0; i < m_Observers.Count; i++) + { + m_ObserverConnections.Add(m_Observers[i].connectionId); + } + } + + /// + /// Removes ownership for an object for a client by its conneciton. + /// This applies to objects that had authority set by AssignClientAuthority, or NetworkServer.SpawnWithClientAuthority. Authority cannot be removed for player objects. + /// + /// The connection of the client to remove authority for. + /// True if authority is removed. + public bool RemoveClientAuthority(NetworkConnection conn) + { + if (!isServer) + { + if (LogFilter.logError) { Debug.LogError("RemoveClientAuthority can only be call on the server for spawned objects."); } + return false; + } + + if (connectionToClient != null) + { + if (LogFilter.logError) { Debug.LogError("RemoveClientAuthority cannot remove authority for a player object"); } + return false; + } + + if (m_ClientAuthorityOwner == null) + { + if (LogFilter.logError) { Debug.LogError("RemoveClientAuthority for " + gameObject + " has no clientAuthority owner."); } + return false; + } + + if (m_ClientAuthorityOwner != conn) + { + if (LogFilter.logError) { Debug.LogError("RemoveClientAuthority for " + gameObject + " has different owner."); } + return false; + } + + m_ClientAuthorityOwner.RemoveOwnedObject(this); + m_ClientAuthorityOwner = null; + + // server now has authority (this is only called on server) + ForceAuthority(true); + + // send msg to that client + var msg = new ClientAuthorityMessage(); + msg.netId = netId; + msg.authority = false; + conn.Send(MsgType.LocalClientAuthority, msg); + + if (clientAuthorityCallback != null) + { + clientAuthorityCallback(conn, this, false); + } + return true; + } + + /// + /// This assigns control of an object to a client via the client's NetworkConnection. + /// This causes hasAuthority to be set on the client that owns the object, and NetworkBehaviour.OnStartAuthority will be called on that client. This object then will be in the NetworkConnection.clientOwnedObjects list for the connection. + /// Authority can be removed with RemoveClientAuthority. Only one client can own an object at any time. Only NetworkIdentities with localPlayerAuthority set can have client authority assigned. This does not need to be called for player objects, as their authority is setup automatically. + /// + /// The connection of the client to assign authority to. + /// True if authority was assigned. + public bool AssignClientAuthority(NetworkConnection conn) + { + if (!isServer) + { + if (LogFilter.logError) { Debug.LogError("AssignClientAuthority can only be call on the server for spawned objects."); } + return false; + } + if (!localPlayerAuthority) + { + if (LogFilter.logError) { Debug.LogError("AssignClientAuthority can only be used for NetworkIdentity component with LocalPlayerAuthority set."); } + return false; + } + + if (m_ClientAuthorityOwner != null && conn != m_ClientAuthorityOwner) + { + if (LogFilter.logError) { Debug.LogError("AssignClientAuthority for " + gameObject + " already has an owner. Use RemoveClientAuthority() first."); } + return false; + } + + if (conn == null) + { + if (LogFilter.logError) { Debug.LogError("AssignClientAuthority for " + gameObject + " owner cannot be null. Use RemoveClientAuthority() instead."); } + return false; + } + + m_ClientAuthorityOwner = conn; + m_ClientAuthorityOwner.AddOwnedObject(this); + + // server no longer has authority (this is called on server). Note that local client could re-acquire authority below + ForceAuthority(false); + + // send msg to that client + var msg = new ClientAuthorityMessage(); + msg.netId = netId; + msg.authority = true; + conn.Send(MsgType.LocalClientAuthority, msg); + + if (clientAuthorityCallback != null) + { + clientAuthorityCallback(conn, this, true); + } + return true; + } + + // marks the identity for future reset, this is because we cant reset the identity during destroy + // as people might want to be able to read the members inside OnDestroy(), and we have no way + // of invoking reset after OnDestroy is called. + internal void MarkForReset() + { + m_Reset = true; + } + + // if we have marked an identity for reset we do the actual reset. + internal void Reset() + { + if (!m_Reset) + return; + + m_Reset = false; + m_IsServer = false; + m_IsClient = false; + m_HasAuthority = false; + + m_NetId = NetworkInstanceId.Zero; + m_IsLocalPlayer = false; + m_ConnectionToServer = null; + m_ConnectionToClient = null; + m_PlayerId = -1; + m_NetworkBehaviours = null; + + ClearObservers(); + m_ClientAuthorityOwner = null; + } + + +#if UNITY_EDITOR + [InitializeOnLoadMethod] + static void OnInitializeOnLoad() + { + // The transport layer has state in C++, so when the C# state is lost (on domain reload), the C++ transport layer must be shutown as well. + NetworkManager.OnDomainReload(); + } +#endif + + [RuntimeInitializeOnLoadMethod] + static void OnRuntimeInitializeOnLoad() + { + var go = new GameObject("UNETCallbacks"); + go.AddComponent(typeof(NetworkCallbacks)); + go.hideFlags = go.hideFlags | HideFlags.HideAndDontSave; + } + + static internal void UNetStaticUpdate() + { + NetworkServer.Update(); + NetworkClient.UpdateClients(); + NetworkManager.UpdateScene(); + +#if UNITY_EDITOR + Profiler.NewProfilerTick(); +#endif + } + }; +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkInstanceId.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkInstanceId.cs new file mode 100644 index 00000000..89c9f38d --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkInstanceId.cs @@ -0,0 +1,76 @@ +using System; + +namespace UnityEngine.Networking +{ + /// + /// This is used to identify networked objects across all participants of a network. It is assigned at runtime by the server when an object is spawned. + /// + [Serializable] + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public struct NetworkInstanceId : IEquatable + { + public NetworkInstanceId(uint value) + { + m_Value = value; + } + + [SerializeField] + readonly uint m_Value; + + /// + /// Returns true if the value of the NetworkInstanceId is zero. + /// Object that have not been spawned will have a value of zero. + /// + /// True if zero. + public bool IsEmpty() + { + return m_Value == 0; + } + + public override int GetHashCode() + { + return (int)m_Value; + } + + public override bool Equals(object obj) + { + return obj is NetworkInstanceId && Equals((NetworkInstanceId)obj); + } + + public bool Equals(NetworkInstanceId other) + { + return this == other; + } + + public static bool operator==(NetworkInstanceId c1, NetworkInstanceId c2) + { + return c1.m_Value == c2.m_Value; + } + + public static bool operator!=(NetworkInstanceId c1, NetworkInstanceId c2) + { + return c1.m_Value != c2.m_Value; + } + + /// + /// Returns a string of "NetID:value". + /// + /// String representation of this object. + public override string ToString() + { + return m_Value.ToString(); + } + + /// + /// The internal value of this identifier. + /// + public uint Value { get { return m_Value; } } + + /// + /// A static invalid NetworkInstanceId that can be used for comparisons. + /// The default value of NetworkInstanceId.Value is zero, and IsEmpty() can be used to check this. But NetworkInstanceId.Invalid is available for specifically setting and checking for invalid IDs. + /// + public static NetworkInstanceId Invalid = new NetworkInstanceId(uint.MaxValue); + internal static NetworkInstanceId Zero = new NetworkInstanceId(0); + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkLobbyManager.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkLobbyManager.cs new file mode 100644 index 00000000..1898cf13 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkLobbyManager.cs @@ -0,0 +1,1177 @@ + +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine.Networking.NetworkSystem; +using UnityEngine.SceneManagement; + +namespace UnityEngine.Networking +{ + /// + /// This is a specialized NetworkManager that includes a networked lobby. + /// The lobby has slots that track the joined players, and a maximum player count that is enforced. It requires that the NetworkLobbyPlayer component be on the lobby player objects. + /// NetworkLobbyManager is derived from NetworkManager, and so it implements many of the virtual functions provided by the NetworkManager class. To avoid accidentally replacing functionality of the NetworkLobbyManager, there are new virtual functions on the NetworkLobbyManager that begin with "OnLobby". These should be used on classes derived from NetworkLobbyManager instead of the virtual functions on NetworkManager. + /// The OnLobby*() functions have empty implementations on the NetworkLobbyManager base class, so the base class functions do not have to be called. + /// + [AddComponentMenu("Network/NetworkLobbyManager")] + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class NetworkLobbyManager : NetworkManager + { + struct PendingPlayer + { + public NetworkConnection conn; + public GameObject lobbyPlayer; + } + + // configuration + [SerializeField] bool m_ShowLobbyGUI = true; + [SerializeField] int m_MaxPlayers = 4; + [SerializeField] int m_MaxPlayersPerConnection = 1; + [SerializeField] int m_MinPlayers; + [SerializeField] NetworkLobbyPlayer m_LobbyPlayerPrefab; + [SerializeField] GameObject m_GamePlayerPrefab; + [SerializeField] string m_LobbyScene = ""; + [SerializeField] string m_PlayScene = ""; + + // runtime data + List m_PendingPlayers = new List(); + /// + /// These slots track players that enter the lobby. + /// The slotId on players is global to the game - across all players. + /// + public NetworkLobbyPlayer[] lobbySlots; + + // static message objects to avoid runtime-allocations + static LobbyReadyToBeginMessage s_ReadyToBeginMessage = new LobbyReadyToBeginMessage(); + static IntegerMessage s_SceneLoadedMessage = new IntegerMessage(); + static LobbyReadyToBeginMessage s_LobbyReadyToBeginMessage = new LobbyReadyToBeginMessage(); + + // properties + /// + /// This flag enables display of the default lobby UI. + /// This is rendered using the old GUI system, so is only recommended for testing purposes. + /// + public bool showLobbyGUI { get { return m_ShowLobbyGUI; } set { m_ShowLobbyGUI = value; } } + /// + /// The maximum number of players allowed in the game. + /// Note that this is the number "players" not clients or connections. There can be multiple players per client. + /// + public int maxPlayers { get { return m_MaxPlayers; } set { m_MaxPlayers = value; } } + /// + /// The maximum number of players per connection. + /// Calling ClientScene.AddPlayer will fail if this limit is reached. + /// + public int maxPlayersPerConnection { get { return m_MaxPlayersPerConnection; } set { m_MaxPlayersPerConnection = value; } } + /// + /// The minimum number of players required to be ready for the game to start. + /// If this is zero then the game can start with any number of players. + /// + public int minPlayers { get { return m_MinPlayers; } set { m_MinPlayers = value; } } + /// + /// This is the prefab of the player to be created in the LobbyScene. + /// This prefab must have a NetworkLobbyPlayer component on it. + /// In the lobby scene, this will be the active player object, but in other scenes while the game is running, this will be replaced by a player object created from the GamePlayerPrefab. But once returned to the lobby scene this will again become the active player object. + /// This can be used to store user data that persists for the lifetime of the session, such as color choices or weapon choices. + /// + public NetworkLobbyPlayer lobbyPlayerPrefab { get { return m_LobbyPlayerPrefab; } set { m_LobbyPlayerPrefab = value; } } + /// + /// This is the prefab of the player to be created in the PlayScene. + /// When CheckReadyToBegin starts the game from the lobby, a new player object is created from this prefab, and that object is made the active player object using NetworkServer.ReplacePlayerForConnection. + /// + public GameObject gamePlayerPrefab { get { return m_GamePlayerPrefab; } set { m_GamePlayerPrefab = value; } } + /// + /// The scene to use for the lobby. This is similar to the offlineScene of the NetworkManager. + /// + public string lobbyScene { get { return m_LobbyScene; } set { m_LobbyScene = value; offlineScene = value; } } + /// + /// The scene to use for the playing the game from the lobby. This is similar to the onlineScene of the NetworkManager. + /// + public string playScene { get { return m_PlayScene; } set { m_PlayScene = value; } } + + void OnValidate() + { + if (m_MaxPlayers <= 0) + { + m_MaxPlayers = 1; + } + + if (m_MaxPlayersPerConnection <= 0) + { + m_MaxPlayersPerConnection = 1; + } + + if (m_MaxPlayersPerConnection > maxPlayers) + { + m_MaxPlayersPerConnection = maxPlayers; + } + + if (m_MinPlayers < 0) + { + m_MinPlayers = 0; + } + + if (m_MinPlayers > m_MaxPlayers) + { + m_MinPlayers = m_MaxPlayers; + } + + if (m_LobbyPlayerPrefab != null) + { + var uv = m_LobbyPlayerPrefab.GetComponent(); + if (uv == null) + { + m_LobbyPlayerPrefab = null; + Debug.LogWarning("LobbyPlayer prefab must have a NetworkIdentity component."); + } + } + + if (m_GamePlayerPrefab != null) + { + var uv = m_GamePlayerPrefab.GetComponent(); + if (uv == null) + { + m_GamePlayerPrefab = null; + Debug.LogWarning("GamePlayer prefab must have a NetworkIdentity component."); + } + } + } + + Byte FindSlot() + { + for (byte i = 0; i < maxPlayers; i++) + { + if (lobbySlots[i] == null) + { + return i; + } + } + return Byte.MaxValue; + } + + void SceneLoadedForPlayer(NetworkConnection conn, GameObject lobbyPlayerGameObject) + { + var lobbyPlayer = lobbyPlayerGameObject.GetComponent(); + if (lobbyPlayer == null) + { + // not a lobby player.. dont replace it + return; + } + + string loadedSceneName = SceneManager.GetSceneAt(0).name; + if (LogFilter.logDebug) { Debug.Log("NetworkLobby SceneLoadedForPlayer scene:" + loadedSceneName + " " + conn); } + + if (loadedSceneName == m_LobbyScene) + { + // cant be ready in lobby, add to ready list + PendingPlayer pending; + pending.conn = conn; + pending.lobbyPlayer = lobbyPlayerGameObject; + m_PendingPlayers.Add(pending); + return; + } + + var controllerId = lobbyPlayerGameObject.GetComponent().playerControllerId; + var gamePlayer = OnLobbyServerCreateGamePlayer(conn, controllerId); + if (gamePlayer == null) + { + // get start position from base class + Transform startPos = GetStartPosition(); + if (startPos != null) + { + gamePlayer = (GameObject)Instantiate(gamePlayerPrefab, startPos.position, startPos.rotation); + } + else + { + gamePlayer = (GameObject)Instantiate(gamePlayerPrefab, Vector3.zero, Quaternion.identity); + } + } + + if (!OnLobbyServerSceneLoadedForPlayer(lobbyPlayerGameObject, gamePlayer)) + { + return; + } + + // replace lobby player with game player + NetworkServer.ReplacePlayerForConnection(conn, gamePlayer, controllerId); + } + + static int CheckConnectionIsReadyToBegin(NetworkConnection conn) + { + int countPlayers = 0; + for (int i = 0; i < conn.playerControllers.Count; i++) + { + var player = conn.playerControllers[i]; + if (player.IsValid) + { + var lobbyPlayer = player.gameObject.GetComponent(); + if (lobbyPlayer.readyToBegin) + { + countPlayers += 1; + } + } + } + return countPlayers; + } + + /// + /// CheckReadyToBegin checks all of the players in the lobby to see if their readyToBegin flag is set. + /// If all of the players are ready, then the server switches from the LobbyScene to the PlayScene - essentially starting the game. This is called automatically in response to NetworkLobbyPlayer.SendReadyToBeginMessage(). + /// + public void CheckReadyToBegin() + { + string loadedSceneName = SceneManager.GetSceneAt(0).name; + if (loadedSceneName != m_LobbyScene) + { + return; + } + + int readyCount = 0; + int playerCount = 0; + + for (int i = 0; i < NetworkServer.connections.Count; i++) + { + var conn = NetworkServer.connections[i]; + + if (conn == null) + continue; + + playerCount += 1; + readyCount += CheckConnectionIsReadyToBegin(conn); + } + if (m_MinPlayers > 0 && readyCount < m_MinPlayers) + { + // not enough players ready yet. + return; + } + + if (readyCount < playerCount) + { + // not all players are ready yet + return; + } + + m_PendingPlayers.Clear(); + OnLobbyServerPlayersReady(); + } + + /// + /// Calling this causes the server to switch back to the lobby scene. + /// + public void ServerReturnToLobby() + { + if (!NetworkServer.active) + { + Debug.Log("ServerReturnToLobby called on client"); + return; + } + ServerChangeScene(m_LobbyScene); + } + + void CallOnClientEnterLobby() + { + OnLobbyClientEnter(); + for (int i = 0; i < lobbySlots.Length; i++) + { + var player = lobbySlots[i]; + if (player == null) + continue; + + player.readyToBegin = false; + player.OnClientEnterLobby(); + } + } + + void CallOnClientExitLobby() + { + OnLobbyClientExit(); + for (int i = 0; i < lobbySlots.Length; i++) + { + var player = lobbySlots[i]; + if (player == null) + continue; + + player.OnClientExitLobby(); + } + } + + /// + /// Sends a message to the server to make the game return to the lobby scene. + /// + /// True if message was sent. + public bool SendReturnToLobby() + { + if (client == null || !client.isConnected) + { + return false; + } + + var msg = new EmptyMessage(); + client.Send(MsgType.LobbyReturnToLobby, msg); + return true; + } + + // ------------------------ server handlers ------------------------ + + public override void OnServerConnect(NetworkConnection conn) + { + // numPlayers returns the player count including this one, so ok to be equal + if (numPlayers > maxPlayers) + { + if (LogFilter.logWarn) { Debug.LogWarning("NetworkLobbyManager can't accept new connection [" + conn + "], too many players connected."); } + conn.Disconnect(); + return; + } + + // cannot join game in progress + string loadedSceneName = SceneManager.GetSceneAt(0).name; + if (loadedSceneName != m_LobbyScene) + { + if (LogFilter.logWarn) { Debug.LogWarning("NetworkLobbyManager can't accept new connection [" + conn + "], not in lobby and game already in progress."); } + conn.Disconnect(); + return; + } + + base.OnServerConnect(conn); + + // when a new client connects, set all old players as dirty so their current ready state is sent out + for (int i = 0; i < lobbySlots.Length; ++i) + { + if (lobbySlots[i]) + { + lobbySlots[i].SetDirtyBit(1); + } + } + + OnLobbyServerConnect(conn); + } + + public override void OnServerDisconnect(NetworkConnection conn) + { + base.OnServerDisconnect(conn); + + // if lobbyplayer for this connection has not been destroyed by now, then destroy it here + for (int i = 0; i < lobbySlots.Length; i++) + { + var player = lobbySlots[i]; + if (player == null) + continue; + + if (player.connectionToClient == conn) + { + lobbySlots[i] = null; + NetworkServer.Destroy(player.gameObject); + } + } + + OnLobbyServerDisconnect(conn); + } + + public override void OnServerAddPlayer(NetworkConnection conn, short playerControllerId) + { + string loadedSceneName = SceneManager.GetSceneAt(0).name; + if (loadedSceneName != m_LobbyScene) + { + return; + } + + // check MaxPlayersPerConnection + int numPlayersForConnection = 0; + for (int i = 0; i < conn.playerControllers.Count; i++) + { + if (conn.playerControllers[i].IsValid) + numPlayersForConnection += 1; + } + + if (numPlayersForConnection >= maxPlayersPerConnection) + { + if (LogFilter.logWarn) { Debug.LogWarning("NetworkLobbyManager no more players for this connection."); } + + var errorMsg = new EmptyMessage(); + conn.Send(MsgType.LobbyAddPlayerFailed, errorMsg); + return; + } + + byte slot = FindSlot(); + if (slot == Byte.MaxValue) + { + if (LogFilter.logWarn) { Debug.LogWarning("NetworkLobbyManager no space for more players"); } + + var errorMsg = new EmptyMessage(); + conn.Send(MsgType.LobbyAddPlayerFailed, errorMsg); + return; + } + + var newLobbyGameObject = OnLobbyServerCreateLobbyPlayer(conn, playerControllerId); + if (newLobbyGameObject == null) + { + newLobbyGameObject = (GameObject)Instantiate(lobbyPlayerPrefab.gameObject, Vector3.zero, Quaternion.identity); + } + + var newLobbyPlayer = newLobbyGameObject.GetComponent(); + newLobbyPlayer.slot = slot; + lobbySlots[slot] = newLobbyPlayer; + + NetworkServer.AddPlayerForConnection(conn, newLobbyGameObject, playerControllerId); + } + + public override void OnServerRemovePlayer(NetworkConnection conn, PlayerController player) + { + var playerControllerId = player.playerControllerId; + byte slot = player.gameObject.GetComponent().slot; + lobbySlots[slot] = null; + base.OnServerRemovePlayer(conn, player); + + for (int i = 0; i < lobbySlots.Length; i++) + { + var lobbyPlayer = lobbySlots[i]; + if (lobbyPlayer != null) + { + lobbyPlayer.GetComponent().readyToBegin = false; + + s_LobbyReadyToBeginMessage.slotId = lobbyPlayer.slot; + s_LobbyReadyToBeginMessage.readyState = false; + NetworkServer.SendToReady(null, MsgType.LobbyReadyToBegin, s_LobbyReadyToBeginMessage); + } + } + + OnLobbyServerPlayerRemoved(conn, playerControllerId); + } + + public override void ServerChangeScene(string sceneName) + { + if (sceneName == m_LobbyScene) + { + for (int i = 0; i < lobbySlots.Length; i++) + { + var lobbyPlayer = lobbySlots[i]; + if (lobbyPlayer == null) + continue; + + // find the game-player object for this connection, and destroy it + var uv = lobbyPlayer.GetComponent(); + + PlayerController playerController; + if (uv.connectionToClient.GetPlayerController(uv.playerControllerId, out playerController)) + { + NetworkServer.Destroy(playerController.gameObject); + } + + if (NetworkServer.active) + { + // re-add the lobby object + lobbyPlayer.GetComponent().readyToBegin = false; + NetworkServer.ReplacePlayerForConnection(uv.connectionToClient, lobbyPlayer.gameObject, uv.playerControllerId); + } + } + } + base.ServerChangeScene(sceneName); + } + + public override void OnServerSceneChanged(string sceneName) + { + if (sceneName != m_LobbyScene) + { + // call SceneLoadedForPlayer on any players that become ready while we were loading the scene. + for (int i = 0; i < m_PendingPlayers.Count; i++) + { + var pending = m_PendingPlayers[i]; + SceneLoadedForPlayer(pending.conn, pending.lobbyPlayer); + } + m_PendingPlayers.Clear(); + } + + OnLobbyServerSceneChanged(sceneName); + } + + void OnServerReadyToBeginMessage(NetworkMessage netMsg) + { + if (LogFilter.logDebug) { Debug.Log("NetworkLobbyManager OnServerReadyToBeginMessage"); } + netMsg.ReadMessage(s_ReadyToBeginMessage); + + PlayerController lobbyController; + if (!netMsg.conn.GetPlayerController((short)s_ReadyToBeginMessage.slotId, out lobbyController)) + { + if (LogFilter.logError) { Debug.LogError("NetworkLobbyManager OnServerReadyToBeginMessage invalid playerControllerId " + s_ReadyToBeginMessage.slotId); } + return; + } + + // set this player ready + var lobbyPlayer = lobbyController.gameObject.GetComponent(); + lobbyPlayer.readyToBegin = s_ReadyToBeginMessage.readyState; + + // tell every player that this player is ready + var outMsg = new LobbyReadyToBeginMessage(); + outMsg.slotId = lobbyPlayer.slot; + outMsg.readyState = s_ReadyToBeginMessage.readyState; + NetworkServer.SendToReady(null, MsgType.LobbyReadyToBegin, outMsg); + + // maybe start the game + CheckReadyToBegin(); + } + + void OnServerSceneLoadedMessage(NetworkMessage netMsg) + { + if (LogFilter.logDebug) { Debug.Log("NetworkLobbyManager OnSceneLoadedMessage"); } + + netMsg.ReadMessage(s_SceneLoadedMessage); + + PlayerController lobbyController; + if (!netMsg.conn.GetPlayerController((short)s_SceneLoadedMessage.value, out lobbyController)) + { + if (LogFilter.logError) { Debug.LogError("NetworkLobbyManager OnServerSceneLoadedMessage invalid playerControllerId " + s_SceneLoadedMessage.value); } + return; + } + + SceneLoadedForPlayer(netMsg.conn, lobbyController.gameObject); + } + + void OnServerReturnToLobbyMessage(NetworkMessage netMsg) + { + if (LogFilter.logDebug) { Debug.Log("NetworkLobbyManager OnServerReturnToLobbyMessage"); } + + ServerReturnToLobby(); + } + + public override void OnStartServer() + { + if (string.IsNullOrEmpty(m_LobbyScene)) + { + if (LogFilter.logError) { Debug.LogError("NetworkLobbyManager LobbyScene is empty. Set the LobbyScene in the inspector for the NetworkLobbyMangaer"); } + return; + } + + if (string.IsNullOrEmpty(m_PlayScene)) + { + if (LogFilter.logError) { Debug.LogError("NetworkLobbyManager PlayScene is empty. Set the PlayScene in the inspector for the NetworkLobbyMangaer"); } + return; + } + + if (lobbySlots.Length == 0) + { + lobbySlots = new NetworkLobbyPlayer[maxPlayers]; + } + + NetworkServer.RegisterHandler(MsgType.LobbyReadyToBegin, OnServerReadyToBeginMessage); + NetworkServer.RegisterHandler(MsgType.LobbySceneLoaded, OnServerSceneLoadedMessage); + NetworkServer.RegisterHandler(MsgType.LobbyReturnToLobby, OnServerReturnToLobbyMessage); + + OnLobbyStartServer(); + } + + public override void OnStartHost() + { + OnLobbyStartHost(); + } + + public override void OnStopHost() + { + OnLobbyStopHost(); + } + + // ------------------------ client handlers ------------------------ + + public override void OnStartClient(NetworkClient lobbyClient) + { + if (lobbySlots.Length == 0) + { + lobbySlots = new NetworkLobbyPlayer[maxPlayers]; + } + + if (m_LobbyPlayerPrefab == null || m_LobbyPlayerPrefab.gameObject == null) + { + if (LogFilter.logError) { Debug.LogError("NetworkLobbyManager no LobbyPlayer prefab is registered. Please add a LobbyPlayer prefab."); } + } + else + { + ClientScene.RegisterPrefab(m_LobbyPlayerPrefab.gameObject); + } + + if (m_GamePlayerPrefab == null) + { + if (LogFilter.logError) { Debug.LogError("NetworkLobbyManager no GamePlayer prefab is registered. Please add a GamePlayer prefab."); } + } + else + { + ClientScene.RegisterPrefab(m_GamePlayerPrefab); + } + + lobbyClient.RegisterHandler(MsgType.LobbyReadyToBegin, OnClientReadyToBegin); + lobbyClient.RegisterHandler(MsgType.LobbyAddPlayerFailed, OnClientAddPlayerFailedMessage); + + OnLobbyStartClient(lobbyClient); + } + + public override void OnClientConnect(NetworkConnection conn) + { + OnLobbyClientConnect(conn); + CallOnClientEnterLobby(); + base.OnClientConnect(conn); + } + + public override void OnClientDisconnect(NetworkConnection conn) + { + OnLobbyClientDisconnect(conn); + base.OnClientDisconnect(conn); + } + + public override void OnStopClient() + { + OnLobbyStopClient(); + CallOnClientExitLobby(); + } + + public override void OnClientSceneChanged(NetworkConnection conn) + { + string loadedSceneName = SceneManager.GetSceneAt(0).name; + if (loadedSceneName == m_LobbyScene) + { + if (client.isConnected) + { + CallOnClientEnterLobby(); + } + } + else + { + CallOnClientExitLobby(); + } + + base.OnClientSceneChanged(conn); + OnLobbyClientSceneChanged(conn); + } + + void OnClientReadyToBegin(NetworkMessage netMsg) + { + netMsg.ReadMessage(s_LobbyReadyToBeginMessage); + + if (s_LobbyReadyToBeginMessage.slotId >= lobbySlots.Count()) + { + if (LogFilter.logError) { Debug.LogError("NetworkLobbyManager OnClientReadyToBegin invalid lobby slot " + s_LobbyReadyToBeginMessage.slotId); } + return; + } + + var lobbyPlayer = lobbySlots[s_LobbyReadyToBeginMessage.slotId]; + if (lobbyPlayer == null || lobbyPlayer.gameObject == null) + { + if (LogFilter.logError) { Debug.LogError("NetworkLobbyManager OnClientReadyToBegin no player at lobby slot " + s_LobbyReadyToBeginMessage.slotId); } + return; + } + + lobbyPlayer.readyToBegin = s_LobbyReadyToBeginMessage.readyState; + lobbyPlayer.OnClientReady(s_LobbyReadyToBeginMessage.readyState); + } + + void OnClientAddPlayerFailedMessage(NetworkMessage netMsg) + { + if (LogFilter.logDebug) { Debug.Log("NetworkLobbyManager Add Player failed."); } + OnLobbyClientAddPlayerFailed(); + } + + // ------------------------ lobby server virtuals ------------------------ + + /// + /// This is called on the host when a host is started. + /// + /// //This script shows you how to add extra functionality when the lobby host starts and stops + /// //Add this script to your GameObject. Make sure there isn't another NetworkManager in the Scene. + /// //Create a Host Button (Create>UI>Text) and assign it in the Inspector of the GameObject this script is attached to + /// //Create a Text GameObject (Create>UI>Text) and attach it to the Status Text field in the Inspector. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// using UnityEngine.UI; + /// + /// public class Example : NetworkLobbyManager + /// { + /// public Button m_HostButton; + /// public Text m_StatusText; + /// bool m_HostStarted; + /// + /// void Start() + /// { + /// //Set the minimum and maximum number of players + /// maxPlayers = 6; + /// minPlayers = 2; + /// maxPlayersPerConnection = 1; + /// //Call these functions when each Button is clicked + /// m_HostButton.onClick.AddListener(HostButton); + /// m_StatusText.text = "Current Scene : " + lobbyScene; + /// } + /// + /// //Output a message when the host joins the lobby + /// public override void OnLobbyStartHost() + /// { + /// //Change the Text to show this message + /// m_StatusText.text = "A Host has joined the lobby!"; + /// m_HostStarted = true; + /// //Do the default actions for when the host starts in the lobby + /// base.OnLobbyStartHost(); + /// } + /// + /// // Output a message to the host when the host stops + /// public override void OnLobbyStopHost() + /// { + /// //Output this message when the host stops + /// m_StatusText.text = "A Host has left the lobby!"; + /// //Do the default actions when the host stops + /// base.OnLobbyStopHost(); + /// m_HostStarted = false; + /// } + /// + /// /// This is where the Buttons are given functionality + /// //Start the host when this Button is pressed + /// public void HostButton() + /// { + /// //Check if the host has already started + /// if (m_HostStarted == false) + /// { + /// //Start the host + /// StartHost(); + /// //Change the Button's Text + /// m_HostButton.GetComponentInChildren<Text>().text = "Stop Host"; + /// } + /// else + /// { + /// //If the host has already started, stop the host + /// StopHost(); + /// //Change the Button's Text + /// m_HostButton.GetComponentInChildren<Text>().text = "Start Host"; + /// } + /// } + /// } + /// + /// + public virtual void OnLobbyStartHost() + { + } + + /// + /// This is called on the host when the host is stopped. + /// + public virtual void OnLobbyStopHost() + { + } + + /// + /// This is called on the server when the server is started - including when a host is started. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// using UnityEngine.UI; + /// + /// public class Example : NetworkLobbyManager + /// { + /// //Add this script to your GameObject. Make sure there isn't another NetworkManager in the Scene. + /// //Create 2 Buttons (Create>UI>Text) and either: + /// //1. assign them in the Inspector of the GameObject this script is attached to or + /// //2. remove this part and the listeners and alter the OnClick section on each Button to match up with each function + /// //Create a Text GameObject (Create>UI>Text) and attach it to the Status Text field in the Inspector. + /// + /// public Button m_ClientButton, m_ServerButton; + /// bool m_ServerStarted, m_ClientStarted; + /// + /// void Start() + /// { + /// showLobbyGUI = true; + /// //Call these functions when each Button is clicked + /// m_ServerButton.onClick.AddListener(ServerButton); + /// m_ClientButton.onClick.AddListener(ClientButton); + /// } + /// + /// //Output a message when your client enters the lobby + /// public override void OnLobbyClientEnter() + /// { + /// m_ClientStarted = true; + /// base.OnLobbyClientEnter(); + /// Debug.Log("Your client has entered the lobby!"); + /// } + /// + /// public override void OnLobbyStopClient() + /// { + /// Debug.Log("Client stopped"); + /// base.OnLobbyStopClient(); + /// } + /// + /// public override void OnLobbyStartServer() + /// { + /// m_ServerStarted = true; + /// base.OnLobbyStartServer(); + /// Debug.Log("Server Started!"); + /// } + /// + /// public override void OnStopServer() + /// { + /// m_ServerStarted = false; + /// base.OnStopServer(); + /// Debug.Log("Server Stopped!"); + /// } + /// + /// //Start the Client when this Button is pressed + /// public void ClientButton() + /// { + /// if (m_ClientStarted == false) + /// { + /// StartClient(); + /// m_ClientButton.GetComponentInChildren<Text>().text = "Stop Client"; + /// } + /// else + /// { + /// StopClient(); + /// m_ClientButton.GetComponentInChildren<Text>().text = "Start Client"; + /// } + /// } + /// + /// //Start the Server when this Button is pressed + /// public void ServerButton() + /// { + /// Debug.Log("Server : " + m_ServerStarted); + /// if (m_ServerStarted == false) + /// { + /// StartServer(); + /// m_ServerButton.GetComponentInChildren<Text>().text = "Stop Server"; + /// } + /// else + /// { + /// StopServer(); + /// ServerReturnToLobby(); + /// m_ServerButton.GetComponentInChildren<Text>().text = "Start Server"; + /// } + /// } + /// } + /// + /// + public virtual void OnLobbyStartServer() + { + } + + /// + /// This is called on the server when a new client connects to the server. + /// + /// The new connection. + public virtual void OnLobbyServerConnect(NetworkConnection conn) + { + } + + /// + /// This is called on the server when a client disconnects. + /// + /// The connection that disconnected. + public virtual void OnLobbyServerDisconnect(NetworkConnection conn) + { + } + + /// + /// This is called on the server when a networked scene finishes loading. + /// + /// Name of the new scene. + public virtual void OnLobbyServerSceneChanged(string sceneName) + { + } + + /// + /// This allows customization of the creation of the lobby-player object on the server. + /// By default the lobbyPlayerPrefab is used to create the lobby-player, but this function allows that behaviour to be customized. + /// + /// The connection the player object is for. + /// The controllerId of the player. + /// The new lobby-player object. + public virtual GameObject OnLobbyServerCreateLobbyPlayer(NetworkConnection conn, short playerControllerId) + { + return null; + } + + /// + /// This allows customization of the creation of the GamePlayer object on the server. + /// By default the gamePlayerPrefab is used to create the game-player, but this function allows that behaviour to be customized. The object returned from the function will be used to replace the lobby-player on the connection. + /// + /// The connection the player object is for. + /// The controllerId of the player on the connnection. + /// A new GamePlayer object. + public virtual GameObject OnLobbyServerCreateGamePlayer(NetworkConnection conn, short playerControllerId) + { + return null; + } + + /// + /// This is called on the server when a player is removed. + /// + /// The connection the player object is for. + /// The controllerId of the player that was removed. + public virtual void OnLobbyServerPlayerRemoved(NetworkConnection conn, short playerControllerId) + { + } + + /// + /// This is called on the server when it is told that a client has finished switching from the lobby scene to a game player scene. + /// When switching from the lobby, the lobby-player is replaced with a game-player object. This callback function gives an opportunity to apply state from the lobby-player to the game-player object. + /// + /// The lobby player object. + /// The game player object. + /// False to not allow this player to replace the lobby player. + // for users to apply settings from their lobby player object to their in-game player object + public virtual bool OnLobbyServerSceneLoadedForPlayer(GameObject lobbyPlayer, GameObject gamePlayer) + { + return true; + } + + /// + /// This is called on the server when all the players in the lobby are ready. + /// The default implementation of this function uses ServerChangeScene() to switch to the game player scene. By implementing this callback you can customize what happens when all the players in the lobby are ready, such as adding a countdown or a confirmation for a group leader. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class GuiLobby : NetworkLobbyManager + /// { + /// float countTimer = 0; + /// + /// public override void OnLobbyServerPlayersReady() + /// { + /// countTimer = Time.time + 5; + /// } + /// + /// void Update() + /// { + /// if (countTimer == 0) + /// return; + /// if (Time.time > countTimer) + /// { + /// countTimer = 0; + /// ServerChangeScene(playScene); + /// } + /// else + /// { + /// Debug.Log("Counting down " + (countTimer - Time.time)); + /// } + /// } + /// } + /// + /// + public virtual void OnLobbyServerPlayersReady() + { + // all players are readyToBegin, start the game + ServerChangeScene(m_PlayScene); + } + + // ------------------------ lobby client virtuals ------------------------ + + /// + /// This is a hook to allow custom behaviour when the game client enters the lobby. + /// + public virtual void OnLobbyClientEnter() + { + } + + /// + /// This is a hook to allow custom behaviour when the game client exits the lobby. + /// + public virtual void OnLobbyClientExit() + { + } + + /// + /// This is called on the client when it connects to server. + /// + /// The connection that connected. + public virtual void OnLobbyClientConnect(NetworkConnection conn) + { + } + + /// + /// This is called on the client when disconnected from a server. + /// + /// The connection that disconnected. + public virtual void OnLobbyClientDisconnect(NetworkConnection conn) + { + } + + /// + /// This is called on the client when a client is started. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// using UnityEngine.UI; + /// + /// public class Example : NetworkLobbyManager + /// { + /// //Add this script to your GameObject. Make sure there isn't another NetworkManager in the Scene. + /// //Create 2 Buttons (Create>UI>Text) and either: + /// //1. assign them in the Inspector of the GameObject this script is attached to or + /// //2. remove this part and the listeners and alter the OnClick section on each Button to match up with each function + /// //Create a Text GameObject (Create>UI>Text) and attach it to the Status Text field in the Inspector. + /// + /// public Button m_ClientButton, m_ServerButton; + /// bool m_ServerStarted, m_ClientStarted; + /// + /// void Start() + /// { + /// showLobbyGUI = true; + /// //Call these functions when each Button is clicked + /// m_ServerButton.onClick.AddListener(ServerButton); + /// m_ClientButton.onClick.AddListener(ClientButton); + /// } + /// + /// //Output a message when your client enters the lobby + /// public override void OnLobbyClientEnter() + /// { + /// m_ClientStarted = true; + /// base.OnLobbyClientEnter(); + /// Debug.Log("Your client has entered the lobby!"); + /// } + /// + /// public override void OnLobbyStopClient() + /// { + /// Debug.Log("Client stopped"); + /// base.OnLobbyStopClient(); + /// } + /// + /// public override void OnLobbyStartServer() + /// { + /// m_ServerStarted = true; + /// base.OnLobbyStartServer(); + /// Debug.Log("Server Started!"); + /// } + /// + /// public override void OnStopServer() + /// { + /// m_ServerStarted = false; + /// base.OnStopServer(); + /// Debug.Log("Server Stopped!"); + /// } + /// + /// //Start the Client when this Button is pressed + /// public void ClientButton() + /// { + /// if (m_ClientStarted == false) + /// { + /// StartClient(); + /// m_ClientButton.GetComponentInChildren<Text>().text = "Stop Client"; + /// } + /// else + /// { + /// StopClient(); + /// m_ClientButton.GetComponentInChildren<Text>().text = "Start Client"; + /// } + /// } + /// + /// //Start the Server when this Button is pressed + /// public void ServerButton() + /// { + /// Debug.Log("Server : " + m_ServerStarted); + /// if (m_ServerStarted == false) + /// { + /// StartServer(); + /// m_ServerButton.GetComponentInChildren<Text>().text = "Stop Server"; + /// } + /// else + /// { + /// StopServer(); + /// ServerReturnToLobby(); + /// m_ServerButton.GetComponentInChildren<Text>().text = "Start Server"; + /// } + /// } + /// } + /// + /// + /// The connection for the lobby. + public virtual void OnLobbyStartClient(NetworkClient lobbyClient) + { + } + + /// + /// This is called on the client when the client stops. + /// + public virtual void OnLobbyStopClient() + { + } + + /// + /// This is called on the client when the client is finished loading a new networked scene. + /// + /// The connection that finished loading a new networked scene. + public virtual void OnLobbyClientSceneChanged(NetworkConnection conn) + { + } + + /// + /// Called on the client when adding a player to the lobby fails. + /// This could be because the lobby is full, or the connection is not allowed to have more players. + /// + // for users to handle adding a player failed on the server + public virtual void OnLobbyClientAddPlayerFailed() + { + } + + // ------------------------ optional UI ------------------------ + + void OnGUI() + { + if (!showLobbyGUI) + return; + + string loadedSceneName = SceneManager.GetSceneAt(0).name; + if (loadedSceneName != m_LobbyScene) + return; + + Rect backgroundRec = new Rect(90 , 180, 500, 150); + GUI.Box(backgroundRec, "Players:"); + + if (NetworkClient.active) + { + Rect addRec = new Rect(100, 300, 120, 20); + if (GUI.Button(addRec, "Add Player")) + { + TryToAddPlayer(); + } + } + } + + /// + /// This is used on clients to attempt to add a player to the game. + /// This may fail if the game is full or the connection cannot have more players. + /// + public void TryToAddPlayer() + { + if (NetworkClient.active) + { + short controllerId = -1; + var controllers = NetworkClient.allClients[0].connection.playerControllers; + + if (controllers.Count < maxPlayers) + { + controllerId = (short)controllers.Count; + } + else + { + for (short i = 0; i < maxPlayers; i++) + { + if (!controllers[i].IsValid) + { + controllerId = i; + break; + } + } + } + if (LogFilter.logDebug) { Debug.Log("NetworkLobbyManager TryToAddPlayer controllerId " + controllerId + " ready:" + ClientScene.ready); } + + if (controllerId == -1) + { + if (LogFilter.logDebug) { Debug.Log("NetworkLobbyManager No Space!"); } + return; + } + + if (ClientScene.ready) + { + ClientScene.AddPlayer(controllerId); + } + else + { + ClientScene.AddPlayer(NetworkClient.allClients[0].connection, controllerId); + } + } + else + { + if (LogFilter.logDebug) { Debug.Log("NetworkLobbyManager NetworkClient not active!"); } + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkLobbyPlayer.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkLobbyPlayer.cs new file mode 100644 index 00000000..dd8211fc --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkLobbyPlayer.cs @@ -0,0 +1,271 @@ + +using System; +using UnityEngine; +using UnityEngine.Networking.NetworkSystem; +using UnityEngine.SceneManagement; + +namespace UnityEngine.Networking +{ + /// + /// This component works in conjunction with the NetworkLobbyManager to make up the multiplayer lobby system. + /// The LobbyPrefab object of the NetworkLobbyManager must have this component on it. This component holds basic lobby player data required for the lobby to function. Game specific data for lobby players can be put in other components on the LobbyPrefab or in scripts derived from NetworkLobbyPlayer. + /// + [DisallowMultipleComponent] + [AddComponentMenu("Network/NetworkLobbyPlayer")] + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class NetworkLobbyPlayer : NetworkBehaviour + { + /// + /// This flag controls whether the default UI is shown for the lobby player. + /// As this UI is rendered using the old GUI system, it is only recommended for testing purposes. + /// + [Tooltip("Enable to show the default lobby GUI for this player.")] + [SerializeField] public bool ShowLobbyGUI = true; + + byte m_Slot; + bool m_ReadyToBegin; + + /// + /// The slot within the lobby that this player inhabits. + /// Lobby slots are global for the game - each player has a unique slotId. + /// + public byte slot { get { return m_Slot; } set { m_Slot = value; }} + /// + /// This is a flag that control whether this player is ready for the game to begin. + /// When all players are ready to begin, the game will start. This should not be set directly, the SendReadyToBeginMessage function should be called on the client to set it on the server. + /// + public bool readyToBegin { get { return m_ReadyToBegin; } set { m_ReadyToBegin = value; } } + + void Start() + { + DontDestroyOnLoad(gameObject); + } + + void OnEnable() + { + SceneManager.sceneLoaded += OnSceneLoaded; + } + + void OnDisable() + { + SceneManager.sceneLoaded -= OnSceneLoaded; + } + + public override void OnStartClient() + { + var lobby = GetLobbyManager(); + if (lobby) + { + lobby.lobbySlots[m_Slot] = this; + m_ReadyToBegin = false; + OnClientEnterLobby(); + } + else + { + Debug.LogError("LobbyPlayer could not find a NetworkLobbyManager. The LobbyPlayer requires a NetworkLobbyManager object to function. Make sure that there is one in the scene."); + } + } + + /// + /// This is used on clients to tell the server that this player is ready for the game to begin. + /// + public void SendReadyToBeginMessage() + { + if (LogFilter.logDebug) { Debug.Log("NetworkLobbyPlayer SendReadyToBeginMessage"); } + + var lobby = GetLobbyManager(); + if (lobby) + { + var msg = new LobbyReadyToBeginMessage(); + msg.slotId = (byte)playerControllerId; + msg.readyState = true; + lobby.client.Send(MsgType.LobbyReadyToBegin, msg); + } + } + + /// + /// This is used on clients to tell the server that this player is not ready for the game to begin. + /// + public void SendNotReadyToBeginMessage() + { + if (LogFilter.logDebug) { Debug.Log("NetworkLobbyPlayer SendReadyToBeginMessage"); } + + var lobby = GetLobbyManager(); + if (lobby) + { + var msg = new LobbyReadyToBeginMessage(); + msg.slotId = (byte)playerControllerId; + msg.readyState = false; + lobby.client.Send(MsgType.LobbyReadyToBegin, msg); + } + } + + /// + /// This is used on clients to tell the server that the client has switched from the lobby to the GameScene and is ready to play. + /// This message triggers the server to replace the lobby player with the game player. + /// + public void SendSceneLoadedMessage() + { + if (LogFilter.logDebug) { Debug.Log("NetworkLobbyPlayer SendSceneLoadedMessage"); } + + var lobby = GetLobbyManager(); + if (lobby) + { + var msg = new IntegerMessage(playerControllerId); + lobby.client.Send(MsgType.LobbySceneLoaded, msg); + } + } + + void OnSceneLoaded(Scene scene, LoadSceneMode mode) + { + var lobby = GetLobbyManager(); + if (lobby) + { + // dont even try this in the startup scene + // Should we check if the LoadSceneMode is Single or Additive?? + // Can the lobby scene be loaded Additively?? + string loadedSceneName = scene.name; + if (loadedSceneName == lobby.lobbyScene) + { + return; + } + } + + if (isLocalPlayer) + { + SendSceneLoadedMessage(); + } + } + + NetworkLobbyManager GetLobbyManager() + { + return NetworkManager.singleton as NetworkLobbyManager; + } + + /// + /// This removes this player from the lobby. + /// This player object will be destroyed - on the server and on all clients. + /// + public void RemovePlayer() + { + if (isLocalPlayer && !m_ReadyToBegin) + { + if (LogFilter.logDebug) { Debug.Log("NetworkLobbyPlayer RemovePlayer"); } + + ClientScene.RemovePlayer(GetComponent().playerControllerId); + } + } + + // ------------------------ callbacks ------------------------ + + /// + /// This is a hook that is invoked on all player objects when entering the lobby. + /// Note: isLocalPlayer is not guaranteed to be set until OnStartLocalPlayer is called. + /// + public virtual void OnClientEnterLobby() + { + } + + /// + /// This is a hook that is invoked on all player objects when exiting the lobby. + /// + public virtual void OnClientExitLobby() + { + } + + /// + /// This is a hook that is invoked on clients when a LobbyPlayer switches between ready or not ready. + /// This function is called when the a client player calls SendReadyToBeginMessage() or SendNotReadyToBeginMessage(). + /// + /// Whether the player is ready or not. + public virtual void OnClientReady(bool readyState) + { + } + + // ------------------------ Custom Serialization ------------------------ + + public override bool OnSerialize(NetworkWriter writer, bool initialState) + { + // dirty flag + writer.WritePackedUInt32(1); + + writer.Write(m_Slot); + writer.Write(m_ReadyToBegin); + return true; + } + + public override void OnDeserialize(NetworkReader reader, bool initialState) + { + var dirty = reader.ReadPackedUInt32(); + if (dirty == 0) + return; + + m_Slot = reader.ReadByte(); + m_ReadyToBegin = reader.ReadBoolean(); + } + + // ------------------------ optional UI ------------------------ + + void OnGUI() + { + if (!ShowLobbyGUI) + return; + + var lobby = GetLobbyManager(); + if (lobby) + { + if (!lobby.showLobbyGUI) + return; + + string loadedSceneName = SceneManager.GetSceneAt(0).name; + if (loadedSceneName != lobby.lobbyScene) + return; + } + + Rect rec = new Rect(100 + m_Slot * 100, 200, 90, 20); + + if (isLocalPlayer) + { + string youStr; + if (m_ReadyToBegin) + { + youStr = "(Ready)"; + } + else + { + youStr = "(Not Ready)"; + } + GUI.Label(rec, youStr); + + if (m_ReadyToBegin) + { + rec.y += 25; + if (GUI.Button(rec, "STOP")) + { + SendNotReadyToBeginMessage(); + } + } + else + { + rec.y += 25; + if (GUI.Button(rec, "START")) + { + SendReadyToBeginMessage(); + } + + rec.y += 25; + if (GUI.Button(rec, "Remove")) + { + ClientScene.RemovePlayer(GetComponent().playerControllerId); + } + } + } + else + { + GUI.Label(rec, "Player [" + netId + "]"); + rec.y += 25; + GUI.Label(rec, "Ready [" + m_ReadyToBegin + "]"); + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkManager.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkManager.cs new file mode 100644 index 00000000..63346433 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkManager.cs @@ -0,0 +1,1957 @@ +using System; +using System.Collections.Generic; +using System.Net; +using UnityEngine.Networking.Match; +using UnityEngine.Networking.NetworkSystem; +using UnityEngine.Networking.Types; +using UnityEngine.SceneManagement; + +namespace UnityEngine.Networking +{ + /// + /// Enumeration of methods of where to spawn player objects in multiplayer games. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class PlayerSpawnMethodExample : MonoBehaviour + /// { + /// void Update() + /// { + /// //Press the space key to switch to spawning on a random spawn point + /// if (Input.GetKeyDown(KeyCode.Space)) + /// { + /// //Check that the PlayerSpawnMethod is currently RoundRobin + /// if (NetworkManager.singleton.playerSpawnMethod == PlayerSpawnMethod.RoundRobin) + /// //Switch it to Random spawning if it is + /// NetworkManager.singleton.playerSpawnMethod = PlayerSpawnMethod.Random; + /// //Otherwise switch it to RoundRobin + /// else NetworkManager.singleton.playerSpawnMethod = PlayerSpawnMethod.RoundRobin; + /// } + /// } + /// } + /// + /// + public enum PlayerSpawnMethod + { + Random, + RoundRobin + }; + + /// + /// The NetworkManager is a convenience class for the HLAPI for managing networking systems. + /// For simple network applications the NetworkManager can be used to control the HLAPI. It provides simple ways to start and stop client and servers, to manage scenes, and has virtual functions that user code can use to implement handlers for network events. The NetworkManager deals with one client at a time. The example below shows a minimal network setup. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class Manager : NetworkManager + /// { + /// public override void OnServerConnect(NetworkConnection conn) + /// { + /// Debug.Log("OnPlayerConnected"); + /// } + /// } + /// + /// + [AddComponentMenu("Network/NetworkManager")] + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class NetworkManager : MonoBehaviour + { + // configuration + [SerializeField] int m_NetworkPort = 7777; + [SerializeField] bool m_ServerBindToIP; + [SerializeField] string m_ServerBindAddress = ""; + [SerializeField] string m_NetworkAddress = "localhost"; + [SerializeField] bool m_DontDestroyOnLoad = true; + [SerializeField] bool m_RunInBackground = true; + [SerializeField] bool m_ScriptCRCCheck = true; + [SerializeField] float m_MaxDelay = 0.01f; + [SerializeField] LogFilter.FilterLevel m_LogLevel = (LogFilter.FilterLevel)LogFilter.Info; + [SerializeField] GameObject m_PlayerPrefab; + [SerializeField] bool m_AutoCreatePlayer = true; + [SerializeField] PlayerSpawnMethod m_PlayerSpawnMethod; + [SerializeField] string m_OfflineScene = ""; + [SerializeField] string m_OnlineScene = ""; + [SerializeField] List m_SpawnPrefabs = new List(); + + [SerializeField] bool m_CustomConfig; + [SerializeField] int m_MaxConnections = 4; + [SerializeField] ConnectionConfig m_ConnectionConfig; + [SerializeField] GlobalConfig m_GlobalConfig; + [SerializeField] List m_Channels = new List(); + + [SerializeField] bool m_UseWebSockets; + [SerializeField] bool m_UseSimulator; + [SerializeField] int m_SimulatedLatency = 1; + [SerializeField] float m_PacketLossPercentage; + + [SerializeField] int m_MaxBufferedPackets = ChannelBuffer.MaxPendingPacketCount; + [SerializeField] bool m_AllowFragmentation = true; + + // matchmaking configuration + [SerializeField] string m_MatchHost = "mm.unet.unity3d.com"; + [SerializeField] int m_MatchPort = 443; + /// + /// The name of the current match. + /// A text string indicating the name of the current match in progress. + /// + [SerializeField] public string matchName = "default"; + /// + /// The maximum number of players in the current match. + /// + [SerializeField] public uint matchSize = 4; + + + NetworkMigrationManager m_MigrationManager; + + private EndPoint m_EndPoint; + bool m_ClientLoadedScene; + + static INetworkTransport s_ActiveTransport = new DefaultNetworkTransport(); + + // properties + /// + /// The network port currently in use. + /// For clients, this is the port of the server connected to. For servers, this is the listen port. + /// + public int networkPort { get { return m_NetworkPort; } set { m_NetworkPort = value; } } + /// + /// Flag to tell the server whether to bind to a specific IP address. + /// If this is false, then no specific IP address is bound to (IP_ANY). + /// + public bool serverBindToIP { get { return m_ServerBindToIP; } set { m_ServerBindToIP = value; }} + /// + /// The IP address to bind the server to. + /// This is only used if serverBindToIP is set to true. + /// + public string serverBindAddress { get { return m_ServerBindAddress; } set { m_ServerBindAddress = value; }} + /// + /// The network address currently in use. + /// For clients, this is the address of the server that is connected to. For servers, this is the local address. + /// + public string networkAddress { get { return m_NetworkAddress; } set { m_NetworkAddress = value; } } + /// + /// A flag to control whether the NetworkManager object is destroyed when the scene changes. + /// This should be set if your game has a single NetworkManager that exists for the lifetime of the process. If there is a NetworkManager in each scene, then this should not be set. + /// + public bool dontDestroyOnLoad { get { return m_DontDestroyOnLoad; } set { m_DontDestroyOnLoad = value; } } + /// + /// Controls whether the program runs when it is in the background. + /// This is required when multiple instances of a program using networking are running on the same machine, such as when testing using localhost. But this is not recommended when deploying to mobile platforms. + /// + public bool runInBackground { get { return m_RunInBackground; } set { m_RunInBackground = value; } } + /// + /// Flag for using the script CRC check between server and clients. + /// Enables a CRC check between server and client that ensures the NetworkBehaviour scripts match. This may not be appropriate in some cases, such a when the client and server are different Unity projects. + /// + public bool scriptCRCCheck { get { return m_ScriptCRCCheck; } set { m_ScriptCRCCheck = value; }} + + [Obsolete("moved to NetworkMigrationManager")] + public bool sendPeerInfo { get { return false; } set {} } + + /// + /// The maximum delay before sending packets on connections. + /// In seconds. The default of 0.01 seconds means packets will be delayed at most by 10 milliseconds. Setting this to zero will disable HLAPI connection buffering. + /// + public float maxDelay { get { return m_MaxDelay; } set { m_MaxDelay = value; } } + /// + /// The log level specifically to user for network log messages. + /// + public LogFilter.FilterLevel logLevel { get { return m_LogLevel; } set { m_LogLevel = value; LogFilter.currentLogLevel = (int)value; } } + /// + /// The default prefab to be used to create player objects on the server. + /// Player objects are created in the default handler for AddPlayer() on the server. Implementing OnServerAddPlayer overrides this behaviour. + /// + public GameObject playerPrefab { get { return m_PlayerPrefab; } set { m_PlayerPrefab = value; } } + /// + /// A flag to control whether or not player objects are automatically created on connect, and on scene change. + /// + public bool autoCreatePlayer { get { return m_AutoCreatePlayer; } set { m_AutoCreatePlayer = value; } } + /// + /// The current method of spawning players used by the NetworkManager. + /// + /// //Attach this script to a GameObject + /// //This script switches the Player spawn method between Round Robin spawning and Random spawning when you press the space key in Play Mode. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class Example : NetworkManager + /// { + /// void Start() + /// { + /// //Change the Player Spawn Method to be Round Robin (spawn at the spawn points in order) + /// playerSpawnMethod = PlayerSpawnMethod.RoundRobin; + /// } + /// + /// void Update() + /// { + /// //Press the space key to switch the spawn method + /// if (Input.GetKeyDown(KeyCode.Space)) + /// { + /// //Press the space key to switch from RoundRobin method to Random method (spawn at the spawn points in a random order) + /// if (playerSpawnMethod == PlayerSpawnMethod.RoundRobin) + /// playerSpawnMethod = PlayerSpawnMethod.Random; + /// //Otherwise switch back to RoundRobin at the press of the space key + /// else playerSpawnMethod = PlayerSpawnMethod.RoundRobin; + /// } + /// } + /// } + /// + /// + public PlayerSpawnMethod playerSpawnMethod { get { return m_PlayerSpawnMethod; } set { m_PlayerSpawnMethod = value; } } + /// + /// The scene to switch to when offline. + /// Setting this makes the NetworkManager do scene management. This scene will be switched to when a network session is completed - such as a client disconnect, or a server shutdown. + /// + public string offlineScene { get { return m_OfflineScene; } set { m_OfflineScene = value; } } + /// + /// The scene to switch to when online. + /// Setting this makes the NetworkManager do scene management. This scene will be switched to when a network session is started - such as a client connect, or a server listen. + /// + public string onlineScene { get { return m_OnlineScene; } set { m_OnlineScene = value; } } + /// + /// List of prefabs that will be registered with the spawning system. + /// For each of these prefabs, ClientManager.RegisterPrefab() will be automatically invoke. + /// + public List spawnPrefabs { get { return m_SpawnPrefabs; }} + + /// + /// The list of currently registered player start positions for the current scene. + /// + public List startPositions { get { return s_StartPositions; }} + + /// + /// Flag to enable custom network configuration. + /// + public bool customConfig { get { return m_CustomConfig; } set { m_CustomConfig = value; } } + /// + /// The custom network configuration to use. + /// This will be used to configure the network transport layer. + /// + public ConnectionConfig connectionConfig { get { if (m_ConnectionConfig == null) { m_ConnectionConfig = new ConnectionConfig(); } return m_ConnectionConfig; } } + /// + /// The transport layer global configuration to be used. + /// This defines global settings for the operation of the transport layer. + /// + public GlobalConfig globalConfig { get { if (m_GlobalConfig == null) { m_GlobalConfig = new GlobalConfig(); } return m_GlobalConfig; } } + /// + /// The maximum number of concurrent network connections to support. + /// The effects the memory usage of the network layer. + /// + public int maxConnections { get { return m_MaxConnections; } set { m_MaxConnections = value; } } + /// + /// The Quality-of-Service channels to use for the network transport layer. + /// + public List channels { get { return m_Channels; } } + + /// + /// Allows you to specify an EndPoint object instead of setting networkAddress and networkPort (required for some platforms such as Xbox One). + /// Setting this object overrides the networkAddress and networkPort fields, and will be used instead of making connections. + /// + public EndPoint secureTunnelEndpoint { get { return m_EndPoint; } set { m_EndPoint = value; } } + + /// + /// This makes the NetworkServer listen for WebSockets connections instead of normal transport layer connections. + /// This allows WebGL clients to connect to the server. + /// + public bool useWebSockets { get { return m_UseWebSockets; } set { m_UseWebSockets = value; } } + /// + /// Flag that control whether clients started by this NetworkManager will use simulated latency and packet loss. + /// + public bool useSimulator { get { return m_UseSimulator; } set { m_UseSimulator = value; }} + /// + /// The delay in milliseconds to be added to incoming and outgoing packets for clients. + /// This is only used when useSimulator is set. + /// + public int simulatedLatency { get { return m_SimulatedLatency; } set { m_SimulatedLatency = value; } } + /// + /// The percentage of incoming and outgoing packets to be dropped for clients. + /// This is only used when useSimulator is set. + /// + public float packetLossPercentage { get { return m_PacketLossPercentage; } set { m_PacketLossPercentage = value; } } + + /// + /// The hostname of the matchmaking server. + /// The default address for the MatchMaker is mm.unet.unity3d.com That will connect a client to the nearest datacenter geographically. However because data centers are siloed from each other, players will only see matches occurring inside the data center they are currently connected to. If a player of your game is traveling to another part of the world, for instance, they may interact with a different set of players that are in that data center. You can override this behavior by specifying a particular data center. Keep in mind generally as distance grows so does latency, which is why we run data centers spread out over the world. + /// To connect to a specific data center use one of the following addresses: + /// United States: us1-mm.unet.unity3d.com Europe: eu1-mm.unet.unity3d.com Singapore: ap1-mm.unet.unity3d.com. + /// + public string matchHost { get { return m_MatchHost; } set { m_MatchHost = value; } } + /// + /// The port of the matchmaking service. + /// + public int matchPort { get { return m_MatchPort; } set { m_MatchPort = value; } } + /// + /// This is true if the client loaded a new scene when connecting to the server. + /// This is set before OnClientConnect is called, so it can be checked there to perform different logic if a scene load occurred. + /// + public bool clientLoadedScene { get { return m_ClientLoadedScene; } set { m_ClientLoadedScene = value; } } + + /// + /// The migration manager being used with the NetworkManager. + /// + public NetworkMigrationManager migrationManager { get { return m_MigrationManager; }} + + /// + /// NumPlayers is the number of active player objects across all connections on the server. + /// This is only valid on the host / server. + /// + // only really valid on the server + public int numPlayers + { + get + { + int numPlayers = 0; + for (int i = 0; i < NetworkServer.connections.Count; i++) + { + var conn = NetworkServer.connections[i]; + if (conn == null) + continue; + + for (int ii = 0; ii < conn.playerControllers.Count; ii++) + { + if (conn.playerControllers[ii].IsValid) + { + numPlayers += 1; + } + } + } + return numPlayers; + } + } + + public static INetworkTransport defaultTransport + { + get + { + return new DefaultNetworkTransport(); + } + } + + public static INetworkTransport activeTransport + { + get + { + return s_ActiveTransport; + } + set + { + if (s_ActiveTransport != null && s_ActiveTransport.IsStarted) + { + throw new InvalidOperationException("Cannot change network transport when current transport object is in use."); + } + + if (value == null) + { + throw new ArgumentNullException("Cannot set active transport to null."); + } + + s_ActiveTransport = value; + } + } + + // runtime data + /// + /// The name of the current network scene. + /// This is populated if the NetworkManager is doing scene management. This should not be changed directly. Calls to ServerChangeScene() cause this to change. New clients that connect to a server will automatically load this scene. + /// + static public string networkSceneName = ""; + /// + /// True if the NetworkServer or NetworkClient isactive. + /// This is read-only. Calling StopServer() or StopClient() turns this off. + /// + public bool isNetworkActive; + /// + /// The current NetworkClient being used by the manager. + /// This is populated when StartClient or StartLocalClient are called. + /// + public NetworkClient client; + static List s_StartPositions = new List(); + static int s_StartPositionIndex; + + /// + /// A MatchInfo instance that will be used when StartServer() or StartClient() are called. + /// This should be populated from the data handed to the callback for NetworkMatch.CreateMatch or NetworkMatch.JoinMatch. It contains all the information necessary to connect to the match in question. + /// + // matchmaking runtime data + public MatchInfo matchInfo; + /// + /// The UMatch MatchMaker object. + /// This is populated if StartMatchMaker() has been called. It is used to communicate with the matchmaking service. This should be shut down after the match is complete to clean up its internal state. If this object is null then the client is not setup to communicate with MatchMaker yet. + /// + public NetworkMatch matchMaker; + /// + /// The list of matches that are available to join. + /// This will be populated if UMatch.ListMatches() has been called. It will contain the most recent set of results from calling ListMatches. + /// + public List matches; + /// + /// The NetworkManager singleton object. + /// + /// //Create a GameObject and attach this script + /// //Create two buttons. To do this, go to Create>UI>Button for each. + /// //Click each Button in the Hierarchy, and navigate to the Inspector window. Scroll down to the On Click() section and press the + button to add an action + /// //Attach your GameObject to access the appropriate function you want your Button to do. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class Example : NetworkManager + /// { + /// public void StartHostButton() + /// { + /// singleton.StartHost(); + /// } + /// + /// //Press the "Disconnect" Button to stop the Host + /// public void StopHostButton() + /// { + /// singleton.StopHost(); + /// } + /// } + /// + /// + public static NetworkManager singleton; + + // static message objects to avoid runtime-allocations + static AddPlayerMessage s_AddPlayerMessage = new AddPlayerMessage(); + static RemovePlayerMessage s_RemovePlayerMessage = new RemovePlayerMessage(); + static ErrorMessage s_ErrorMessage = new ErrorMessage(); + + static AsyncOperation s_LoadingSceneAsync; + static NetworkConnection s_ClientReadyConnection; + + // this is used to persist network address between scenes. + static string s_Address; + +#if UNITY_EDITOR + static bool s_DomainReload; + static NetworkManager s_PendingSingleton; + + internal static void OnDomainReload() + { + s_DomainReload = true; + } + + public NetworkManager() + { + s_PendingSingleton = this; + } + +#endif + + void Awake() + { + InitializeSingleton(); + } + + void InitializeSingleton() + { + if (singleton != null && singleton == this) + { + return; + } + + // do this early + var logLevel = (int)m_LogLevel; + if (logLevel != LogFilter.SetInScripting) + { + LogFilter.currentLogLevel = logLevel; + } + + if (m_DontDestroyOnLoad) + { + if (singleton != null) + { + if (LogFilter.logDev) { Debug.Log("Multiple NetworkManagers detected in the scene. Only one NetworkManager can exist at a time. The duplicate NetworkManager will not be used."); } + Destroy(gameObject); + return; + } + if (LogFilter.logDev) { Debug.Log("NetworkManager created singleton (DontDestroyOnLoad)"); } + singleton = this; + if (Application.isPlaying) DontDestroyOnLoad(gameObject); + } + else + { + if (LogFilter.logDev) { Debug.Log("NetworkManager created singleton (ForScene)"); } + singleton = this; + } + + if (m_NetworkAddress != "") + { + s_Address = m_NetworkAddress; + } + else if (s_Address != "") + { + m_NetworkAddress = s_Address; + } + } + + void OnValidate() + { + if (m_SimulatedLatency < 1) m_SimulatedLatency = 1; + if (m_SimulatedLatency > 500) m_SimulatedLatency = 500; + + if (m_PacketLossPercentage < 0) m_PacketLossPercentage = 0; + if (m_PacketLossPercentage > 99) m_PacketLossPercentage = 99; + + if (m_MaxConnections <= 0) m_MaxConnections = 1; + if (m_MaxConnections > 32000) m_MaxConnections = 32000; + + if (m_MaxBufferedPackets <= 0) m_MaxBufferedPackets = 0; + if (m_MaxBufferedPackets > ChannelBuffer.MaxBufferedPackets) + { + m_MaxBufferedPackets = ChannelBuffer.MaxBufferedPackets; + if (LogFilter.logError) { Debug.LogError("NetworkManager - MaxBufferedPackets cannot be more than " + ChannelBuffer.MaxBufferedPackets); } + } + + if (m_PlayerPrefab != null && m_PlayerPrefab.GetComponent() == null) + { + if (LogFilter.logError) { Debug.LogError("NetworkManager - playerPrefab must have a NetworkIdentity."); } + m_PlayerPrefab = null; + } + + if (m_ConnectionConfig != null && m_ConnectionConfig.MinUpdateTimeout <= 0) + { + if (LogFilter.logError) { Debug.LogError("NetworkManager MinUpdateTimeout cannot be zero or less. The value will be reset to 1 millisecond"); } + m_ConnectionConfig.MinUpdateTimeout = 1; + } + + if (m_GlobalConfig != null) + { + if (m_GlobalConfig.ThreadAwakeTimeout <= 0) + { + if (LogFilter.logError) { Debug.LogError("NetworkManager ThreadAwakeTimeout cannot be zero or less. The value will be reset to 1 millisecond"); } + m_GlobalConfig.ThreadAwakeTimeout = 1; + } + } + } + + internal void RegisterServerMessages() + { + NetworkServer.RegisterHandler(MsgType.Connect, OnServerConnectInternal); + NetworkServer.RegisterHandler(MsgType.Disconnect, OnServerDisconnectInternal); + NetworkServer.RegisterHandler(MsgType.Ready, OnServerReadyMessageInternal); + NetworkServer.RegisterHandler(MsgType.AddPlayer, OnServerAddPlayerMessageInternal); + NetworkServer.RegisterHandler(MsgType.RemovePlayer, OnServerRemovePlayerMessageInternal); + NetworkServer.RegisterHandler(MsgType.Error, OnServerErrorInternal); + } + + /// + /// This sets up a NetworkMigrationManager object to work with this NetworkManager. + /// The NetworkManager will automatically call functions on the migration manager, such as NetworkMigrationManager.LostHostOnClient when network events happen. + /// + /// The migration manager object to use with the NetworkManager. + public void SetupMigrationManager(NetworkMigrationManager man) + { + m_MigrationManager = man; + } + + public bool StartServer(ConnectionConfig config, int maxConnections) + { + return StartServer(null, config, maxConnections); + } + + /// + /// This starts a new server. + /// This uses the networkPort property as the listen port. + /// + /// //This is a script that creates a Toggle that you enable to start the Server. + /// //Attach this script to an empty GameObject + /// //Create a Toggle GameObject by going to Create>UI>Toggle. + /// //Click on your empty GameObject. + /// //Click and drag the Toggle GameObject from the Hierarchy to the Toggle section in the Inspector window. + /// + /// using UnityEngine; + /// using UnityEngine.UI; + /// using UnityEngine.Networking; + /// + /// //This makes the GameObject a NetworkManager GameObject + /// public class Example : NetworkManager + /// { + /// public Toggle m_Toggle; + /// Text m_ToggleText; + /// + /// void Start() + /// { + /// //Fetch the Text of the Toggle to allow you to change it later + /// m_ToggleText = m_Toggle.GetComponentInChildren<Text>(); + /// OnOff(false); + /// } + /// + /// //Connect this function to the Toggle to start and stop the Server + /// public void OnOff(bool change) + /// { + /// //Detect when the Toggle returns false + /// if (change == false) + /// { + /// //Stop the Server + /// StopServer(); + /// //Change the text of the Toggle + /// m_ToggleText.text = "Connect Server"; + /// } + /// //Detect when the Toggle returns true + /// if (change == true) + /// { + /// //Start the Server + /// StartServer(); + /// //Change the Toggle Text + /// m_ToggleText.text = "Disconnect Server"; + /// } + /// } + /// + /// //Detect when the Server starts and output the status + /// public override void OnStartServer() + /// { + /// //Output that the Server has started + /// Debug.Log("Server Started!"); + /// } + /// + /// //Detect when the Server stops + /// public override void OnStopServer() + /// { + /// //Output that the Server has stopped + /// Debug.Log("Server Stopped!"); + /// } + /// } + /// + /// + /// True is the server was started. + public bool StartServer() + { + return StartServer(null); + } + + public bool StartServer(MatchInfo info) + { + return StartServer(info, null, -1); + } + + bool StartServer(MatchInfo info, ConnectionConfig config, int maxConnections) + { + InitializeSingleton(); + + OnStartServer(); + + if (m_RunInBackground) + Application.runInBackground = true; + + NetworkCRC.scriptCRCCheck = scriptCRCCheck; + NetworkServer.useWebSockets = m_UseWebSockets; + + if (m_GlobalConfig != null) + { + NetworkManager.activeTransport.Init(m_GlobalConfig); + } + + // passing a config overrides setting the connectionConfig property + if (m_CustomConfig && m_ConnectionConfig != null && config == null) + { + m_ConnectionConfig.Channels.Clear(); + for (int channelId = 0; channelId < m_Channels.Count; channelId++) + { + m_ConnectionConfig.AddChannel(m_Channels[channelId]); + } + NetworkServer.Configure(m_ConnectionConfig, m_MaxConnections); + } + + if (config != null) + { + NetworkServer.Configure(config, maxConnections); + } + + if (info != null) + { + if (!NetworkServer.Listen(info, m_NetworkPort)) + { + if (LogFilter.logError) { Debug.LogError("StartServer listen failed."); } + return false; + } + } + else + { + if (m_ServerBindToIP && !string.IsNullOrEmpty(m_ServerBindAddress)) + { + if (!NetworkServer.Listen(m_ServerBindAddress, m_NetworkPort)) + { + if (LogFilter.logError) { Debug.LogError("StartServer listen on " + m_ServerBindAddress + " failed."); } + return false; + } + } + else + { + if (!NetworkServer.Listen(m_NetworkPort)) + { + if (LogFilter.logError) { Debug.LogError("StartServer listen failed."); } + return false; + } + } + } + + // this must be after Listen(), since that registers the default message handlers + RegisterServerMessages(); + + if (LogFilter.logDebug) { Debug.Log("NetworkManager StartServer port:" + m_NetworkPort); } + isNetworkActive = true; + + // Only change scene if the requested online scene is not blank, and is not already loaded + string loadedSceneName = SceneManager.GetSceneAt(0).name; + if (!string.IsNullOrEmpty(m_OnlineScene) && m_OnlineScene != loadedSceneName && m_OnlineScene != m_OfflineScene) + { + ServerChangeScene(m_OnlineScene); + } + else + { + NetworkServer.SpawnObjects(); + } + return true; + } + + internal void RegisterClientMessages(NetworkClient client) + { + client.RegisterHandler(MsgType.Connect, OnClientConnectInternal); + client.RegisterHandler(MsgType.Disconnect, OnClientDisconnectInternal); + client.RegisterHandler(MsgType.NotReady, OnClientNotReadyMessageInternal); + client.RegisterHandler(MsgType.Error, OnClientErrorInternal); + client.RegisterHandler(MsgType.Scene, OnClientSceneInternal); + + if (m_PlayerPrefab != null) + { + ClientScene.RegisterPrefab(m_PlayerPrefab); + } + for (int i = 0; i < m_SpawnPrefabs.Count; i++) + { + var prefab = m_SpawnPrefabs[i]; + if (prefab != null) + { + ClientScene.RegisterPrefab(prefab); + } + } + } + + /// + /// This allows the NetworkManager to use a client object created externally to the NetworkManager instead of using StartClient(). + /// The StartClient() function creates a client object, but this is not always what is desired. UseExternalClient allows a NetworkClient object to be created by other code and used with the NetworkManager. + /// The client object will have the standard NetworkManager message handlers registered on it. + /// + /// The NetworkClient object to use. + public void UseExternalClient(NetworkClient externalClient) + { + if (m_RunInBackground) + Application.runInBackground = true; + + if (externalClient != null) + { + client = externalClient; + isNetworkActive = true; + RegisterClientMessages(client); + OnStartClient(client); + } + else + { + OnStopClient(); + + // this should stop any game-related systems, but not close the connection + ClientScene.DestroyAllClientObjects(); + ClientScene.HandleClientDisconnect(client.connection); + client = null; + if (!string.IsNullOrEmpty(m_OfflineScene)) + { + ClientChangeScene(m_OfflineScene, false); + } + } + s_Address = m_NetworkAddress; + } + + public NetworkClient StartClient(MatchInfo info, ConnectionConfig config, int hostPort) + { + InitializeSingleton(); + + matchInfo = info; + if (m_RunInBackground) + Application.runInBackground = true; + + isNetworkActive = true; + + if (m_GlobalConfig != null) + { + NetworkManager.activeTransport.Init(m_GlobalConfig); + } + + client = new NetworkClient(); + client.hostPort = hostPort; + + if (config != null) + { + if ((config.UsePlatformSpecificProtocols) && (UnityEngine.Application.platform != RuntimePlatform.PS4)) + throw new ArgumentOutOfRangeException("Platform specific protocols are not supported on this platform"); + + client.Configure(config, 1); + } + else + { + if (m_CustomConfig && m_ConnectionConfig != null) + { + m_ConnectionConfig.Channels.Clear(); + for (int i = 0; i < m_Channels.Count; i++) + { + m_ConnectionConfig.AddChannel(m_Channels[i]); + } + if ((m_ConnectionConfig.UsePlatformSpecificProtocols) && (UnityEngine.Application.platform != RuntimePlatform.PS4)) + throw new ArgumentOutOfRangeException("Platform specific protocols are not supported on this platform"); + client.Configure(m_ConnectionConfig, m_MaxConnections); + } + } + + RegisterClientMessages(client); + if (matchInfo != null) + { + if (LogFilter.logDebug) { Debug.Log("NetworkManager StartClient match: " + matchInfo); } + client.Connect(matchInfo); + } + else if (m_EndPoint != null) + { + if (LogFilter.logDebug) { Debug.Log("NetworkManager StartClient using provided SecureTunnel"); } + client.Connect(m_EndPoint); + } + else + { + if (string.IsNullOrEmpty(m_NetworkAddress)) + { + if (LogFilter.logError) { Debug.LogError("Must set the Network Address field in the manager"); } + return null; + } + if (LogFilter.logDebug) { Debug.Log("NetworkManager StartClient address:" + m_NetworkAddress + " port:" + m_NetworkPort); } + + if (m_UseSimulator) + { + client.ConnectWithSimulator(m_NetworkAddress, m_NetworkPort, m_SimulatedLatency, m_PacketLossPercentage); + } + else + { + client.Connect(m_NetworkAddress, m_NetworkPort); + } + } + + if (m_MigrationManager != null) + { + m_MigrationManager.Initialize(client, matchInfo); + } + + OnStartClient(client); + s_Address = m_NetworkAddress; + return client; + } + + public NetworkClient StartClient(MatchInfo matchInfo) + { + return StartClient(matchInfo, null); + } + + /// + /// This starts a network client. It uses the networkAddress and networkPort properties as the address to connect to. + /// This makes the newly created client connect to the server immediately. + /// + /// The client object created. + public NetworkClient StartClient() + { + return StartClient(null, null); + } + + public NetworkClient StartClient(MatchInfo info, ConnectionConfig config) + { + return StartClient(info, config, 0); + } + + public virtual NetworkClient StartHost(ConnectionConfig config, int maxConnections) + { + OnStartHost(); + if (StartServer(null, config, maxConnections)) + { + var client = ConnectLocalClient(); + OnServerConnect(client.connection); + OnStartClient(client); + return client; + } + return null; + } + + public virtual NetworkClient StartHost(MatchInfo info) + { + OnStartHost(); + matchInfo = info; + if (StartServer(info)) + { + var client = ConnectLocalClient(); + OnStartClient(client); + return client; + } + return null; + } + + /// + /// This starts a network "host" - a server and client in the same application. + /// The client returned from StartHost() is a special "local" client that communicates to the in-process server using a message queue instead of the real network. But in almost all other cases, it can be treated as a normal client. + /// + /// The client object created - this is a "local client". + public virtual NetworkClient StartHost() + { + OnStartHost(); + if (StartServer()) + { + var localClient = ConnectLocalClient(); + OnStartClient(localClient); + return localClient; + } + return null; + } + + NetworkClient ConnectLocalClient() + { + if (LogFilter.logDebug) { Debug.Log("NetworkManager StartHost port:" + m_NetworkPort); } + m_NetworkAddress = "localhost"; + client = ClientScene.ConnectLocalServer(); + RegisterClientMessages(client); + + if (m_MigrationManager != null) + { + m_MigrationManager.Initialize(client, matchInfo); + } + return client; + } + + /// + /// This stops both the client and the server that the manager is using. + /// + public void StopHost() + { + var serverWasActive = NetworkServer.active; + OnStopHost(); + + StopServer(); + StopClient(); + + if (m_MigrationManager != null) + { + if (serverWasActive) + { + m_MigrationManager.LostHostOnHost(); + } + } + } + + /// + /// Stops the server that the manager is using. + /// + public void StopServer() + { + if (!NetworkServer.active) + return; + + OnStopServer(); + + if (LogFilter.logDebug) { Debug.Log("NetworkManager StopServer"); } + isNetworkActive = false; + NetworkServer.Shutdown(); + StopMatchMaker(); + if (!string.IsNullOrEmpty(m_OfflineScene)) + { + ServerChangeScene(m_OfflineScene); + } + CleanupNetworkIdentities(); + } + + /// + /// Stops the client that the manager is using. + /// + public void StopClient() + { + OnStopClient(); + + if (LogFilter.logDebug) { Debug.Log("NetworkManager StopClient"); } + isNetworkActive = false; + if (client != null) + { + // only shutdown this client, not ALL clients. + client.Disconnect(); + client.Shutdown(); + client = null; + } + StopMatchMaker(); + + ClientScene.DestroyAllClientObjects(); + if (!string.IsNullOrEmpty(m_OfflineScene)) + { + ClientChangeScene(m_OfflineScene, false); + } + CleanupNetworkIdentities(); + } + + /// + /// This causes the server to switch scenes and sets the networkSceneName. + /// Clients that connect to this server will automatically switch to this scene. This is called autmatically if onlineScene or offlineScene are set, but it can be called from user code to switch scenes again while the game is in progress. This automatically sets clients to be not-ready. The clients must call NetworkClient.Ready() again to participate in the new scene. + /// + /// The name of the scene to change to. The server will change scene immediately, and a message will be sent to connected clients to ask them to change scene also. + public virtual void ServerChangeScene(string newSceneName) + { + if (string.IsNullOrEmpty(newSceneName)) + { + if (LogFilter.logError) { Debug.LogError("ServerChangeScene empty scene name"); } + return; + } + + if (LogFilter.logDebug) { Debug.Log("ServerChangeScene " + newSceneName); } + NetworkServer.SetAllClientsNotReady(); + networkSceneName = newSceneName; + + s_LoadingSceneAsync = SceneManager.LoadSceneAsync(newSceneName); + + StringMessage msg = new StringMessage(networkSceneName); + NetworkServer.SendToAll(MsgType.Scene, msg); + + s_StartPositionIndex = 0; + s_StartPositions.Clear(); + } + + void CleanupNetworkIdentities() + { + foreach (NetworkIdentity netId in Resources.FindObjectsOfTypeAll()) + { + netId.MarkForReset(); + } + } + + internal void ClientChangeScene(string newSceneName, bool forceReload) + { + if (string.IsNullOrEmpty(newSceneName)) + { + if (LogFilter.logError) { Debug.LogError("ClientChangeScene empty scene name"); } + return; + } + + if (LogFilter.logDebug) { Debug.Log("ClientChangeScene newSceneName:" + newSceneName + " networkSceneName:" + networkSceneName); } + + + if (newSceneName == networkSceneName) + { + if (m_MigrationManager != null) + { + // special case for rejoining a match after host migration + FinishLoadScene(); + return; + } + + if (!forceReload) + { + FinishLoadScene(); + return; + } + } + + s_LoadingSceneAsync = SceneManager.LoadSceneAsync(newSceneName); + networkSceneName = newSceneName; + } + + void FinishLoadScene() + { + // NOTE: this cannot use NetworkClient.allClients[0] - that client may be for a completely different purpose. + + if (client != null) + { + if (s_ClientReadyConnection != null) + { + m_ClientLoadedScene = true; + OnClientConnect(s_ClientReadyConnection); + s_ClientReadyConnection = null; + } + } + else + { + if (LogFilter.logDev) { Debug.Log("FinishLoadScene client is null"); } + } + + if (NetworkServer.active) + { + NetworkServer.SpawnObjects(); + OnServerSceneChanged(networkSceneName); + } + + if (IsClientConnected() && client != null) + { + RegisterClientMessages(client); + OnClientSceneChanged(client.connection); + } + } + + internal static void UpdateScene() + { +#if UNITY_EDITOR + // In the editor, reloading scripts in play mode causes a Mono Domain Reload. + // This gets the transport layer (C++) and HLAPI (C#) out of sync. + // This check below detects that problem and shuts down the transport layer to bring both systems back in sync. + if (singleton == null && s_PendingSingleton != null && s_DomainReload) + { + if (LogFilter.logWarn) { Debug.LogWarning("NetworkManager detected a script reload in the editor. This has caused the network to be shut down."); } + + s_DomainReload = false; + s_PendingSingleton.InitializeSingleton(); + + // destroy network objects + var uvs = FindObjectsOfType(); + foreach (var uv in uvs) + { + GameObject.Destroy(uv.gameObject); + } + + singleton.StopHost(); + + NetworkManager.activeTransport.Shutdown(); + } +#endif + if (singleton == null) + return; + + if (s_LoadingSceneAsync == null) + return; + + if (!s_LoadingSceneAsync.isDone) + return; + + if (LogFilter.logDebug) { Debug.Log("ClientChangeScene done readyCon:" + s_ClientReadyConnection); } + singleton.FinishLoadScene(); + s_LoadingSceneAsync.allowSceneActivation = true; + s_LoadingSceneAsync = null; + } + + void OnDestroy() + { + if (LogFilter.logDev) { Debug.Log("NetworkManager destroyed"); } + } + + /// + /// Registers the transform of a game object as a player spawn location. + /// This is done automatically by NetworkStartPosition components, but can be done manually from user script code. + /// + /// Transform to register. + static public void RegisterStartPosition(Transform start) + { + if (LogFilter.logDebug) { Debug.Log("RegisterStartPosition: (" + start.gameObject.name + ") " + start.position); } + s_StartPositions.Add(start); + } + + /// + /// Unregisters the transform of a game object as a player spawn location. + /// This is done automatically by the NetworkStartPosition component, but can be done manually from user code. + /// + /// + static public void UnRegisterStartPosition(Transform start) + { + if (LogFilter.logDebug) { Debug.Log("UnRegisterStartPosition: (" + start.gameObject.name + ") " + start.position); } + s_StartPositions.Remove(start); + } + + /// + /// This checks if the NetworkManager has a client and that it is connected to a server. + /// This is more specific than NetworkClient.isActive, which will be true if there are any clients active, rather than just the NetworkManager's client. + /// + /// True if the NetworkManagers client is connected to a server. + public bool IsClientConnected() + { + return client != null && client.isConnected; + } + + /// + /// Shuts down the NetworkManager completely and destroy the singleton. + /// This is required if a new NetworkManager instance needs to be created after the original one was destroyed. The example below has a reference to the GameObject with the NetworkManager on it and destroys the instance before calling Shutdown() and switching scenes. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class SwitchToEmptyScene : MonoBehaviour + /// { + /// public GameObject NetworkManagerGameObject; + /// + /// void OnGUI() + /// { + /// if (GUI.Button(new Rect(10, 10, 200, 20), "Switch")) + /// { + /// Destroy(NetworkManagerGameObject); + /// NetworkManager.Shutdown(); + /// Application.LoadLevel("empty"); + /// } + /// } + /// } + /// + /// This cleanup allows a new scene with a new NetworkManager to be loaded. + /// + // this is the only way to clear the singleton, so another instance can be created. + static public void Shutdown() + { + if (singleton == null) + return; + + s_StartPositions.Clear(); + s_StartPositionIndex = 0; + s_ClientReadyConnection = null; + + singleton.StopHost(); + singleton = null; + } + + // ----------------------------- Server Internal Message Handlers -------------------------------- + + internal void OnServerConnectInternal(NetworkMessage netMsg) + { + if (LogFilter.logDebug) { Debug.Log("NetworkManager:OnServerConnectInternal"); } + + netMsg.conn.SetMaxDelay(m_MaxDelay); + + if (m_MaxBufferedPackets != ChannelBuffer.MaxBufferedPackets) + { + for (int channelId = 0; channelId < NetworkServer.numChannels; channelId++) + { + netMsg.conn.SetChannelOption(channelId, ChannelOption.MaxPendingBuffers, m_MaxBufferedPackets); + } + } + + if (!m_AllowFragmentation) + { + for (int channelId = 0; channelId < NetworkServer.numChannels; channelId++) + { + netMsg.conn.SetChannelOption(channelId, ChannelOption.AllowFragmentation, 0); + } + } + + if (networkSceneName != "" && networkSceneName != m_OfflineScene) + { + StringMessage msg = new StringMessage(networkSceneName); + netMsg.conn.Send(MsgType.Scene, msg); + } + + if (m_MigrationManager != null) + { + m_MigrationManager.SendPeerInfo(); + } + OnServerConnect(netMsg.conn); + } + + internal void OnServerDisconnectInternal(NetworkMessage netMsg) + { + if (LogFilter.logDebug) { Debug.Log("NetworkManager:OnServerDisconnectInternal"); } + + if (m_MigrationManager != null) + { + m_MigrationManager.SendPeerInfo(); + } + OnServerDisconnect(netMsg.conn); + } + + internal void OnServerReadyMessageInternal(NetworkMessage netMsg) + { + if (LogFilter.logDebug) { Debug.Log("NetworkManager:OnServerReadyMessageInternal"); } + + OnServerReady(netMsg.conn); + } + + internal void OnServerAddPlayerMessageInternal(NetworkMessage netMsg) + { + if (LogFilter.logDebug) { Debug.Log("NetworkManager:OnServerAddPlayerMessageInternal"); } + + netMsg.ReadMessage(s_AddPlayerMessage); + + if (s_AddPlayerMessage.msgSize != 0) + { + var reader = new NetworkReader(s_AddPlayerMessage.msgData); + OnServerAddPlayer(netMsg.conn, s_AddPlayerMessage.playerControllerId, reader); + } + else + { + OnServerAddPlayer(netMsg.conn, s_AddPlayerMessage.playerControllerId); + } + + if (m_MigrationManager != null) + { + m_MigrationManager.SendPeerInfo(); + } + } + + internal void OnServerRemovePlayerMessageInternal(NetworkMessage netMsg) + { + if (LogFilter.logDebug) { Debug.Log("NetworkManager:OnServerRemovePlayerMessageInternal"); } + + netMsg.ReadMessage(s_RemovePlayerMessage); + + PlayerController player; + netMsg.conn.GetPlayerController(s_RemovePlayerMessage.playerControllerId, out player); + OnServerRemovePlayer(netMsg.conn, player); + netMsg.conn.RemovePlayerController(s_RemovePlayerMessage.playerControllerId); + + if (m_MigrationManager != null) + { + m_MigrationManager.SendPeerInfo(); + } + } + + internal void OnServerErrorInternal(NetworkMessage netMsg) + { + if (LogFilter.logDebug) { Debug.Log("NetworkManager:OnServerErrorInternal"); } + + netMsg.ReadMessage(s_ErrorMessage); + OnServerError(netMsg.conn, s_ErrorMessage.errorCode); + } + + // ----------------------------- Client Internal Message Handlers -------------------------------- + + internal void OnClientConnectInternal(NetworkMessage netMsg) + { + if (LogFilter.logDebug) { Debug.Log("NetworkManager:OnClientConnectInternal"); } + + netMsg.conn.SetMaxDelay(m_MaxDelay); + + string loadedSceneName = SceneManager.GetSceneAt(0).name; + if (string.IsNullOrEmpty(m_OnlineScene) || (m_OnlineScene == m_OfflineScene) || (loadedSceneName == m_OnlineScene)) + { + m_ClientLoadedScene = false; + OnClientConnect(netMsg.conn); + } + else + { + // will wait for scene id to come from the server. + s_ClientReadyConnection = netMsg.conn; + } + } + + internal void OnClientDisconnectInternal(NetworkMessage netMsg) + { + if (LogFilter.logDebug) { Debug.Log("NetworkManager:OnClientDisconnectInternal"); } + + if (m_MigrationManager != null) + { + if (m_MigrationManager.LostHostOnClient(netMsg.conn)) + { + // should OnClientDisconnect be called? + return; + } + } + + if (!string.IsNullOrEmpty(m_OfflineScene)) + { + ClientChangeScene(m_OfflineScene, false); + } + + // If we have a valid connection here drop the client in the matchmaker before shutting down below + if (matchMaker != null && matchInfo != null && matchInfo.networkId != NetworkID.Invalid && matchInfo.nodeId != NodeID.Invalid) + { + matchMaker.DropConnection(matchInfo.networkId, matchInfo.nodeId, matchInfo.domain, OnDropConnection); + } + + OnClientDisconnect(netMsg.conn); + } + + internal void OnClientNotReadyMessageInternal(NetworkMessage netMsg) + { + if (LogFilter.logDebug) { Debug.Log("NetworkManager:OnClientNotReadyMessageInternal"); } + + ClientScene.SetNotReady(); + OnClientNotReady(netMsg.conn); + + // NOTE: s_ClientReadyConnection is not set here! don't want OnClientConnect to be invoked again after scene changes. + } + + internal void OnClientErrorInternal(NetworkMessage netMsg) + { + if (LogFilter.logDebug) { Debug.Log("NetworkManager:OnClientErrorInternal"); } + + netMsg.ReadMessage(s_ErrorMessage); + OnClientError(netMsg.conn, s_ErrorMessage.errorCode); + } + + internal void OnClientSceneInternal(NetworkMessage netMsg) + { + if (LogFilter.logDebug) { Debug.Log("NetworkManager:OnClientSceneInternal"); } + + string newSceneName = netMsg.reader.ReadString(); + + if (IsClientConnected() && !NetworkServer.active) + { + ClientChangeScene(newSceneName, true); + } + } + + // ----------------------------- Server System Callbacks -------------------------------- + + /// + /// Called on the server when a new client connects. + /// Unity calls this on the Server when a Client connects to the Server. Use an override to tell the NetworkManager what to do when a client connects to the server. + /// + /// //Attach this script to a GameObject and add a NetworkHUD component to the GameObject. + /// //Create a Text GameObject (Create>UI>Text) and attach it in the Text field in the Inspector. + /// //This script changes Text on the screen when a client connects to the server + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// using UnityEngine.UI; + /// + /// public class OnServerConnectExample : NetworkManager + /// { + /// //Assign a Text component in the GameObject's Inspector + /// public Text m_Text; + /// + /// //Detect when a client connects to the Server + /// public override void OnServerConnect(NetworkConnection connection) + /// { + /// //Change the text to show the connection and the client's ID + /// m_Text.text = "Client " + connection.connectionId + " Connected!"; + /// } + /// } + /// + /// + /// Connection from client. + public virtual void OnServerConnect(NetworkConnection conn) + { + } + + /// + /// Called on the server when a client disconnects. + /// This is called on the Server when a Client disconnects from the Server. Use an override to decide what should happen when a disconnection is detected. + /// + /// //This script outputs a message when a client connects or disconnects from the server + /// //Attach this script to your GameObject. + /// //Attach a NetworkManagerHUD to your by clicking Add Component in the Inspector window of the GameObject. Then go to Network>NetworkManagerHUD. + /// //Create a Text GameObject and attach it to the Text field in the Inspector. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// using UnityEngine.UI; + /// + /// public class Example : NetworkManager + /// { + /// //Assign a Text component in the GameObject's Inspector + /// public Text m_Text; + /// + /// //Detect when a client connects to the Server + /// public override void OnServerConnect(NetworkConnection connection) + /// { + /// //Change the text to show the connection + /// m_Text.text = "Client " + connection.connectionId + " Connected!"; + /// } + /// + /// //Detect when a client disconnects from the Server + /// public override void OnServerDisconnect(NetworkConnection connection) + /// { + /// //Change the text to show the loss of connection + /// m_Text.text = "Client " + connection.connectionId + "Connection Lost!"; + /// } + /// } + /// + /// + /// Connection from client. + public virtual void OnServerDisconnect(NetworkConnection conn) + { + NetworkServer.DestroyPlayersForConnection(conn); + if (conn.lastError != NetworkError.Ok) + { + if (LogFilter.logError) { Debug.LogError("ServerDisconnected due to error: " + conn.lastError); } + } + } + + /// + /// Called on the server when a client is ready. + /// The default implementation of this function calls NetworkServer.SetClientReady() to continue the network setup process. + /// + /// Connection from client. + public virtual void OnServerReady(NetworkConnection conn) + { + if (conn.playerControllers.Count == 0) + { + // this is now allowed (was not for a while) + if (LogFilter.logDebug) { Debug.Log("Ready with no player object"); } + } + NetworkServer.SetClientReady(conn); + } + + /// + /// Called on the server when a client adds a new player with ClientScene.AddPlayer. + /// The default implementation for this function creates a new player object from the playerPrefab. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// using UnityEngine.Networking.NetworkSystem; + /// + /// class MyManager : NetworkManager + /// { + /// public override void OnServerAddPlayer(NetworkConnection conn, short playerControllerId, NetworkReader extraMessageReader) + /// { + /// if (extraMessageReader != null) + /// { + /// var s = extraMessageReader.ReadMessage<StringMessage>(); + /// Debug.Log("my name is " + s.value); + /// } + /// OnServerAddPlayer(conn, playerControllerId, extraMessageReader); + /// } + /// } + /// + /// + /// Connection from client. + /// Id of the new player. + /// An extra message object passed for the new player. + public virtual void OnServerAddPlayer(NetworkConnection conn, short playerControllerId, NetworkReader extraMessageReader) + { + OnServerAddPlayerInternal(conn, playerControllerId); + } + + public virtual void OnServerAddPlayer(NetworkConnection conn, short playerControllerId) + { + OnServerAddPlayerInternal(conn, playerControllerId); + } + + void OnServerAddPlayerInternal(NetworkConnection conn, short playerControllerId) + { + if (m_PlayerPrefab == null) + { + if (LogFilter.logError) { Debug.LogError("The PlayerPrefab is empty on the NetworkManager. Please setup a PlayerPrefab object."); } + return; + } + + if (m_PlayerPrefab.GetComponent() == null) + { + if (LogFilter.logError) { Debug.LogError("The PlayerPrefab does not have a NetworkIdentity. Please add a NetworkIdentity to the player prefab."); } + return; + } + + if (playerControllerId < conn.playerControllers.Count && conn.playerControllers[playerControllerId].IsValid && conn.playerControllers[playerControllerId].gameObject != null) + { + if (LogFilter.logError) { Debug.LogError("There is already a player at that playerControllerId for this connections."); } + return; + } + + GameObject player; + Transform startPos = GetStartPosition(); + if (startPos != null) + { + player = (GameObject)Instantiate(m_PlayerPrefab, startPos.position, startPos.rotation); + } + else + { + player = (GameObject)Instantiate(m_PlayerPrefab, Vector3.zero, Quaternion.identity); + } + + NetworkServer.AddPlayerForConnection(conn, player, playerControllerId); + } + + /// + /// This finds a spawn position based on NetworkStartPosition objects in the scene. + /// This is used by the default implementation of OnServerAddPlayer. + /// + /// Returns the transform to spawn a player at, or null. + public Transform GetStartPosition() + { + // first remove any dead transforms + if (s_StartPositions.Count > 0) + { + for (int i = s_StartPositions.Count - 1; i >= 0; i--) + { + if (s_StartPositions[i] == null) + s_StartPositions.RemoveAt(i); + } + } + + if (m_PlayerSpawnMethod == PlayerSpawnMethod.Random && s_StartPositions.Count > 0) + { + // try to spawn at a random start location + int index = Random.Range(0, s_StartPositions.Count); + return s_StartPositions[index]; + } + if (m_PlayerSpawnMethod == PlayerSpawnMethod.RoundRobin && s_StartPositions.Count > 0) + { + if (s_StartPositionIndex >= s_StartPositions.Count) + { + s_StartPositionIndex = 0; + } + + Transform startPos = s_StartPositions[s_StartPositionIndex]; + s_StartPositionIndex += 1; + return startPos; + } + return null; + } + + /// + /// Called on the server when a client removes a player. + /// The default implementation of this function destroys the corresponding player object. + /// + /// The connection to remove the player from. + /// The player controller to remove. + public virtual void OnServerRemovePlayer(NetworkConnection conn, PlayerController player) + { + if (player.gameObject != null) + { + NetworkServer.Destroy(player.gameObject); + } + } + + /// + /// Called on the server when a network error occurs for a client connection. + /// + /// Connection from client. + /// Error code. + public virtual void OnServerError(NetworkConnection conn, int errorCode) + { + } + + /// + /// Called on the server when a scene is completed loaded, when the scene load was initiated by the server with ServerChangeScene(). + /// + /// The name of the new scene. + public virtual void OnServerSceneChanged(string sceneName) + { + } + + // ----------------------------- Client System Callbacks -------------------------------- + + /// + /// Called on the client when connected to a server. + /// The default implementation of this function sets the client as ready and adds a player. Override the function to dictate what happens when the client connects. + /// + /// //Attach this script to a GameObject + /// //Create a Text GameObject(Create>UI>Text) and attach it to the Text field in the Inspector window + /// //This script changes the Text depending on if a client connects or disconnects to the server + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// using UnityEngine.UI; + /// + /// public class Example : NetworkManager + /// { + /// //Assign a Text component in the GameObject's Inspector + /// public Text m_ClientText; + /// + /// //Detect when a client connects to the Server + /// public override void OnClientConnect(NetworkConnection connection) + /// { + /// //Change the text to show the connection on the client side + /// m_ClientText.text = " " + connection.connectionId + " Connected!"; + /// } + /// + /// //Detect when a client connects to the Server + /// public override void OnClientDisconnect(NetworkConnection connection) + /// { + /// //Change the text to show the connection loss on the client side + /// m_ClientText.text = "Connection" + connection.connectionId + " Lost!"; + /// } + /// } + /// + /// + /// Connection to the server. + public virtual void OnClientConnect(NetworkConnection conn) + { + if (!clientLoadedScene) + { + // Ready/AddPlayer is usually triggered by a scene load completing. if no scene was loaded, then Ready/AddPlayer it here instead. + ClientScene.Ready(conn); + if (m_AutoCreatePlayer) + { + ClientScene.AddPlayer(0); + } + } + } + + /// + /// Called on clients when disconnected from a server. + /// This is called on the client when it disconnects from the server. Override this function to decide what happens when the client disconnects. + /// + /// //Attach this script to a GameObject + /// //Create a Text GameObject(Create>UI>Text) and attach it to the Text field in the Inspector window + /// //This script changes the Text depending on if a client connects or disconnects to the server + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// using UnityEngine.UI; + /// + /// public class OnClientConnectExample : NetworkManager + /// { + /// //Assign a Text component in the GameObject's Inspector + /// public Text m_ClientText; + /// + /// //Detect when a client connects to the Server + /// public override void OnClientConnect(NetworkConnection connection) + /// { + /// //Change the text to show the connection on the client side + /// m_ClientText.text = " " + connection.connectionId + " Connected!"; + /// } + /// + /// //Detect when a client connects to the Server + /// public override void OnClientDisconnect(NetworkConnection connection) + /// { + /// //Change the text to show the connection loss on the client side + /// m_ClientText.text = "Connection" + connection.connectionId + " Lost!"; + /// } + /// } + /// + /// + /// Connection to the server. + public virtual void OnClientDisconnect(NetworkConnection conn) + { + StopClient(); + if (conn.lastError != NetworkError.Ok) + { + if (LogFilter.logError) { Debug.LogError("ClientDisconnected due to error: " + conn.lastError); } + } + } + + /// + /// Called on clients when a network error occurs. + /// + /// Connection to a server. + /// Error code. + public virtual void OnClientError(NetworkConnection conn, int errorCode) + { + } + + /// + /// Called on clients when a servers tells the client it is no longer ready. + /// This is commonly used when switching scenes. + /// + /// Connection to a server. + public virtual void OnClientNotReady(NetworkConnection conn) + { + } + + /// + /// Called on clients when a scene has completed loaded, when the scene load was initiated by the server. + /// Scene changes can cause player objects to be destroyed. The default implementation of OnClientSceneChanged in the NetworkManager is to add a player object for the connection if no player object exists. + /// + /// The network connection that the scene change message arrived on. + public virtual void OnClientSceneChanged(NetworkConnection conn) + { + // always become ready. + ClientScene.Ready(conn); + + if (!m_AutoCreatePlayer) + { + return; + } + + bool addPlayer = (ClientScene.localPlayers.Count == 0); + bool foundPlayer = false; + for (int i = 0; i < ClientScene.localPlayers.Count; i++) + { + if (ClientScene.localPlayers[i].gameObject != null) + { + foundPlayer = true; + break; + } + } + if (!foundPlayer) + { + // there are players, but their game objects have all been deleted + addPlayer = true; + } + if (addPlayer) + { + ClientScene.AddPlayer(0); + } + } + + // ----------------------------- Matchmaker -------------------------------- + + /// + /// This starts MatchMaker for the NetworkManager. + /// This uses the matchHost and matchPort properties as the address of the MatchMaker service to connect to. Please call SetMatchHost prior to calling this function if you are not using the default MatchMaker address. + /// + public void StartMatchMaker() + { + if (LogFilter.logDebug) { Debug.Log("NetworkManager StartMatchMaker"); } + SetMatchHost(m_MatchHost, m_MatchPort, m_MatchPort == 443); + } + + /// + /// Stops the MatchMaker that the NetworkManager is using. + /// This should be called after a match is complete and before starting or joining a new match. + /// + public void StopMatchMaker() + { + // If we have a valid connection here drop the client in the matchmaker before shutting down below + if (matchMaker != null && matchInfo != null && matchInfo.networkId != NetworkID.Invalid && matchInfo.nodeId != NodeID.Invalid) + { + matchMaker.DropConnection(matchInfo.networkId, matchInfo.nodeId, matchInfo.domain, OnDropConnection); + } + + if (matchMaker != null) + { + Destroy(matchMaker); + matchMaker = null; + } + matchInfo = null; + matches = null; + } + + /// + /// This sets the address of the MatchMaker service. + /// The default address for the MatchMaker is mm.unet.unity3d.com That will connect a client to the nearest datacenter geographically. However because data centers are siloed from each other, players will only see matches occurring inside the data center they are currently connected to. If a player of your game is traveling to another part of the world, for instance, they may interact with a different set of players that are in that data center. You can override this behavior by specifying a particular data center. Keep in mind generally as distance grows so does latency, which is why we run data centers spread out over the world. + /// To connect to a specific data center use one of the following addresses: + /// United States: us1-mm.unet.unity3d.com Europe: eu1-mm.unet.unity3d.com Singapore: ap1-mm.unet.unity3d.com. + /// + /// Hostname of MatchMaker service. + /// Port of MatchMaker service. + /// Protocol used by MatchMaker service. + public void SetMatchHost(string newHost, int port, bool https) + { + if (matchMaker == null) + { + matchMaker = gameObject.AddComponent(); + } + if (newHost == "127.0.0.1") + { + newHost = "localhost"; + } + string prefix = "http://"; + if (https) + { + prefix = "https://"; + } + + if (newHost.StartsWith("http://")) + { + newHost = newHost.Replace("http://", ""); + } + if (newHost.StartsWith("https://")) + { + newHost = newHost.Replace("https://", ""); + } + + m_MatchHost = newHost; + m_MatchPort = port; + + string fullURI = prefix + m_MatchHost + ":" + m_MatchPort; + if (LogFilter.logDebug) { Debug.Log("SetMatchHost:" + fullURI); } + matchMaker.baseUri = new Uri(fullURI); + } + + //------------------------------ Start & Stop callbacks ----------------------------------- + + // Since there are multiple versions of StartServer, StartClient and StartHost, to reliably customize + // their functionality, users would need override all the versions. Instead these callbacks are invoked + // from all versions, so users only need to implement this one case. + + /// + /// This hook is invoked when a host is started. + /// StartHost has multiple signatures, but they all cause this hook to be called. + /// + public virtual void OnStartHost() + { + } + + /// + /// This hook is invoked when a server is started - including when a host is started. + /// StartServer has multiple signatures, but they all cause this hook to be called. + /// + public virtual void OnStartServer() + { + } + + /// + /// This is a hook that is invoked when the client is started. + /// StartClient has multiple signatures, but they all cause this hook to be called. + /// + /// The NetworkClient object that was started. + public virtual void OnStartClient(NetworkClient client) + { + } + + /// + /// This hook is called when a server is stopped - including when a host is stopped. + /// + public virtual void OnStopServer() + { + } + + /// + /// This hook is called when a client is stopped. + /// + public virtual void OnStopClient() + { + } + + /// + /// This hook is called when a host is stopped. + /// + public virtual void OnStopHost() + { + } + + //------------------------------ Matchmaker callbacks ----------------------------------- + + /// + /// Callback that happens when a NetworkMatch.CreateMatch request has been processed on the server. + /// + /// Indicates if the request succeeded. + /// A text description for the error if success is false. + /// The information about the newly created match. + public virtual void OnMatchCreate(bool success, string extendedInfo, MatchInfo matchInfo) + { + if (LogFilter.logDebug) { Debug.LogFormat("NetworkManager OnMatchCreate Success:{0}, ExtendedInfo:{1}, matchInfo:{2}", success, extendedInfo, matchInfo); } + + if (success) + StartHost(matchInfo); + } + + /// + /// Callback that happens when a NetworkMatch.ListMatches request has been processed on the server. + /// + /// Indicates if the request succeeded. + /// A text description for the error if success is false. + /// A list of matches corresponding to the filters set in the initial list request. + public virtual void OnMatchList(bool success, string extendedInfo, List matchList) + { + if (LogFilter.logDebug) { Debug.LogFormat("NetworkManager OnMatchList Success:{0}, ExtendedInfo:{1}, matchList.Count:{2}", success, extendedInfo, matchList.Count); } + + matches = matchList; + } + + /// + /// Callback that happens when a NetworkMatch.JoinMatch request has been processed on the server. + /// + /// Indicates if the request succeeded. + /// A text description for the error if success is false. + /// The info for the newly joined match. + public virtual void OnMatchJoined(bool success, string extendedInfo, MatchInfo matchInfo) + { + if (LogFilter.logDebug) { Debug.LogFormat("NetworkManager OnMatchJoined Success:{0}, ExtendedInfo:{1}, matchInfo:{2}", success, extendedInfo, matchInfo); } + + if (success) + StartClient(matchInfo); + } + + /// + /// Callback that happens when a NetworkMatch.DestroyMatch request has been processed on the server. /// + /// Indicates if the request succeeded. + /// A text description for the error if success is false. + public virtual void OnDestroyMatch(bool success, string extendedInfo) + { + if (LogFilter.logDebug) { Debug.LogFormat("NetworkManager OnDestroyMatch Success:{0}, ExtendedInfo:{1}", success, extendedInfo); } + } + + /// + /// Callback that happens when a NetworkMatch.DropConnection match request has been processed on the server. + /// + /// Indicates if the request succeeded. + /// A text description for the error if success is false. + public virtual void OnDropConnection(bool success, string extendedInfo) + { + if (LogFilter.logDebug) { Debug.LogFormat("NetworkManager OnDropConnection Success:{0}, ExtendedInfo:{1}", success, extendedInfo); } + } + + /// + /// Callback that happens when a NetworkMatch.SetMatchAttributes has been processed on the server. + /// + /// Indicates if the request succeeded. + /// A text description for the error if success is false. + public virtual void OnSetMatchAttributes(bool success, string extendedInfo) + { + if (LogFilter.logDebug) { Debug.LogFormat("NetworkManager OnSetMatchAttributes Success:{0}, ExtendedInfo:{1}", success, extendedInfo); } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkManagerHUD.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkManagerHUD.cs new file mode 100644 index 00000000..9f404a29 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkManagerHUD.cs @@ -0,0 +1,288 @@ +using System; +using System.ComponentModel; + +namespace UnityEngine.Networking +{ + /// + /// An extension for the NetworkManager that displays a default HUD for controlling the network state of the game. + /// This component also shows useful internal state for the networking system in the inspector window of the editor. It allows users to view connections, networked objects, message handlers, and packet statistics. This information can be helpful when debugging networked games. + /// + [AddComponentMenu("Network/NetworkManagerHUD")] + [RequireComponent(typeof(NetworkManager))] + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class NetworkManagerHUD : MonoBehaviour + { + /// + /// The NetworkManager associated with this HUD. + /// + public NetworkManager manager; + /// + /// Whether to show the default control HUD at runtime. + /// + [SerializeField] public bool showGUI = true; + /// + /// The horizontal offset in pixels to draw the HUD runtime GUI at. + /// + [SerializeField] public int offsetX; + /// + /// The vertical offset in pixels to draw the HUD runtime GUI at. + /// + [SerializeField] public int offsetY; + + // Runtime variable + bool m_ShowServer; + + void Awake() + { + manager = GetComponent(); + } + + void Update() + { + if (!showGUI) + return; + + if (!manager.IsClientConnected() && !NetworkServer.active && manager.matchMaker == null) + { + if (UnityEngine.Application.platform != RuntimePlatform.WebGLPlayer) + { + if (Input.GetKeyDown(KeyCode.S)) + { + manager.StartServer(); + } + if (Input.GetKeyDown(KeyCode.H)) + { + manager.StartHost(); + } + } + if (Input.GetKeyDown(KeyCode.C)) + { + manager.StartClient(); + } + } + if (NetworkServer.active) + { + if (manager.IsClientConnected()) + { + if (Input.GetKeyDown(KeyCode.X)) + { + manager.StopHost(); + } + } + else + { + if (Input.GetKeyDown(KeyCode.X)) + { + manager.StopServer(); + } + } + } + } + + void OnGUI() + { + if (!showGUI) + return; + + int xpos = 10 + offsetX; + int ypos = 40 + offsetY; + const int spacing = 24; + + bool noConnection = (manager.client == null || manager.client.connection == null || + manager.client.connection.connectionId == -1); + + if (!manager.IsClientConnected() && !NetworkServer.active && manager.matchMaker == null) + { + if (noConnection) + { + if (UnityEngine.Application.platform != RuntimePlatform.WebGLPlayer) + { + if (GUI.Button(new Rect(xpos, ypos, 200, 20), "LAN Host(H)")) + { + manager.StartHost(); + } + ypos += spacing; + } + + if (GUI.Button(new Rect(xpos, ypos, 105, 20), "LAN Client(C)")) + { + manager.StartClient(); + } + + manager.networkAddress = GUI.TextField(new Rect(xpos + 100, ypos, 95, 20), manager.networkAddress); + ypos += spacing; + + if (UnityEngine.Application.platform == RuntimePlatform.WebGLPlayer) + { + // cant be a server in webgl build + GUI.Box(new Rect(xpos, ypos, 200, 25), "( WebGL cannot be server )"); + ypos += spacing; + } + else + { + if (GUI.Button(new Rect(xpos, ypos, 200, 20), "LAN Server Only(S)")) + { + manager.StartServer(); + } + ypos += spacing; + } + } + else + { + GUI.Label(new Rect(xpos, ypos, 200, 20), "Connecting to " + manager.networkAddress + ":" + manager.networkPort + ".."); + ypos += spacing; + + + if (GUI.Button(new Rect(xpos, ypos, 200, 20), "Cancel Connection Attempt")) + { + manager.StopClient(); + } + } + } + else + { + if (NetworkServer.active) + { + string serverMsg = "Server: port=" + manager.networkPort; + if (manager.useWebSockets) + { + serverMsg += " (Using WebSockets)"; + } + GUI.Label(new Rect(xpos, ypos, 300, 20), serverMsg); + ypos += spacing; + } + if (manager.IsClientConnected()) + { + GUI.Label(new Rect(xpos, ypos, 300, 20), "Client: address=" + manager.networkAddress + " port=" + manager.networkPort); + ypos += spacing; + } + } + + if (manager.IsClientConnected() && !ClientScene.ready) + { + if (GUI.Button(new Rect(xpos, ypos, 200, 20), "Client Ready")) + { + ClientScene.Ready(manager.client.connection); + + if (ClientScene.localPlayers.Count == 0) + { + ClientScene.AddPlayer(0); + } + } + ypos += spacing; + } + + if (NetworkServer.active || manager.IsClientConnected()) + { + if (GUI.Button(new Rect(xpos, ypos, 200, 20), "Stop (X)")) + { + manager.StopHost(); + } + ypos += spacing; + } + + if (!NetworkServer.active && !manager.IsClientConnected() && noConnection) + { + ypos += 10; + + if (UnityEngine.Application.platform == RuntimePlatform.WebGLPlayer) + { + GUI.Box(new Rect(xpos - 5, ypos, 220, 25), "(WebGL cannot use Match Maker)"); + return; + } + + if (manager.matchMaker == null) + { + if (GUI.Button(new Rect(xpos, ypos, 200, 20), "Enable Match Maker (M)")) + { + manager.StartMatchMaker(); + } + ypos += spacing; + } + else + { + if (manager.matchInfo == null) + { + if (manager.matches == null) + { + if (GUI.Button(new Rect(xpos, ypos, 200, 20), "Create Internet Match")) + { + manager.matchMaker.CreateMatch(manager.matchName, manager.matchSize, true, "", "", "", 0, 0, manager.OnMatchCreate); + } + ypos += spacing; + + GUI.Label(new Rect(xpos, ypos, 100, 20), "Room Name:"); + manager.matchName = GUI.TextField(new Rect(xpos + 100, ypos, 100, 20), manager.matchName); + ypos += spacing; + + ypos += 10; + + if (GUI.Button(new Rect(xpos, ypos, 200, 20), "Find Internet Match")) + { + manager.matchMaker.ListMatches(0, 20, "", false, 0, 0, manager.OnMatchList); + } + ypos += spacing; + } + else + { + for (int i = 0; i < manager.matches.Count; i++) + { + var match = manager.matches[i]; + if (GUI.Button(new Rect(xpos, ypos, 200, 20), "Join Match:" + match.name)) + { + manager.matchName = match.name; + manager.matchMaker.JoinMatch(match.networkId, "", "", "", 0, 0, manager.OnMatchJoined); + } + ypos += spacing; + } + + if (GUI.Button(new Rect(xpos, ypos, 200, 20), "Back to Match Menu")) + { + manager.matches = null; + } + ypos += spacing; + } + } + + if (GUI.Button(new Rect(xpos, ypos, 200, 20), "Change MM server")) + { + m_ShowServer = !m_ShowServer; + } + if (m_ShowServer) + { + ypos += spacing; + if (GUI.Button(new Rect(xpos, ypos, 100, 20), "Local")) + { + manager.SetMatchHost("localhost", 1337, false); + m_ShowServer = false; + } + ypos += spacing; + if (GUI.Button(new Rect(xpos, ypos, 100, 20), "Internet")) + { + manager.SetMatchHost("mm.unet.unity3d.com", 443, true); + m_ShowServer = false; + } + ypos += spacing; + if (GUI.Button(new Rect(xpos, ypos, 100, 20), "Staging")) + { + manager.SetMatchHost("staging-mm.unet.unity3d.com", 443, true); + m_ShowServer = false; + } + } + + ypos += spacing; + + GUI.Label(new Rect(xpos, ypos, 300, 20), "MM Uri: " + manager.matchMaker.baseUri); + ypos += spacing; + + if (GUI.Button(new Rect(xpos, ypos, 200, 20), "Disable Match Maker")) + { + manager.StopMatchMaker(); + } + ypos += spacing; + } + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkMessageHandlers.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkMessageHandlers.cs new file mode 100644 index 00000000..60e8e117 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkMessageHandlers.cs @@ -0,0 +1,79 @@ +#if ENABLE_UNET +using System; +using System.Collections.Generic; + +#pragma warning disable 618 +namespace UnityEngine.Networking +{ + internal class NetworkMessageHandlers + { + Dictionary m_MsgHandlers = new Dictionary(); + + internal void RegisterHandlerSafe(short msgType, NetworkMessageDelegate handler) + { + if (handler == null) + { + if (LogFilter.logError) { Debug.LogError("RegisterHandlerSafe id:" + msgType + " handler is null"); } + return; + } + + if (LogFilter.logDebug) { Debug.Log("RegisterHandlerSafe id:" + msgType + " handler:" + handler.GetMethodName()); } + if (m_MsgHandlers.ContainsKey(msgType)) + { + //if (LogFilter.logError) { Debug.LogError("RegisterHandlerSafe id:" + msgType + " handler:" + handler.GetMethodName() + " conflict"); } + return; + } + m_MsgHandlers.Add(msgType, handler); + } + + public void RegisterHandler(short msgType, NetworkMessageDelegate handler) + { + if (handler == null) + { + if (LogFilter.logError) { Debug.LogError("RegisterHandler id:" + msgType + " handler is null"); } + return; + } + + if (msgType <= MsgType.InternalHighest) + { + if (LogFilter.logError) { Debug.LogError("RegisterHandler: Cannot replace system message handler " + msgType); } + return; + } + + if (m_MsgHandlers.ContainsKey(msgType)) + { + if (LogFilter.logDebug) { Debug.Log("RegisterHandler replacing " + msgType); } + + m_MsgHandlers.Remove(msgType); + } + if (LogFilter.logDebug) { Debug.Log("RegisterHandler id:" + msgType + " handler:" + handler.GetMethodName()); } + m_MsgHandlers.Add(msgType, handler); + } + + public void UnregisterHandler(short msgType) + { + m_MsgHandlers.Remove(msgType); + } + + internal NetworkMessageDelegate GetHandler(short msgType) + { + if (m_MsgHandlers.ContainsKey(msgType)) + { + return m_MsgHandlers[msgType]; + } + return null; + } + + internal Dictionary GetHandlers() + { + return m_MsgHandlers; + } + + internal void ClearMessageHandlers() + { + m_MsgHandlers.Clear(); + } + } +} +#pragma warning restore 618 +#endif //ENABLE_UNET diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkMigrationManager.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkMigrationManager.cs new file mode 100644 index 00000000..88c2b814 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkMigrationManager.cs @@ -0,0 +1,1145 @@ + +using System; +using System.Collections.Generic; +using UnityEngine.Networking.Match; +using UnityEngine.Networking.NetworkSystem; +using UnityEngine.Networking.Types; + +namespace UnityEngine.Networking +{ + /// + /// A component that manages the process of a new host taking over a game when the old host is lost. This is referred to as "host migration". The migration manager sends information about each peer in the game to all the clients, and when the host is lost because of a crash or network outage, the clients are able to choose a new host, and continue the game. + /// The old host is able to rejoin the new game on the new host. + /// The state of SyncVars and SyncLists on all objects with NetworkIdentities in the scene is maintained during a host migration. This also applies to custom serialized data for objects. + /// All of the player objects in the game are disabled when the host is lost. Then, when the other clients rejoin the new game on the new host, the corresponding players for those clients are re-enabled on the host, and respawned on the other clients. No player state data is lost during a host migration. + /// This class provides a simple default UI for controlling the behaviour when the host is lost. The UI can be disabled with the showGUI property. There are a number of virtual functions that can be implemented to customize the behaviour of host migration. + /// Note that only data that is available to clients will be preserved during a host migration. If there is data that is only on the server, then it will not be available to the client that becomes the new host. This means data on the host that is not in SyncVars or SyncLists will not be available after a host migration. + /// The callback function OnStartServer is invoked for all networked objects when the client becomes a new host. + /// On the new host, the NetworkMigrationManager uses the function NetworkServer.BecomeNewHost() to construct a networked server scene from the state in the current ClientScene. + /// The peers in a game with host migration enabled are identified by their connectionId on the server. When a client reconnects to the new host of a game, this connectionId is passed to the new host so that it can match this client with the client that was connected to the old host. This Id is set on the ClientScene as the "reconnectId". + /// The old host of the game, the one that crashed or lost its network connection, can also reconnect to the new game as a client. This client uses the special ReconnectId of ClientScene.ReconnectIdHost (which is zero). + /// + [AddComponentMenu("Network/NetworkMigrationManager")] + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class NetworkMigrationManager : MonoBehaviour + { + /// + /// An enumeration of how to handle scene changes when the connection to the host is lost. + /// + public enum SceneChangeOption + { + /// + /// The client should stay in the online scene. + /// + StayInOnlineScene, + /// + /// The client should return to the offline scene. + /// + SwitchToOfflineScene + } + + [SerializeField] + bool m_HostMigration = true; + + [SerializeField] + bool m_ShowGUI = true; + + [SerializeField] + int m_OffsetX = 10; + + [SerializeField] + int m_OffsetY = 300; + + NetworkClient m_Client; + bool m_WaitingToBecomeNewHost; + bool m_WaitingReconnectToNewHost; + bool m_DisconnectedFromHost; + bool m_HostWasShutdown; + + MatchInfo m_MatchInfo; + int m_OldServerConnectionId = -1; + string m_NewHostAddress; + + PeerInfoMessage m_NewHostInfo = new PeerInfoMessage(); + PeerListMessage m_PeerListMessage = new PeerListMessage(); + + PeerInfoMessage[] m_Peers; + + /// + /// Information about a player object from another peer. + /// + // There can be multiple pending players for a connectionId, distinguished by oldNetId/playerControllerId + public struct PendingPlayerInfo + { + /// + /// The networkId of the player object. + /// + public NetworkInstanceId netId; + /// + /// The playerControllerId of the player GameObject. + /// The HLAPI treats players and clients as separate GameObjects. In most cases, there is a single player for each client, but in some situations (for example, when there are multiple controllers connected to a console system) there might be multiple player GameObjects for a single connection. When there are multiple players for a single connection, use the playerControllerId property to tell them apart. This is an identifier that is scoped to the connection, so that it maps to the id of the controller associated with the player on that client. + /// + public short playerControllerId; + /// + /// The gameObject for the player. + /// + public GameObject obj; + } + + /// + /// The player objects for connections to the old host. + /// This is used when clients reconnect to the new host. + /// + public struct ConnectionPendingPlayers + { + /// + /// The list of players for a connection. + /// + public List players; + } + Dictionary m_PendingPlayers = new Dictionary(); + + void AddPendingPlayer(GameObject obj, int connectionId, NetworkInstanceId netId, short playerControllerId) + { + if (!m_PendingPlayers.ContainsKey(connectionId)) + { + var pending = new ConnectionPendingPlayers(); + pending.players = new List(); + m_PendingPlayers[connectionId] = pending; + } + PendingPlayerInfo info = new PendingPlayerInfo(); + info.netId = netId; + info.playerControllerId = playerControllerId; + info.obj = obj; + m_PendingPlayers[connectionId].players.Add(info); + } + + GameObject FindPendingPlayer(int connectionId, NetworkInstanceId netId, short playerControllerId) + { + if (m_PendingPlayers.ContainsKey(connectionId)) + { + for (int i = 0; i < m_PendingPlayers[connectionId].players.Count; i++) + { + var info = m_PendingPlayers[connectionId].players[i]; + if (info.netId == netId && info.playerControllerId == playerControllerId) + { + return info.obj; + } + } + } + return null; + } + + void RemovePendingPlayer(int connectionId) + { + m_PendingPlayers.Remove(connectionId); + } + + /// + /// Controls whether host migration is active. + /// If this is not true, then SendPeerInfo() will not send peer information to clients. + /// + public bool hostMigration + { + get { return m_HostMigration; } + set { m_HostMigration = value; } + } + + /// + /// Flag to toggle display of the default UI. + /// + public bool showGUI + { + get { return m_ShowGUI; } + set { m_ShowGUI = value; } + } + + /// + /// The X offset in pixels of the migration manager default GUI. + /// + public int offsetX + { + get { return m_OffsetX; } + set { m_OffsetX = value; } + } + + /// + /// The Y offset in pixels of the migration manager default GUI. + /// + public int offsetY + { + get { return m_OffsetY; } + set { m_OffsetY = value; } + } + + /// + /// The client instance that is being used to connect to the host. + /// This is populated by the Initialize() method. It will be set automatically by the NetworkManager if one is being used. + /// + public NetworkClient client + { + get { return m_Client; } + } + + /// + /// True if this is a client that was disconnected from the host, and was chosen as the new host. + /// + public bool waitingToBecomeNewHost + { + get { return m_WaitingToBecomeNewHost; } + set { m_WaitingToBecomeNewHost = value; } + } + + /// + /// True if this is a client that was disconnected from the host and is now waiting to reconnect to the new host. + /// + public bool waitingReconnectToNewHost + { + get { return m_WaitingReconnectToNewHost; } + set { m_WaitingReconnectToNewHost = value; } + } + + /// + /// True is this is a client that has been disconnected from a host. + /// + public bool disconnectedFromHost + { + get { return m_DisconnectedFromHost; } + } + + /// + /// True if this was the host and the host has been shut down. + /// + public bool hostWasShutdown + { + get { return m_HostWasShutdown; } + } + + /// + /// Information about the match. This may be null if there is no match. + /// + public MatchInfo matchInfo + { + get { return m_MatchInfo; } + } + + /// + /// The connectionId that this client was assign on the old host. + /// This is the Id that will be set on the ClientScene as the ReconnectId. This Id will be used to identify the client when it connects to the new host. + /// + public int oldServerConnectionId + { + get { return m_OldServerConnectionId; } + } + + /// + /// The IP address of the new host to connect to. + /// The FindNewHost utility function will set this address. Methods of choosing the new host that are implemented by users should also set this address. + /// The default UI button to "Reconnect to New Host" uses this address. + /// + public string newHostAddress + { + get { return m_NewHostAddress; } + set { m_NewHostAddress = value; } + } + + /// + /// The set of peers involved in the game. This includes the host and this client. + /// This is populated on clients when they recieve a MsgType.NetworkInfo message from the host. That message is sent when SendPeerInfo() is called on the host. + /// + public PeerInfoMessage[] peers + { + get { return m_Peers; } + } + + /// + /// The player objects that have been disabled, and are waiting for their corresponding clients to reconnect. + /// There may be multiple pending player GameObjects for each peer. Each will have a different playerControllerId. + /// The HLAPI treats players and clients as separate GameObjects. In most cases, there is a single player for each client, but in some situations (for example, when there are multiple controllers connected to a console system) there might be multiple player GameObjects for a single connection. When there are multiple players for a single connection, use the playerControllerId property to tell them apart. This is an identifier that is scoped to the connection, so that it maps to the id of the controller associated with the player on that client. + /// + public Dictionary pendingPlayers + { + get { return m_PendingPlayers; } + } + + void Start() + { + Reset(ClientScene.ReconnectIdInvalid); + } + + /// + /// Resets the migration manager, and sets the ClientScene's ReconnectId. + /// + /// The connectionId for the ClientScene to use when reconnecting. + public void Reset(int reconnectId) + { + m_OldServerConnectionId = -1; + m_WaitingToBecomeNewHost = false; + m_WaitingReconnectToNewHost = false; + m_DisconnectedFromHost = false; + m_HostWasShutdown = false; + ClientScene.SetReconnectId(reconnectId, m_Peers); + + if (NetworkManager.singleton != null) + { + NetworkManager.singleton.SetupMigrationManager(this); + } + } + + internal void AssignAuthorityCallback(NetworkConnection conn, NetworkIdentity uv, bool authorityState) + { + var msg = new PeerAuthorityMessage(); + msg.connectionId = conn.connectionId; + msg.netId = uv.netId; + msg.authorityState = authorityState; + + if (LogFilter.logDebug) { Debug.Log("AssignAuthorityCallback send for netId" + uv.netId); } + + for (int i = 0; i < NetworkServer.connections.Count; i++) + { + var c = NetworkServer.connections[i]; + if (c != null) + { + c.Send(MsgType.PeerClientAuthority, msg); + } + } + } + + /// + /// Used to initialize the migration manager with client and match information. + /// This is called automatically by the NetworkManager from within StartClient() if a NetworkManager is being used with the migration manager. + /// + /// The NetworkClient being used to connect to the host. + /// Information about the match being used. This may be null if there is no match. + public void Initialize(NetworkClient newClient, MatchInfo newMatchInfo) + { + if (LogFilter.logDev) { Debug.Log("NetworkMigrationManager initialize"); } + + m_Client = newClient; + m_MatchInfo = newMatchInfo; + newClient.RegisterHandlerSafe(MsgType.NetworkInfo, OnPeerInfo); + newClient.RegisterHandlerSafe(MsgType.PeerClientAuthority, OnPeerClientAuthority); + + NetworkIdentity.clientAuthorityCallback = AssignAuthorityCallback; + } + + /// + /// This causes objects for known players to be disabled. + /// These objects are added to the pendingPlayers list, and will be re-enabled when their clients reconnect. + /// This happens when the connection to the host of the game is lost. + /// + public void DisablePlayerObjects() + { + if (LogFilter.logDev) { Debug.Log("NetworkMigrationManager DisablePlayerObjects"); } + + if (m_Peers == null) + return; + + for (int peerId = 0; peerId < m_Peers.Length; peerId++) + { + var peer = m_Peers[peerId]; + if (peer.playerIds != null) + { + for (int i = 0; i < peer.playerIds.Length; i++) + { + var info = peer.playerIds[i]; + if (LogFilter.logDev) { Debug.Log("DisablePlayerObjects disable player for " + peer.address + " netId:" + info.netId + " control:" + info.playerControllerId); } + + GameObject playerObj = ClientScene.FindLocalObject(info.netId); + if (playerObj != null) + { + playerObj.SetActive(false); + + AddPendingPlayer(playerObj, peer.connectionId, info.netId, info.playerControllerId); + } + else + { + if (LogFilter.logWarn) { Debug.LogWarning("DisablePlayerObjects didnt find player Conn:" + peer.connectionId + " NetId:" + info.netId); } + } + } + } + } + } + + /// + /// This sends the set of peers in the game to all the peers in the game. + /// This is called automatically by the NetworkManager if one is active. It happens when clients connect to and disconnect from the server, and when players are added and removed from clients. The function SendPeers() udpates all clients with the information about which client owns which objects. It is automatically called when players are added and removed via the NetworkManager, but there is no hook in the NetworkManager when non-player client authority objects are added and removed. SendPeerInfo() is NOT called automatically. It is up to user code to call SendPeerInfo() when they want to update the set of client-owned objects. + /// + public void SendPeerInfo() + { + if (!m_HostMigration) + return; + + var listMsg = new PeerListMessage(); + var addresses = new List(); + + for (int i = 0; i < NetworkServer.connections.Count; i++) + { + var conn = NetworkServer.connections[i]; + if (conn != null) + { + var peerInfo = new PeerInfoMessage(); + + string address; + int port; + NetworkID networkId; + NodeID node; + byte error2; + NetworkManager.activeTransport.GetConnectionInfo(NetworkServer.serverHostId, conn.connectionId, out address, out port, out networkId, out node, out error2); + + peerInfo.connectionId = conn.connectionId; + peerInfo.port = port; + if (i == 0) + { + peerInfo.port = NetworkServer.listenPort; + peerInfo.isHost = true; + peerInfo.address = ""; + } + else + { + peerInfo.address = address; + peerInfo.isHost = false; + } + var playerIds = new List(); + for (int pid = 0; pid < conn.playerControllers.Count; pid++) + { + var player = conn.playerControllers[pid]; + if (player != null && player.unetView != null) + { + PeerInfoPlayer info; + info.netId = player.unetView.netId; + info.playerControllerId = player.unetView.playerControllerId; + playerIds.Add(info); + } + } + + if (conn.clientOwnedObjects != null) + { + foreach (var netId in conn.clientOwnedObjects) + { + var obj = NetworkServer.FindLocalObject(netId); + if (obj == null) + continue; + + var objUV = obj.GetComponent(); + if (objUV.playerControllerId != -1) + { + // already added players + continue; + } + + PeerInfoPlayer info; + info.netId = netId; + info.playerControllerId = -1; + playerIds.Add(info); + } + } + if (playerIds.Count > 0) + { + peerInfo.playerIds = playerIds.ToArray(); + } + addresses.Add(peerInfo); + } + } + + listMsg.peers = addresses.ToArray(); + + // (re)send all peers to all peers (including the new one) + for (int i = 0; i < NetworkServer.connections.Count; i++) + { + var conn = NetworkServer.connections[i]; + if (conn != null) + { + listMsg.oldServerConnectionId = conn.connectionId; + conn.Send(MsgType.NetworkInfo, listMsg); + } + } + } + + // received on both host and clients + void OnPeerClientAuthority(NetworkMessage netMsg) + { + var msg = netMsg.ReadMessage(); + + if (LogFilter.logDebug) { Debug.Log("OnPeerClientAuthority for netId:" + msg.netId); } + + if (m_Peers == null) + { + // havent received peers yet. just ignore this. the peer list will contain this data. + return; + } + + // find the peer for connId + for (int peerId = 0; peerId < m_Peers.Length; peerId++) + { + var p = m_Peers[peerId]; + if (p.connectionId == msg.connectionId) + { + if (p.playerIds == null) + { + p.playerIds = new PeerInfoPlayer[0]; + } + + if (msg.authorityState) + { + for (int i = 0; i < p.playerIds.Length; i++) + { + if (p.playerIds[i].netId == msg.netId) + { + // already in list + return; + } + } + var newPlayerId = new PeerInfoPlayer(); + newPlayerId.netId = msg.netId; + newPlayerId.playerControllerId = -1; + + var pl = new List(p.playerIds); + pl.Add(newPlayerId); + p.playerIds = pl.ToArray(); + } + else + { + for (int i = 0; i < p.playerIds.Length; i++) + { + if (p.playerIds[i].netId == msg.netId) + { + var pl = new List(p.playerIds); + pl.RemoveAt(i); + p.playerIds = pl.ToArray(); + break; + } + } + } + } + } + + var foundObj = ClientScene.FindLocalObject(msg.netId); + OnAuthorityUpdated(foundObj, msg.connectionId, msg.authorityState); + } + + // recieved on both host and clients + void OnPeerInfo(NetworkMessage netMsg) + { + if (LogFilter.logDebug) { Debug.Log("OnPeerInfo"); } + + netMsg.ReadMessage(m_PeerListMessage); + m_Peers = m_PeerListMessage.peers; + m_OldServerConnectionId = m_PeerListMessage.oldServerConnectionId; + + for (int i = 0; i < m_Peers.Length; i++) + { + if (LogFilter.logDebug) { Debug.Log("peer conn " + m_Peers[i].connectionId + " your conn " + m_PeerListMessage.oldServerConnectionId); } + + if (m_Peers[i].connectionId == m_PeerListMessage.oldServerConnectionId) + { + m_Peers[i].isYou = true; + break; + } + } + OnPeersUpdated(m_PeerListMessage); + } + + void OnServerReconnectPlayerMessage(NetworkMessage netMsg) + { + var msg = netMsg.ReadMessage(); + + if (LogFilter.logDev) { Debug.Log("OnReconnectMessage: connId=" + msg.oldConnectionId + " playerControllerId:" + msg.playerControllerId + " netId:" + msg.netId); } + + var playerObject = FindPendingPlayer(msg.oldConnectionId, msg.netId, msg.playerControllerId); + if (playerObject == null) + { + if (LogFilter.logError) { Debug.LogError("OnReconnectMessage connId=" + msg.oldConnectionId + " player null for netId:" + msg.netId + " msg.playerControllerId:" + msg.playerControllerId); } + return; + } + + if (playerObject.activeSelf) + { + if (LogFilter.logError) { Debug.LogError("OnReconnectMessage connId=" + msg.oldConnectionId + " player already active?"); } + return; + } + + if (LogFilter.logDebug) { Debug.Log("OnReconnectMessage: player=" + playerObject); } + + + NetworkReader extraDataReader = null; + if (msg.msgSize != 0) + { + extraDataReader = new NetworkReader(msg.msgData); + } + + if (msg.playerControllerId != -1) + { + if (extraDataReader == null) + { + OnServerReconnectPlayer(netMsg.conn, playerObject, msg.oldConnectionId, msg.playerControllerId); + } + else + { + OnServerReconnectPlayer(netMsg.conn, playerObject, msg.oldConnectionId, msg.playerControllerId, extraDataReader); + } + } + else + { + OnServerReconnectObject(netMsg.conn, playerObject, msg.oldConnectionId); + } + } + + /// + /// This re-establishes a non-player object with client authority with a client that is reconnected. It is similar to NetworkServer.SpawnWithClientAuthority(). + /// This is called by the default implementation of OnServerReconnectObject. + /// + /// The connection of the new client. + /// The object with client authority that is being reconnected. + /// This client's connectionId on the old host. + /// True if the object was reconnected. + // call this on the server to re-setup an object for a new connection + public bool ReconnectObjectForConnection(NetworkConnection newConnection, GameObject oldObject, int oldConnectionId) + { + if (!NetworkServer.active) + { + if (LogFilter.logError) { Debug.LogError("ReconnectObjectForConnection must have active server"); } + return false; + } + + if (LogFilter.logDebug) { Debug.Log("ReconnectObjectForConnection: oldConnId=" + oldConnectionId + " obj=" + oldObject + " conn:" + newConnection); } + + if (!m_PendingPlayers.ContainsKey(oldConnectionId)) + { + if (LogFilter.logError) { Debug.LogError("ReconnectObjectForConnection oldConnId=" + oldConnectionId + " not found."); } + return false; + } + + oldObject.SetActive(true); + oldObject.GetComponent().SetNetworkInstanceId(new NetworkInstanceId(0)); + + if (!NetworkServer.SpawnWithClientAuthority(oldObject, newConnection)) + { + if (LogFilter.logError) { Debug.LogError("ReconnectObjectForConnection oldConnId=" + oldConnectionId + " SpawnWithClientAuthority failed."); } + return false; + } + + return true; + } + + /// + /// This re-establishes a player object with a client that is reconnected. It is similar to NetworkServer.AddPlayerForConnection(). The player game object will become the player object for the new connection. + /// This is called by the default implementation of OnServerReconnectPlayer. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// class MyMigrationManager : NetworkMigrationManager + /// { + /// protected override void OnServerReconnectPlayer(NetworkConnection newConnection, GameObject oldPlayer, int oldConnectionId, short playerControllerId) + /// { + /// Debug.Log("Reconnecting oldPlayer:" + oldPlayer); + /// ReconnectPlayerForConnection(newConnection, oldPlayer, oldConnectionId, playerControllerId); + /// } + /// } + /// + /// + /// The connection of the new client. + /// The player object. + /// This client's connectionId on the old host. + /// The playerControllerId of the player that is rejoining. + /// True if able to re-add this player. + // call this on the server to re-setup a reconnecting player for a new connection + public bool ReconnectPlayerForConnection(NetworkConnection newConnection, GameObject oldPlayer, int oldConnectionId, short playerControllerId) + { + if (!NetworkServer.active) + { + if (LogFilter.logError) { Debug.LogError("ReconnectPlayerForConnection must have active server"); } + return false; + } + + if (LogFilter.logDebug) { Debug.Log("ReconnectPlayerForConnection: oldConnId=" + oldConnectionId + " player=" + oldPlayer + " conn:" + newConnection); } + + if (!m_PendingPlayers.ContainsKey(oldConnectionId)) + { + if (LogFilter.logError) { Debug.LogError("ReconnectPlayerForConnection oldConnId=" + oldConnectionId + " not found."); } + return false; + } + + oldPlayer.SetActive(true); + + // this ensures the observers are rebuilt for the player object + NetworkServer.Spawn(oldPlayer); + + if (!NetworkServer.AddPlayerForConnection(newConnection, oldPlayer, playerControllerId)) + { + if (LogFilter.logError) { Debug.LogError("ReconnectPlayerForConnection oldConnId=" + oldConnectionId + " AddPlayerForConnection failed."); } + return false; + } + + //NOTE. cannot remove the pending player here - could be more owned objects to come in later messages. + + if (NetworkServer.localClientActive) + { + SendPeerInfo(); + } + + return true; + } + + /// + /// This should be called on a client when it has lost its connection to the host. + /// This will caus the virtual function OnClientDisconnectedFromHost to be invoked. This is called automatically by the NetworkManager if one is in use. + /// + /// The connection of the client that was connected to the host. + /// True if the client should stay in the on-line scene. + // called by NetworkManager on clients when connection to host is lost. + // return true to stay in online scene + public bool LostHostOnClient(NetworkConnection conn) + { + if (LogFilter.logDebug) { Debug.Log("NetworkMigrationManager client OnDisconnectedFromHost"); } + + if (UnityEngine.Application.platform == RuntimePlatform.WebGLPlayer) + { + if (LogFilter.logError) { Debug.LogError("LostHostOnClient: Host migration not supported on WebGL"); } + return false; + } + + if (m_Client == null) + { + if (LogFilter.logError) { Debug.LogError("NetworkMigrationManager LostHostOnHost client was never initialized."); } + return false; + } + + if (!m_HostMigration) + { + if (LogFilter.logError) { Debug.LogError("NetworkMigrationManager LostHostOnHost migration not enabled."); } + return false; + } + + m_DisconnectedFromHost = true; + DisablePlayerObjects(); + + + byte error; + NetworkManager.activeTransport.Disconnect(m_Client.hostId, m_Client.connection.connectionId, out error); + + if (m_OldServerConnectionId != -1) + { + // only call this if we actually connected + SceneChangeOption sceneOption; + OnClientDisconnectedFromHost(conn, out sceneOption); + return sceneOption == SceneChangeOption.StayInOnlineScene; + } + + // never entered the online scene + return false; + } + + /// + /// This should be called on a host when it has has been shutdown. + /// This causes the virtual function OnServerHostShutdown to be invoked. This is called automatically by the NetworkManager if one is in use. + /// + // called by NetworkManager on host when host is closed + public void LostHostOnHost() + { + if (LogFilter.logDebug) { Debug.Log("NetworkMigrationManager LostHostOnHost"); } + + if (UnityEngine.Application.platform == RuntimePlatform.WebGLPlayer) + { + if (LogFilter.logError) { Debug.LogError("LostHostOnHost: Host migration not supported on WebGL"); } + return; + } + + OnServerHostShutdown(); + + if (m_Peers == null) + { + if (LogFilter.logError) { Debug.LogError("NetworkMigrationManager LostHostOnHost no peers"); } + return; + } + + if (m_Peers.Length != 1) + { + // there was another player that could become the host + m_HostWasShutdown = true; + } + } + + /// + /// This causes a client that has been disconnected from the host to become the new host of the game. + /// This starts a server, initializes it with the state of the existing networked objects, and starts a local client so that this client becomes a host. The old NetworkClient instance that was connected to the old host is destroyed. + /// This will cause OnStartServer to be called on networked objects in the scene. + /// Any player objects for this peer will automatically be re-added through the local client that was created. + /// + /// The network port to listen on. + /// True if able to become the new host. + public bool BecomeNewHost(int port) + { + if (LogFilter.logDebug) { Debug.Log("NetworkMigrationManager BecomeNewHost " + m_MatchInfo); } + + NetworkServer.RegisterHandler(MsgType.ReconnectPlayer, OnServerReconnectPlayerMessage); + + var newClient = NetworkServer.BecomeHost(m_Client, port, m_MatchInfo, oldServerConnectionId, peers); + if (newClient != null) + { + if (NetworkManager.singleton != null) + { + NetworkManager.singleton.RegisterServerMessages(); + NetworkManager.singleton.UseExternalClient(newClient); + } + else + { + Debug.LogWarning("MigrationManager BecomeNewHost - No NetworkManager."); + } + + newClient.RegisterHandlerSafe(MsgType.NetworkInfo, OnPeerInfo); + + RemovePendingPlayer(m_OldServerConnectionId); + Reset(ClientScene.ReconnectIdInvalid); + SendPeerInfo(); + return true; + } + else + { + if (LogFilter.logError) { Debug.LogError("NetworkServer.BecomeHost failed"); } + return false; + } + } + + // ----------------------------- Callbacks --------------------------------------- + + /// + /// A virtual function that is called when the client is disconnected from the host. + /// The sceneChange parameter allows the game to choose to stay in the current scene, or switch to the offline scene. + /// + /// The connection to the old host. + /// How to handle scene changes. + // called on client after the connection to host is lost. controls whether to switch scenes + protected virtual void OnClientDisconnectedFromHost(NetworkConnection conn, out SceneChangeOption sceneChange) + { + sceneChange = SceneChangeOption.StayInOnlineScene; + } + + /// + /// A virtual function that is called when the host is shutdown. + /// Calling NetworkManager.StopHost() will cause this function to be invoked if there is an active NetworkMigrationManager. Using the Stop Host button of the NetworkManagerHUD will cause this to be called. + /// + // called on host after the host is lost. host MUST change scenes + protected virtual void OnServerHostShutdown() + { + } + + /// + /// A virtual function that is called on the new host when a client from the old host reconnects to the new host. + /// The base class version of this function calls ReconnectPlayerForConnection() to hookup the new client. + /// ReconnectPlayerForConnection does not have to be called from within this function, it can be done asynchronously. + /// + /// The connection of the new client. + /// The player object associated with this client. + /// The connectionId of this client on the old host. + /// The playerControllerId of the player that is re-joining. + // called on new host (server) when a client from the old host re-connects a player + protected virtual void OnServerReconnectPlayer(NetworkConnection newConnection, GameObject oldPlayer, int oldConnectionId, short playerControllerId) + { + ReconnectPlayerForConnection(newConnection, oldPlayer, oldConnectionId, playerControllerId); + } + + /// + /// A virtual function that is called on the new host when a client from the old host reconnects to the new host. + /// The base class version of this function calls ReconnectPlayerForConnection() to hookup the new client. + /// ReconnectPlayerForConnection does not have to be called from within this function, it can be done asynchronously. + /// + /// The connection of the new client. + /// The player object associated with this client. + /// The connectionId of this client on the old host. + /// The playerControllerId of the player that is re-joining. + /// Additional message data (optional). + // called on new host (server) when a client from the old host re-connects a player + protected virtual void OnServerReconnectPlayer(NetworkConnection newConnection, GameObject oldPlayer, int oldConnectionId, short playerControllerId, NetworkReader extraMessageReader) + { + // extraMessageReader is not used in the default version, but it is available for custom versions to use + ReconnectPlayerForConnection(newConnection, oldPlayer, oldConnectionId, playerControllerId); + } + + /// + /// A virtual function that is called for non-player objects with client authority on the new host when a client from the old host reconnects to the new host. + /// The base class version of this function calls ReconnectObjectForConnection() to hookup the object for the new client. + /// + /// The connection of the new client. + /// The object with authority that is being reconnected. + /// The connectionId of this client on the old host. + // called on new host (server) when a client from the old host re-connects an object with authority + protected virtual void OnServerReconnectObject(NetworkConnection newConnection, GameObject oldObject, int oldConnectionId) + { + ReconnectObjectForConnection(newConnection, oldObject, oldConnectionId); + } + + /// + /// A virtual function that is called when the set of peers in the game changes. + /// This happens when a new client connects to the host, a client disconnects from the host, and when players are added and removed from clients. + /// The list of peers is stored in the member variable peers on the migration manager. This is used when the connection to the host is lost, to choose the new host and to re-add player objects. + /// + /// The set of peers in the game. + // called on both host and client when the set of peers is updated + protected virtual void OnPeersUpdated(PeerListMessage peers) + { + if (LogFilter.logDev) { Debug.Log("NetworkMigrationManager NumPeers " + peers.peers.Length); } + } + + /// + /// A virtual function that is called when the authority of a non-player object changes. + /// This is called on the host and on clients when the AssignClientAuthority, RemoveClientAuthority and NetworkServer.SpawnWithClientAuthority are used. + /// + /// The game object whose authority has changed. + /// The id of the connection whose authority changed for this object. + /// The new authority state for the object. + // called on both host and client when authority changes on a non-player object + protected virtual void OnAuthorityUpdated(GameObject go, int connectionId, bool authorityState) + { + if (LogFilter.logDev) { Debug.Log("NetworkMigrationManager OnAuthorityUpdated for " + go + " conn:" + connectionId + " state:" + authorityState); } + } + + /// + /// This is a utility function to pick one of the peers in the game as the new host. + /// This function implements the default host-choosing strategy of picking the peer with the lowest connectionId on the server. + /// Applications are not required to use this function to choose the new host. They can use any method they want. The choice does not have to be made synchronously, so it is possible to communicate with an external service to choose the new host. + /// However, the default UI of the NetworkMigrationManager calls into this function. + /// + /// Information about the new host, including the IP address. + /// True if this client is to be the new host. + /// True if able to pick a new host. + // utility function called by the default UI on client after connection to host was lost, to pick a new host. + public virtual bool FindNewHost(out NetworkSystem.PeerInfoMessage newHostInfo, out bool youAreNewHost) + { + if (m_Peers == null) + { + if (LogFilter.logError) { Debug.LogError("NetworkMigrationManager FindLowestHost no peers"); } + newHostInfo = null; + youAreNewHost = false; + return false; + } + + if (LogFilter.logDev) { Debug.Log("NetworkMigrationManager FindLowestHost"); } + + const int k_FakeConnectionId = 50000; + + newHostInfo = new PeerInfoMessage(); + newHostInfo.connectionId = k_FakeConnectionId; + newHostInfo.address = ""; + newHostInfo.port = 0; + + int yourConnectionId = -1; + youAreNewHost = false; + + for (int peerId = 0; peerId < m_Peers.Length; peerId++) + { + var peer = m_Peers[peerId]; + if (peer.connectionId == 0) + { + continue; + } + + if (peer.isHost) + { + continue; + } + + if (peer.isYou) + { + yourConnectionId = peer.connectionId; + } + + if (peer.connectionId < newHostInfo.connectionId) + { + newHostInfo = peer; + } + } + if (newHostInfo.connectionId == k_FakeConnectionId) + { + return false; + } + if (newHostInfo.connectionId == yourConnectionId) + { + youAreNewHost = true; + } + + if (LogFilter.logDev) { Debug.Log("FindNewHost new host is " + newHostInfo.address); } + return true; + } + + // ----------------------------- GUI --------------------------------------- + + void OnGUIHost() + { + int ypos = m_OffsetY; + const int spacing = 25; + + GUI.Label(new Rect(m_OffsetX, ypos, 200, 40), "Host Was Shutdown ID(" + m_OldServerConnectionId + ")"); + ypos += spacing; + + if (UnityEngine.Application.platform == RuntimePlatform.WebGLPlayer) + { + GUI.Label(new Rect(m_OffsetX, ypos, 200, 40), "Host Migration not supported for WebGL"); + return; + } + + if (m_WaitingReconnectToNewHost) + { + if (GUI.Button(new Rect(m_OffsetX, ypos, 200, 20), "Reconnect as Client")) + { + Reset(ClientScene.ReconnectIdHost); + + if (NetworkManager.singleton != null) + { + NetworkManager.singleton.networkAddress = GUI.TextField(new Rect(m_OffsetX + 100, ypos, 95, 20), NetworkManager.singleton.networkAddress); + NetworkManager.singleton.StartClient(); + } + else + { + Debug.LogWarning("MigrationManager Old Host Reconnect - No NetworkManager."); + } + } + ypos += spacing; + } + else + { + if (GUI.Button(new Rect(m_OffsetX, ypos, 200, 20), "Pick New Host")) + { + bool youAreNewHost; + if (FindNewHost(out m_NewHostInfo, out youAreNewHost)) + { + m_NewHostAddress = m_NewHostInfo.address; + if (youAreNewHost) + { + // you cannot be the new host.. you were the old host..? + Debug.LogWarning("MigrationManager FindNewHost - new host is self?"); + } + else + { + m_WaitingReconnectToNewHost = true; + } + } + } + ypos += spacing; + } + + if (GUI.Button(new Rect(m_OffsetX, ypos, 200, 20), "Leave Game")) + { + if (NetworkManager.singleton != null) + { + NetworkManager.singleton.SetupMigrationManager(null); + NetworkManager.singleton.StopHost(); + } + else + { + Debug.LogWarning("MigrationManager Old Host LeaveGame - No NetworkManager."); + } + Reset(ClientScene.ReconnectIdInvalid); + } + ypos += spacing; + } + + void OnGUIClient() + { + int ypos = m_OffsetY; + const int spacing = 25; + + GUI.Label(new Rect(m_OffsetX, ypos, 200, 40), "Lost Connection To Host ID(" + m_OldServerConnectionId + ")"); + ypos += spacing; + + if (UnityEngine.Application.platform == RuntimePlatform.WebGLPlayer) + { + GUI.Label(new Rect(m_OffsetX, ypos, 200, 40), "Host Migration not supported for WebGL"); + return; + } + + if (m_WaitingToBecomeNewHost) + { + GUI.Label(new Rect(m_OffsetX, ypos, 200, 40), "You are the new host"); + ypos += spacing; + + if (GUI.Button(new Rect(m_OffsetX, ypos, 200, 20), "Start As Host")) + { + if (NetworkManager.singleton != null) + { + BecomeNewHost(NetworkManager.singleton.networkPort); + } + else + { + Debug.LogWarning("MigrationManager Client BecomeNewHost - No NetworkManager."); + } + } + ypos += spacing; + } + else if (m_WaitingReconnectToNewHost) + { + GUI.Label(new Rect(m_OffsetX, ypos, 200, 40), "New host is " + m_NewHostAddress); + ypos += spacing; + + if (GUI.Button(new Rect(m_OffsetX, ypos, 200, 20), "Reconnect To New Host")) + { + Reset(m_OldServerConnectionId); + + if (NetworkManager.singleton != null) + { + NetworkManager.singleton.networkAddress = m_NewHostAddress; + NetworkManager.singleton.client.ReconnectToNewHost(m_NewHostAddress, NetworkManager.singleton.networkPort); + } + else + { + Debug.LogWarning("MigrationManager Client reconnect - No NetworkManager."); + } + } + ypos += spacing; + } + else + { + if (GUI.Button(new Rect(m_OffsetX, ypos, 200, 20), "Pick New Host")) + { + bool youAreNewHost; + if (FindNewHost(out m_NewHostInfo, out youAreNewHost)) + { + m_NewHostAddress = m_NewHostInfo.address; + if (youAreNewHost) + { + m_WaitingToBecomeNewHost = true; + } + else + { + m_WaitingReconnectToNewHost = true; + } + } + } + ypos += spacing; + } + + if (GUI.Button(new Rect(m_OffsetX, ypos, 200, 20), "Leave Game")) + { + if (NetworkManager.singleton != null) + { + NetworkManager.singleton.SetupMigrationManager(null); + NetworkManager.singleton.StopHost(); + } + else + { + Debug.LogWarning("MigrationManager Client LeaveGame - No NetworkManager."); + } + Reset(ClientScene.ReconnectIdInvalid); + } + ypos += spacing; + } + + void OnGUI() + { + if (!m_ShowGUI) + return; + + if (m_HostWasShutdown) + { + OnGUIHost(); + return; + } + + if (m_DisconnectedFromHost && m_OldServerConnectionId != -1) + { + OnGUIClient(); + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkProximityChecker.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkProximityChecker.cs new file mode 100644 index 00000000..dfa1dc64 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkProximityChecker.cs @@ -0,0 +1,164 @@ +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace UnityEngine.Networking +{ + /// + /// Component that controls visibility of networked objects for players. + /// Any object with this component on it will not be visible to players more than a (configurable) distance away. + /// + [AddComponentMenu("Network/NetworkProximityChecker")] + [RequireComponent(typeof(NetworkIdentity))] + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class NetworkProximityChecker : NetworkBehaviour + { + /// + /// Enumeration of methods to use to check proximity. + /// + public enum CheckMethod + { + /// + /// Use 3D physics to determine proximity. + /// + Physics3D, + /// + /// Use 2D physics to determine proximity. + /// + Physics2D + }; + + /// + /// The maximim range that objects will be visible at. + /// + [TooltipAttribute("The maximum range that objects will be visible at.")] + public int visRange = 10; + + /// + /// How often (in seconds) that this object should update the set of players that can see it. + /// + [TooltipAttribute("How often (in seconds) that this object should update the set of players that can see it.")] + public float visUpdateInterval = 1.0f; // in seconds + + /// + /// Which method to use for checking proximity of players. + /// + [TooltipAttribute("Which method to use for checking proximity of players.\n\nPhysics3D uses 3D physics to determine proximity.\n\nPhysics2D uses 2D physics to determine proximity.")] + public CheckMethod checkMethod = CheckMethod.Physics3D; + + /// + /// Flag to force this object to be hidden for players. + /// If this object is a player object, it will not be hidden for that player. + /// + [TooltipAttribute("Enable to force this object to be hidden from players.")] + public bool forceHidden = false; + + float m_VisUpdateTime; + + void Update() + { + if (!NetworkServer.active) + return; + + if (Time.time - m_VisUpdateTime > visUpdateInterval) + { + GetComponent().RebuildObservers(false); + m_VisUpdateTime = Time.time; + } + } + + // called when a new player enters + public override bool OnCheckObserver(NetworkConnection newObserver) + { + if (forceHidden) + return false; + + // this cant use newObserver.playerControllers[0]. must iterate to find a valid player. + GameObject player = null; + for (int i = 0; i < newObserver.playerControllers.Count; i++) + { + var p = newObserver.playerControllers[i]; + if (p != null && p.gameObject != null) + { + player = p.gameObject; + break; + } + } + if (player == null) + return false; + + var pos = player.transform.position; + return (pos - transform.position).magnitude < visRange; + } + + public override bool OnRebuildObservers(HashSet observers, bool initial) + { + if (forceHidden) + { + // ensure player can still see themself + var uv = GetComponent(); + if (uv.connectionToClient != null) + { + observers.Add(uv.connectionToClient); + } + return true; + } + + // find players within range + switch (checkMethod) + { + case CheckMethod.Physics3D: + { + var hits = Physics.OverlapSphere(transform.position, visRange); + for (int i = 0; i < hits.Length; i++) + { + var hit = hits[i]; + // (if an object has a connectionToClient, it is a player) + var uv = hit.GetComponent(); + if (uv != null && uv.connectionToClient != null) + { + observers.Add(uv.connectionToClient); + } + } + return true; + } + + case CheckMethod.Physics2D: + { + var hits = Physics2D.OverlapCircleAll(transform.position, visRange); + for (int i = 0; i < hits.Length; i++) + { + var hit = hits[i]; + // (if an object has a connectionToClient, it is a player) + var uv = hit.GetComponent(); + if (uv != null && uv.connectionToClient != null) + { + observers.Add(uv.connectionToClient); + } + } + return true; + } + } + return false; + } + + // called hiding and showing objects on the host + public override void OnSetLocalVisibility(bool vis) + { + SetVis(gameObject, vis); + } + + static void SetVis(GameObject go, bool vis) + { + foreach (var r in go.GetComponents()) + { + r.enabled = vis; + } + for (int i = 0; i < go.transform.childCount; i++) + { + var t = go.transform.GetChild(i); + SetVis(t.gameObject, vis); + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkReader.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkReader.cs new file mode 100644 index 00000000..61c30d36 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkReader.cs @@ -0,0 +1,740 @@ +using System; +using System.Text; +using UnityEngine; + +namespace UnityEngine.Networking +{ + /// + /// General purpose serializer for UNET (for reading byte arrays). + /// This class works with NetworkWriter and is used for serializing data for UNet commands, RPC calls, events and low level messages. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class ExampleScript : MonoBehaviour + /// { + /// // Writing data to a NetworkWriter and then + /// // Converting this to a NetworkReader. + /// void Start() + /// { + /// // The data you add to your writer must be prefixed with a message type. + /// // This is in the form of a short. + /// short myMsgType = 143; + /// NetworkWriter writer = new NetworkWriter(); + /// // You start the message in your writer by passing in the message type. + /// // This is a short meaning that it will take up 2 bytes at the start of + /// // your message. + /// writer.StartMessage(myMsgType); + /// // You can now begin your message. In this case we will just use strings. + /// writer.Write("Test data 1"); + /// writer.Write("Test data 2"); + /// writer.Write("Test data 3"); + /// // Make sure to end your message with FinishMessage() + /// writer.FinishMessage(); + /// // You can now access the data in your writer. ToArray() returns a copy + /// // of the bytes that the writer is using and AsArray() returns the + /// // internal array of bytes, not a copy. + /// byte[] writerData = writer.ToArray(); + /// CreateNetworkReader(writerData); + /// } + /// + /// void CreateNetworkReader(byte[] data) + /// { + /// // We will create the NetworkReader using the data from our previous + /// // NetworkWriter. + /// NetworkReader networkReader = new NetworkReader(data); + /// // The first two bytes in the buffer represent the size + /// // of the message. This is equal to the NetworkReader.Length + /// // minus the size of the prefix. + /// byte[] readerMsgSizeData = networkReader.ReadBytes(2); + /// short readerMsgSize = (short)((readerMsgSizeData[1] << 8) + readerMsgSizeData[0]); + /// Debug.Log(readerMsgSize); + /// // The message type added in NetworkWriter.StartMessage + /// // is to be read now. It is a short and so consists of + /// // two bytes. It is the second two bytes on the buffer. + /// byte[] readerMsgTypeData = networkReader.ReadBytes(2); + /// short readerMsgType = (short)((readerMsgTypeData[1] << 8) + readerMsgTypeData[0]); + /// Debug.Log(readerMsgType); + /// // If all of your data is of the same type (in this case the + /// // data on our buffer is comprised of only strings) you can + /// // read all the data from the buffer using a loop like so. + /// while (networkReader.Position < networkReader.Length) + /// { + /// Debug.Log(networkReader.ReadString()); + /// } + /// } + /// } + /// + /// + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class NetworkReader + { + NetBuffer m_buf; + + const int k_MaxStringLength = 1024 * 32; + const int k_InitialStringBufferSize = 1024; + static byte[] s_StringReaderBuffer; + static Encoding s_Encoding; + + /// + /// Creates a new NetworkReader object. + /// + public NetworkReader() + { + m_buf = new NetBuffer(); + Initialize(); + } + + /// + /// Creates a new NetworkReader object. + /// + /// A buffer to construct the reader with, this buffer is NOT copied. + public NetworkReader(NetworkWriter writer) + { + m_buf = new NetBuffer(writer.AsArray()); + Initialize(); + } + + public NetworkReader(byte[] buffer) + { + m_buf = new NetBuffer(buffer); + Initialize(); + } + + static void Initialize() + { + if (s_Encoding == null) + { + s_StringReaderBuffer = new byte[k_InitialStringBufferSize]; + s_Encoding = new UTF8Encoding(); + } + } + + /// + /// The current position within the buffer. + /// See NetworkReader for a code example. + /// + public uint Position { get { return m_buf.Position; } } + /// + /// The current length of the buffer. + /// See NetworkReader for a code example. + /// + public int Length { get { return m_buf.Length; } } + + /// + /// Sets the current position of the reader's stream to the start of the stream. + /// + public void SeekZero() + { + m_buf.SeekZero(); + } + + internal void Replace(byte[] buffer) + { + m_buf.Replace(buffer); + } + + // http://sqlite.org/src4/doc/trunk/www/varint.wiki + // NOTE: big endian. + + /// + /// Reads a 32-bit variable-length-encoded value. + /// + /// The 32 bit value read. + public UInt32 ReadPackedUInt32() + { + byte a0 = ReadByte(); + if (a0 < 241) + { + return a0; + } + byte a1 = ReadByte(); + if (a0 >= 241 && a0 <= 248) + { + return (UInt32)(240 + 256 * (a0 - 241) + a1); + } + byte a2 = ReadByte(); + if (a0 == 249) + { + return (UInt32)(2288 + 256 * a1 + a2); + } + byte a3 = ReadByte(); + if (a0 == 250) + { + return a1 + (((UInt32)a2) << 8) + (((UInt32)a3) << 16); + } + byte a4 = ReadByte(); + if (a0 >= 251) + { + return a1 + (((UInt32)a2) << 8) + (((UInt32)a3) << 16) + (((UInt32)a4) << 24); + } + throw new IndexOutOfRangeException("ReadPackedUInt32() failure: " + a0); + } + + /// + /// Reads a 64-bit variable-length-encoded value. + /// + /// The 64 bit value read. + public UInt64 ReadPackedUInt64() + { + byte a0 = ReadByte(); + if (a0 < 241) + { + return a0; + } + byte a1 = ReadByte(); + if (a0 >= 241 && a0 <= 248) + { + return 240 + 256 * (a0 - ((UInt64)241)) + a1; + } + byte a2 = ReadByte(); + if (a0 == 249) + { + return 2288 + (((UInt64)256) * a1) + a2; + } + byte a3 = ReadByte(); + if (a0 == 250) + { + return a1 + (((UInt64)a2) << 8) + (((UInt64)a3) << 16); + } + byte a4 = ReadByte(); + if (a0 == 251) + { + return a1 + (((UInt64)a2) << 8) + (((UInt64)a3) << 16) + (((UInt64)a4) << 24); + } + + + byte a5 = ReadByte(); + if (a0 == 252) + { + return a1 + (((UInt64)a2) << 8) + (((UInt64)a3) << 16) + (((UInt64)a4) << 24) + (((UInt64)a5) << 32); + } + + + byte a6 = ReadByte(); + if (a0 == 253) + { + return a1 + (((UInt64)a2) << 8) + (((UInt64)a3) << 16) + (((UInt64)a4) << 24) + (((UInt64)a5) << 32) + (((UInt64)a6) << 40); + } + + + byte a7 = ReadByte(); + if (a0 == 254) + { + return a1 + (((UInt64)a2) << 8) + (((UInt64)a3) << 16) + (((UInt64)a4) << 24) + (((UInt64)a5) << 32) + (((UInt64)a6) << 40) + (((UInt64)a7) << 48); + } + + + byte a8 = ReadByte(); + if (a0 == 255) + { + return a1 + (((UInt64)a2) << 8) + (((UInt64)a3) << 16) + (((UInt64)a4) << 24) + (((UInt64)a5) << 32) + (((UInt64)a6) << 40) + (((UInt64)a7) << 48) + (((UInt64)a8) << 56); + } + throw new IndexOutOfRangeException("ReadPackedUInt64() failure: " + a0); + } + + /// + /// Reads a NetworkInstanceId from the stream. + /// + /// The NetworkInstanceId read. + public NetworkInstanceId ReadNetworkId() + { + return new NetworkInstanceId(ReadPackedUInt32()); + } + + /// + /// Reads a NetworkSceneId from the stream. + /// + /// The NetworkSceneId read. + public NetworkSceneId ReadSceneId() + { + return new NetworkSceneId(ReadPackedUInt32()); + } + + /// + /// Reads a byte from the stream. + /// + /// The value read. + public byte ReadByte() + { + return m_buf.ReadByte(); + } + + /// + /// Reads a signed byte from the stream. + /// + /// Value read + public sbyte ReadSByte() + { + return (sbyte)m_buf.ReadByte(); + } + + /// + /// Reads a signed 16 bit integer from the stream. + /// + /// Value read + public short ReadInt16() + { + ushort value = 0; + value |= m_buf.ReadByte(); + value |= (ushort)(m_buf.ReadByte() << 8); + return (short)value; + } + + /// + /// Reads an unsigned 16 bit integer from the stream. + /// + /// Value read + public ushort ReadUInt16() + { + ushort value = 0; + value |= m_buf.ReadByte(); + value |= (ushort)(m_buf.ReadByte() << 8); + return value; + } + + /// + /// Reads a signed 32bit integer from the stream. + /// + /// Value read + public int ReadInt32() + { + uint value = 0; + value |= m_buf.ReadByte(); + value |= (uint)(m_buf.ReadByte() << 8); + value |= (uint)(m_buf.ReadByte() << 16); + value |= (uint)(m_buf.ReadByte() << 24); + return (int)value; + } + + /// + /// Reads an unsigned 32 bit integer from the stream. + /// + /// Value read + public uint ReadUInt32() + { + uint value = 0; + value |= m_buf.ReadByte(); + value |= (uint)(m_buf.ReadByte() << 8); + value |= (uint)(m_buf.ReadByte() << 16); + value |= (uint)(m_buf.ReadByte() << 24); + return value; + } + + /// + /// Reads a signed 64 bit integer from the stream. + /// + /// Value read + public long ReadInt64() + { + ulong value = 0; + + ulong other = m_buf.ReadByte(); + value |= other; + + other = ((ulong)m_buf.ReadByte()) << 8; + value |= other; + + other = ((ulong)m_buf.ReadByte()) << 16; + value |= other; + + other = ((ulong)m_buf.ReadByte()) << 24; + value |= other; + + other = ((ulong)m_buf.ReadByte()) << 32; + value |= other; + + other = ((ulong)m_buf.ReadByte()) << 40; + value |= other; + + other = ((ulong)m_buf.ReadByte()) << 48; + value |= other; + + other = ((ulong)m_buf.ReadByte()) << 56; + value |= other; + + return (long)value; + } + + /// + /// Reads an unsigned 64 bit integer from the stream. + /// + /// Value read + public ulong ReadUInt64() + { + ulong value = 0; + ulong other = m_buf.ReadByte(); + value |= other; + + other = ((ulong)m_buf.ReadByte()) << 8; + value |= other; + + other = ((ulong)m_buf.ReadByte()) << 16; + value |= other; + + other = ((ulong)m_buf.ReadByte()) << 24; + value |= other; + + other = ((ulong)m_buf.ReadByte()) << 32; + value |= other; + + other = ((ulong)m_buf.ReadByte()) << 40; + value |= other; + + other = ((ulong)m_buf.ReadByte()) << 48; + value |= other; + + other = ((ulong)m_buf.ReadByte()) << 56; + value |= other; + return value; + } + + /// + /// Reads a decimal from the stream. + /// + /// Value read + public decimal ReadDecimal() + { + Int32[] bits = new Int32[4]; + + bits[0] = ReadInt32(); + bits[1] = ReadInt32(); + bits[2] = ReadInt32(); + bits[3] = ReadInt32(); + + return new decimal(bits); + } + + /// + /// Reads a float from the stream. + /// + /// Value read + public float ReadSingle() + { + uint value = ReadUInt32(); + return FloatConversion.ToSingle(value); + } + + /// + /// Reads a double from the stream. + /// + /// Value read + public double ReadDouble() + { + ulong value = ReadUInt64(); + return FloatConversion.ToDouble(value); + } + + /// + /// Reads a string from the stream. (max of 32k bytes). + /// See NetworkReader for a code example. + /// + /// Value read. + public string ReadString() + { + UInt16 numBytes = ReadUInt16(); + if (numBytes == 0) + return ""; + + if (numBytes >= k_MaxStringLength) + { + throw new IndexOutOfRangeException("ReadString() too long: " + numBytes); + } + + while (numBytes > s_StringReaderBuffer.Length) + { + s_StringReaderBuffer = new byte[s_StringReaderBuffer.Length * 2]; + } + + m_buf.ReadBytes(s_StringReaderBuffer, numBytes); + + char[] chars = s_Encoding.GetChars(s_StringReaderBuffer, 0, numBytes); + return new string(chars); + } + + /// + /// Reads a char from the stream. + /// + /// Value read. + public char ReadChar() + { + return (char)m_buf.ReadByte(); + } + + /// + /// Reads a boolean from the stream. + /// + /// The value read. + public bool ReadBoolean() + { + int value = m_buf.ReadByte(); + return value == 1; + } + + /// + /// Reads a number of bytes from the stream. + /// See NetworkReader for a code example. + /// + /// Number of bytes to read. + /// Bytes read. (this is a copy). + public byte[] ReadBytes(int count) + { + if (count < 0) + { + throw new IndexOutOfRangeException("NetworkReader ReadBytes " + count); + } + //TODO: Allocation! + byte[] value = new byte[count]; + m_buf.ReadBytes(value, (uint)count); + return value; + } + + /// + /// This read a 16-bit byte count and a array of bytes of that size from the stream. + /// The format used by this function is the same as NetworkWriter.WriteBytesAndSize(). + /// + /// The bytes read from the stream. + public byte[] ReadBytesAndSize() + { + ushort sz = ReadUInt16(); + if (sz == 0) + return new byte[0]; + + return ReadBytes(sz); + } + + /// + /// Reads a Unity Vector2 object. + /// + /// The vector read from the stream. + public Vector2 ReadVector2() + { + return new Vector2(ReadSingle(), ReadSingle()); + } + + /// + /// Reads a Unity Vector3 objects. + /// + /// The vector read from the stream. + public Vector3 ReadVector3() + { + return new Vector3(ReadSingle(), ReadSingle(), ReadSingle()); + } + + /// + /// Reads a Unity Vector4 object. + /// + /// The vector read from the stream + public Vector4 ReadVector4() + { + return new Vector4(ReadSingle(), ReadSingle(), ReadSingle(), ReadSingle()); + } + + /// + /// Reads a unity Color objects. + /// + /// The color read from the stream. + public Color ReadColor() + { + return new Color(ReadSingle(), ReadSingle(), ReadSingle(), ReadSingle()); + } + + /// + /// Reads a unity color32 objects. + /// + /// The color read from the stream. + public Color32 ReadColor32() + { + return new Color32(ReadByte(), ReadByte(), ReadByte(), ReadByte()); + } + + /// + /// Reads a Unity Quaternion object. + /// + /// The quaternion read from the stream. + public Quaternion ReadQuaternion() + { + return new Quaternion(ReadSingle(), ReadSingle(), ReadSingle(), ReadSingle()); + } + + /// + /// Reads a Unity Rect object. + /// + /// The rect read from the stream. + public Rect ReadRect() + { + return new Rect(ReadSingle(), ReadSingle(), ReadSingle(), ReadSingle()); + } + + /// + /// Reads a unity Plane object. + /// + /// The plane read from the stream. + public Plane ReadPlane() + { + return new Plane(ReadVector3(), ReadSingle()); + } + + /// + /// Reads a Unity Ray object. + /// + /// The ray read from the stream. + public Ray ReadRay() + { + return new Ray(ReadVector3(), ReadVector3()); + } + + /// + /// Reads a unity Matrix4x4 object. + /// + /// The matrix read from the stream. + public Matrix4x4 ReadMatrix4x4() + { + Matrix4x4 m = new Matrix4x4(); + m.m00 = ReadSingle(); + m.m01 = ReadSingle(); + m.m02 = ReadSingle(); + m.m03 = ReadSingle(); + m.m10 = ReadSingle(); + m.m11 = ReadSingle(); + m.m12 = ReadSingle(); + m.m13 = ReadSingle(); + m.m20 = ReadSingle(); + m.m21 = ReadSingle(); + m.m22 = ReadSingle(); + m.m23 = ReadSingle(); + m.m30 = ReadSingle(); + m.m31 = ReadSingle(); + m.m32 = ReadSingle(); + m.m33 = ReadSingle(); + return m; + } + + /// + /// Reads a NetworkHash128 assetId. + /// + /// The assetId object read from the stream. + public NetworkHash128 ReadNetworkHash128() + { + NetworkHash128 hash; + hash.i0 = ReadByte(); + hash.i1 = ReadByte(); + hash.i2 = ReadByte(); + hash.i3 = ReadByte(); + hash.i4 = ReadByte(); + hash.i5 = ReadByte(); + hash.i6 = ReadByte(); + hash.i7 = ReadByte(); + hash.i8 = ReadByte(); + hash.i9 = ReadByte(); + hash.i10 = ReadByte(); + hash.i11 = ReadByte(); + hash.i12 = ReadByte(); + hash.i13 = ReadByte(); + hash.i14 = ReadByte(); + hash.i15 = ReadByte(); + return hash; + } + + /// + /// Reads a reference to a Transform from the stream. + /// The game object of this Transform must have a NetworkIdentity. + /// + /// The transform object read. + public Transform ReadTransform() + { + NetworkInstanceId netId = ReadNetworkId(); + if (netId.IsEmpty()) + { + return null; + } + GameObject go = ClientScene.FindLocalObject(netId); + if (go == null) + { + if (LogFilter.logDebug) { Debug.Log("ReadTransform netId:" + netId); } + return null; + } + + return go.transform; + } + + /// + /// Reads a reference to a GameObject from the stream. + /// + /// The GameObject referenced. + public GameObject ReadGameObject() + { + NetworkInstanceId netId = ReadNetworkId(); + if (netId.IsEmpty()) + { + return null; + } + + GameObject go; + if (NetworkServer.active) + { + go = NetworkServer.FindLocalObject(netId); + } + else + { + go = ClientScene.FindLocalObject(netId); + } + if (go == null) + { + if (LogFilter.logDebug) { Debug.Log("ReadGameObject netId:" + netId + "go: null"); } + } + + return go; + } + + /// + /// Reads a reference to a NetworkIdentity from the stream. + /// + /// The NetworkIdentity object read. + public NetworkIdentity ReadNetworkIdentity() + { + NetworkInstanceId netId = ReadNetworkId(); + if (netId.IsEmpty()) + { + return null; + } + GameObject go; + if (NetworkServer.active) + { + go = NetworkServer.FindLocalObject(netId); + } + else + { + go = ClientScene.FindLocalObject(netId); + } + if (go == null) + { + if (LogFilter.logDebug) { Debug.Log("ReadNetworkIdentity netId:" + netId + "go: null"); } + return null; + } + + return go.GetComponent(); + } + + /// + /// Returns a string representation of the reader's buffer. + /// + /// Buffer contents. + public override string ToString() + { + return m_buf.ToString(); + } + + /// + /// This is a utility function to read a typed network message from the stream. + /// + /// The type of the Network Message, must be derived from MessageBase. + /// + public TMsg ReadMessage() where TMsg : MessageBase, new() + { + var msg = new TMsg(); + msg.Deserialize(this); + return msg; + } + }; +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkScene.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkScene.cs new file mode 100644 index 00000000..5ddd06f9 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkScene.cs @@ -0,0 +1,289 @@ +#if ENABLE_UNET +using System; +using System.Collections.Generic; + +#pragma warning disable 618 +namespace UnityEngine.Networking +{ + // This is an internal class to allow the client and server to share scene-related functionality. + // This code (mostly) used to be in ClientScene. + internal class NetworkScene + { + // localObjects is NOT static. For the Host, even though there is one scene and gameObjects are + // shared with the localClient, the set of active objects for each must be separate to prevent + // out-of-order object initialization problems. + Dictionary m_LocalObjects = new Dictionary(); + + static Dictionary s_GuidToPrefab = new Dictionary(); + static Dictionary s_SpawnHandlers = new Dictionary(); + static Dictionary s_UnspawnHandlers = new Dictionary(); + + internal Dictionary localObjects { get { return m_LocalObjects; }} + + static internal Dictionary guidToPrefab { get { return s_GuidToPrefab; }} + static internal Dictionary spawnHandlers { get { return s_SpawnHandlers; }} + static internal Dictionary unspawnHandlers { get { return s_UnspawnHandlers; }} + + internal void Shutdown() + { + ClearLocalObjects(); + ClearSpawners(); + } + + internal void SetLocalObject(NetworkInstanceId netId, GameObject obj, bool isClient, bool isServer) + { + if (LogFilter.logDev) { Debug.Log("SetLocalObject " + netId + " " + obj); } + + if (obj == null) + { + m_LocalObjects[netId] = null; + return; + } + + NetworkIdentity foundNetworkIdentity = null; + if (m_LocalObjects.ContainsKey(netId)) + { + foundNetworkIdentity = m_LocalObjects[netId]; + } + + if (foundNetworkIdentity == null) + { + foundNetworkIdentity = obj.GetComponent(); + m_LocalObjects[netId] = foundNetworkIdentity; + } + + foundNetworkIdentity.UpdateClientServer(isClient, isServer); + } + + // this lets the client take an instance ID from the server and find + // the local object that it corresponds too. This is temporary until + // object references can be serialized transparently. + internal GameObject FindLocalObject(NetworkInstanceId netId) + { + if (m_LocalObjects.ContainsKey(netId)) + { + var uv = m_LocalObjects[netId]; + if (uv != null) + { + return uv.gameObject; + } + } + return null; + } + + internal bool GetNetworkIdentity(NetworkInstanceId netId, out NetworkIdentity uv) + { + if (m_LocalObjects.ContainsKey(netId) && m_LocalObjects[netId] != null) + { + uv = m_LocalObjects[netId]; + return true; + } + uv = null; + return false; + } + + internal bool RemoveLocalObject(NetworkInstanceId netId) + { + return m_LocalObjects.Remove(netId); + } + + internal bool RemoveLocalObjectAndDestroy(NetworkInstanceId netId) + { + if (m_LocalObjects.ContainsKey(netId)) + { + NetworkIdentity localObject = m_LocalObjects[netId]; + Object.Destroy(localObject.gameObject); + return m_LocalObjects.Remove(netId); + } + return false; + } + + internal void ClearLocalObjects() + { + m_LocalObjects.Clear(); + } + + static internal void RegisterPrefab(GameObject prefab, NetworkHash128 newAssetId) + { + NetworkIdentity view = prefab.GetComponent(); + if (view) + { + view.SetDynamicAssetId(newAssetId); + + if (LogFilter.logDebug) { Debug.Log("Registering prefab '" + prefab.name + "' as asset:" + view.assetId); } + s_GuidToPrefab[view.assetId] = prefab; + } + else + { + if (LogFilter.logError) { Debug.LogError("Could not register '" + prefab.name + "' since it contains no NetworkIdentity component"); } + } + } + + static internal void RegisterPrefab(GameObject prefab) + { + NetworkIdentity view = prefab.GetComponent(); + if (view) + { + if (LogFilter.logDebug) { Debug.Log("Registering prefab '" + prefab.name + "' as asset:" + view.assetId); } + s_GuidToPrefab[view.assetId] = prefab; + + var uvs = prefab.GetComponentsInChildren(); + if (uvs.Length > 1) + { + if (LogFilter.logWarn) + { + Debug.LogWarning("The prefab '" + prefab.name + + "' has multiple NetworkIdentity components. There can only be one NetworkIdentity on a prefab, and it must be on the root object."); + } + } + } + else + { + if (LogFilter.logError) { Debug.LogError("Could not register '" + prefab.name + "' since it contains no NetworkIdentity component"); } + } + } + + static internal bool GetPrefab(NetworkHash128 assetId, out GameObject prefab) + { + if (!assetId.IsValid()) + { + prefab = null; + return false; + } + if (s_GuidToPrefab.ContainsKey(assetId) && s_GuidToPrefab[assetId] != null) + { + prefab = s_GuidToPrefab[assetId]; + return true; + } + prefab = null; + return false; + } + + static internal void ClearSpawners() + { + s_GuidToPrefab.Clear(); + s_SpawnHandlers.Clear(); + s_UnspawnHandlers.Clear(); + } + + static public void UnregisterSpawnHandler(NetworkHash128 assetId) + { + s_SpawnHandlers.Remove(assetId); + s_UnspawnHandlers.Remove(assetId); + } + + static internal void RegisterSpawnHandler(NetworkHash128 assetId, SpawnDelegate spawnHandler, UnSpawnDelegate unspawnHandler) + { + if (spawnHandler == null || unspawnHandler == null) + { + if (LogFilter.logError) { Debug.LogError("RegisterSpawnHandler custom spawn function null for " + assetId); } + return; + } + + if (LogFilter.logDebug) { Debug.Log("RegisterSpawnHandler asset '" + assetId + "' " + spawnHandler.GetMethodName() + "/" + unspawnHandler.GetMethodName()); } + + s_SpawnHandlers[assetId] = spawnHandler; + s_UnspawnHandlers[assetId] = unspawnHandler; + } + + static internal void UnregisterPrefab(GameObject prefab) + { + NetworkIdentity identity = prefab.GetComponent(); + if (identity == null) + { + if (LogFilter.logError) { Debug.LogError("Could not unregister '" + prefab.name + "' since it contains no NetworkIdentity component"); } + return; + } + s_SpawnHandlers.Remove(identity.assetId); + s_UnspawnHandlers.Remove(identity.assetId); + } + + static internal void RegisterPrefab(GameObject prefab, SpawnDelegate spawnHandler, UnSpawnDelegate unspawnHandler) + { + NetworkIdentity identity = prefab.GetComponent(); + if (identity == null) + { + if (LogFilter.logError) { Debug.LogError("Could not register '" + prefab.name + "' since it contains no NetworkIdentity component"); } + return; + } + + if (spawnHandler == null || unspawnHandler == null) + { + if (LogFilter.logError) { Debug.LogError("RegisterPrefab custom spawn function null for " + identity.assetId); } + return; + } + + if (!identity.assetId.IsValid()) + { + if (LogFilter.logError) { Debug.LogError("RegisterPrefab game object " + prefab.name + " has no prefab. Use RegisterSpawnHandler() instead?"); } + return; + } + + if (LogFilter.logDebug) { Debug.Log("Registering custom prefab '" + prefab.name + "' as asset:" + identity.assetId + " " + spawnHandler.GetMethodName() + "/" + unspawnHandler.GetMethodName()); } + + s_SpawnHandlers[identity.assetId] = spawnHandler; + s_UnspawnHandlers[identity.assetId] = unspawnHandler; + } + + static internal bool GetSpawnHandler(NetworkHash128 assetId, out SpawnDelegate handler) + { + if (s_SpawnHandlers.ContainsKey(assetId)) + { + handler = s_SpawnHandlers[assetId]; + return true; + } + handler = null; + return false; + } + + static internal bool InvokeUnSpawnHandler(NetworkHash128 assetId, GameObject obj) + { + if (s_UnspawnHandlers.ContainsKey(assetId) && s_UnspawnHandlers[assetId] != null) + { + UnSpawnDelegate handler = s_UnspawnHandlers[assetId]; + handler(obj); + return true; + } + return false; + } + + internal void DestroyAllClientObjects() + { + foreach (var netId in m_LocalObjects.Keys) + { + NetworkIdentity uv = m_LocalObjects[netId]; + + if (uv != null && uv.gameObject != null) + { + if (!InvokeUnSpawnHandler(uv.assetId, uv.gameObject)) + { + if (uv.sceneId.IsEmpty()) + { + Object.Destroy(uv.gameObject); + } + else + { + uv.MarkForReset(); + uv.gameObject.SetActive(false); + } + } + } + } + ClearLocalObjects(); + } + + internal void DumpAllClientObjects() + { + foreach (var netId in m_LocalObjects.Keys) + { + NetworkIdentity uv = m_LocalObjects[netId]; + if (uv != null) + Debug.Log("ID:" + netId + " OBJ:" + uv.gameObject + " AS:" + uv.assetId); + else + Debug.Log("ID:" + netId + " OBJ: null"); + } + } + } +} +#pragma warning restore 618 +#endif //ENABLE_UNET diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkSceneId.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkSceneId.cs new file mode 100644 index 00000000..5903e245 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkSceneId.cs @@ -0,0 +1,68 @@ +using System; + +namespace UnityEngine.Networking +{ + /// + /// This is used to identify networked objects in a scene. These values are allocated in the editor and are persistent for the lifetime of the object in the scene. + /// + [Serializable] + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public struct NetworkSceneId : IEquatable + { + public NetworkSceneId(uint value) + { + m_Value = value; + } + + [SerializeField] + uint m_Value; + + /// + /// Returns true if the value is zero. Non-scene objects - ones which are spawned at runtime will have a sceneId of zero. + /// + /// True if zero. + public bool IsEmpty() + { + return m_Value == 0; + } + + public override int GetHashCode() + { + return (int)m_Value; + } + + public override bool Equals(object obj) + { + return obj is NetworkSceneId && Equals((NetworkSceneId)obj); + } + + public bool Equals(NetworkSceneId other) + { + return this == other; + } + + public static bool operator==(NetworkSceneId c1, NetworkSceneId c2) + { + return c1.m_Value == c2.m_Value; + } + + public static bool operator!=(NetworkSceneId c1, NetworkSceneId c2) + { + return c1.m_Value != c2.m_Value; + } + + /// + /// Returns a string like SceneId:value. + /// + /// String representation of this object. + public override string ToString() + { + return m_Value.ToString(); + } + + /// + /// The internal value for this object. + /// + public uint Value { get { return m_Value; } } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkServer.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkServer.cs new file mode 100644 index 00000000..d9bd90bf --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkServer.cs @@ -0,0 +1,2588 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using UnityEngine.Networking.Match; +using UnityEngine.Networking.NetworkSystem; +using UnityEngine.Networking.Types; +using UnityEngineInternal; + +namespace UnityEngine.Networking +{ + /// + /// The NetworkServer uses a NetworkServerSimple for basic network functionality and adds more game-like functionality. + /// NetworkServer handles remote connections from remote clients via a NetworkServerSimple instance, and also has a local connection for a local client. + /// The NetworkServer is a singleton. It has static convenience functions such as NetworkServer.SendToAll() and NetworkServer.Spawn() which automatically use the singleton instance. + /// The NetworkManager uses the NetworkServer, but it can be used without the NetworkManager. + /// The set of networked objects that have been spawned is managed by NetworkServer. Objects are spawned with NetworkServer.Spawn() which adds them to this set, and makes them be created on clients. Spawned objects are removed automatically when they are destroyed, or than they can be removed from the spawned set by calling NetworkServer.UnSpawn() - this does not destroy the object. + /// There are a number of internal messages used by NetworkServer, these are setup when NetworkServer.Listen() is called. + /// + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public sealed class NetworkServer + { + static bool s_Active; + static volatile NetworkServer s_Instance; + static object s_Sync = new Object(); + static bool m_DontListen; + bool m_LocalClientActive; + + // only used for localConnection accessor + List m_LocalConnectionsFakeList = new List(); + ULocalConnectionToClient m_LocalConnection = null; + + NetworkScene m_NetworkScene; + HashSet m_ExternalConnections; + ServerSimpleWrapper m_SimpleServerSimple; + + float m_MaxDelay = 0.1f; + HashSet m_RemoveList; + int m_RemoveListCount; + const int k_RemoveListInterval = 100; + + // this is cached here for easy access when checking the size of state update packets in NetworkIdentity + static internal ushort maxPacketSize; + + // static message objects to avoid runtime-allocations + static RemovePlayerMessage s_RemovePlayerMessage = new RemovePlayerMessage(); + + /// + /// A list of local connections on the server. + /// + static public List localConnections { get { return instance.m_LocalConnectionsFakeList; } } + + /// + /// The port that the server is listening on. + /// + static public int listenPort { get { return instance.m_SimpleServerSimple.listenPort; } } + /// + /// The transport layer hostId used by this server. + /// + static public int serverHostId { get { return instance.m_SimpleServerSimple.serverHostId; } } + /// + /// A list of all the current connections from clients. + /// The connections in the list are at the index of their connectionId. There may be nulls in this list for disconnected clients. + /// + static public ReadOnlyCollection connections { get { return instance.m_SimpleServerSimple.connections; } } + /// + /// Dictionary of the message handlers registered with the server. + /// The key to the dictionary is the message Id. + /// + static public Dictionary handlers { get { return instance.m_SimpleServerSimple.handlers; } } + /// + /// The host topology that the server is using. + /// This is read-only once the server is started. + /// + static public HostTopology hostTopology { get { return instance.m_SimpleServerSimple.hostTopology; }} + /// + /// This is a dictionary of networked objects that have been spawned on the server. + /// The key to the dictionary is NetworkIdentity netId. + /// + public static Dictionary objects { get { return instance.m_NetworkScene.localObjects; } } + + [Obsolete("Moved to NetworkMigrationManager")] + public static bool sendPeerInfo { get { return false; } set {} } + /// + /// If you enable this, the server will not listen for incoming connections on the regular network port. + /// This can be used if the game is running in host mode and does not want external players to be able to connect - making it like a single-player game. Also this can be useful when using AddExternalConnection(). + /// + public static bool dontListen { get { return m_DontListen; } set { m_DontListen = value; } } + /// + /// This makes the server listen for WebSockets connections instead of normal transport layer connections. + /// This allows WebGL clients to connect to this server. Note that WebGL clients cannot listen for WebSocket connections, they can only make outgoing WebSockets connections. + /// + public static bool useWebSockets { get { return instance.m_SimpleServerSimple.useWebSockets; } set { instance.m_SimpleServerSimple.useWebSockets = value; } } + + internal static NetworkServer instance + { + get + { + if (s_Instance == null) + { + lock (s_Sync) + { + if (s_Instance == null) + { + s_Instance = new NetworkServer(); + } + } + } + return s_Instance; + } + } + /// + /// Checks if the server has been started. + /// This will be true after NetworkServer.Listen() has been called. + /// + public static bool active { get { return s_Active; } } + /// + /// True is a local client is currently active on the server. + /// This will be true for "Hosts" on hosted server games. + /// + public static bool localClientActive { get { return instance.m_LocalClientActive; } } + /// + /// The number of channels the network is configure with. + /// + public static int numChannels { get { return instance.m_SimpleServerSimple.hostTopology.DefaultConfig.ChannelCount; } } + + /// + /// The maximum delay before sending packets on connections. + /// In seconds. The default of 0.01 seconds means packets will be delayed at most by 10 milliseconds. Setting this to zero will disable HLAPI connection buffering. + /// + public static float maxDelay { get { return instance.m_MaxDelay; } set { instance.InternalSetMaxDelay(value); } } + + /// + /// The class to be used when creating new network connections. + /// This can be set with SetNetworkConnectionClass. This allows custom classes that do special processing of data from the transport layer to be used with the NetworkServer. + /// See NetworkConnection.TransportSend and NetworkConnection.TransportReceive for details. + /// + static public Type networkConnectionClass + { + get { return instance.m_SimpleServerSimple.networkConnectionClass; } + } + + /// + /// This sets the class used when creating new network connections. + /// The class must be derived from NetworkConnection. + /// + /// + static public void SetNetworkConnectionClass() where T : NetworkConnection + { + instance.m_SimpleServerSimple.SetNetworkConnectionClass(); + } + + NetworkServer() + { + NetworkManager.activeTransport.Init(); + if (LogFilter.logDev) { Debug.Log("NetworkServer Created version " + Version.Current); } + m_RemoveList = new HashSet(); + m_ExternalConnections = new HashSet(); + m_NetworkScene = new NetworkScene(); + m_SimpleServerSimple = new ServerSimpleWrapper(this); + } + + /// + /// This configures the transport layer settings for the server. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class Example : MonoBehaviour + /// { + /// void StartServer() + /// { + /// ConnectionConfig config = new ConnectionConfig(); + /// config.AddChannel(QosType.ReliableSequenced); + /// config.AddChannel(QosType.UnreliableSequenced); + /// config.PacketSize = 500; + /// NetworkServer.Configure(config, 10); + /// NetworkServer.Listen(7070); + /// } + /// } + /// + /// + /// Transport layer confuration object. + /// The maximum number of client connections to allow. + /// True if successfully configured. + static public bool Configure(ConnectionConfig config, int maxConnections) + { + return instance.m_SimpleServerSimple.Configure(config, maxConnections); + } + + /// + /// This configures the transport layer settings for the server. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class Example : MonoBehaviour + /// { + /// void StartServer() + /// { + /// ConnectionConfig config = new ConnectionConfig(); + /// config.AddChannel(QosType.ReliableSequenced); + /// config.AddChannel(QosType.UnreliableSequenced); + /// config.PacketSize = 500; + /// NetworkServer.Configure(config, 10); + /// NetworkServer.Listen(7070); + /// } + /// } + /// + /// + /// Transport layer topology object to use. + /// True if successfully configured. + static public bool Configure(HostTopology topology) + { + return instance.m_SimpleServerSimple.Configure(topology); + } + + /// + /// Reset the NetworkServer singleton. + /// + public static void Reset() + { +#if UNITY_EDITOR + Profiler.ResetAll(); +#endif + NetworkManager.activeTransport.Shutdown(); + NetworkManager.activeTransport.Init(); + + s_Instance = null; + s_Active = false; + } + + /// + /// This shuts down the server and disconnects all clients. + /// + public static void Shutdown() + { + if (s_Instance != null) + { + s_Instance.InternalDisconnectAll(); + + if (m_DontListen) + { + // was never started, so dont stop + } + else + { + s_Instance.m_SimpleServerSimple.Stop(); + } + + s_Instance = null; + } + m_DontListen = false; + s_Active = false; + } + + static public bool Listen(MatchInfo matchInfo, int listenPort) + { + if (!matchInfo.usingRelay) + return instance.InternalListen(null, listenPort); + + instance.InternalListenRelay(matchInfo.address, matchInfo.port, matchInfo.networkId, Utility.GetSourceID(), matchInfo.nodeId); + return true; + } + + internal void RegisterMessageHandlers() + { + m_SimpleServerSimple.RegisterHandlerSafe(MsgType.Ready, OnClientReadyMessage); + m_SimpleServerSimple.RegisterHandlerSafe(MsgType.Command, OnCommandMessage); + m_SimpleServerSimple.RegisterHandlerSafe(MsgType.LocalPlayerTransform, NetworkTransform.HandleTransform); + m_SimpleServerSimple.RegisterHandlerSafe(MsgType.LocalChildTransform, NetworkTransformChild.HandleChildTransform); + m_SimpleServerSimple.RegisterHandlerSafe(MsgType.RemovePlayer, OnRemovePlayerMessage); + m_SimpleServerSimple.RegisterHandlerSafe(MsgType.Animation, NetworkAnimator.OnAnimationServerMessage); + m_SimpleServerSimple.RegisterHandlerSafe(MsgType.AnimationParameters, NetworkAnimator.OnAnimationParametersServerMessage); + m_SimpleServerSimple.RegisterHandlerSafe(MsgType.AnimationTrigger, NetworkAnimator.OnAnimationTriggerServerMessage); + m_SimpleServerSimple.RegisterHandlerSafe(MsgType.Fragment, NetworkConnection.OnFragment); + + // also setup max packet size. + maxPacketSize = hostTopology.DefaultConfig.PacketSize; + } + + /// + /// Starts a server using a Relay server. This is the manual way of using the Relay server, as the regular NetworkServer.Connect() will automatically use the Relay server if a match exists. + /// + /// Relay server IP Address. + /// Relay server port. + /// GUID of the network to create. + /// This server's sourceId. + /// The node to join the network with. + static public void ListenRelay(string relayIp, int relayPort, NetworkID netGuid, SourceID sourceId, NodeID nodeId) + { + instance.InternalListenRelay(relayIp, relayPort, netGuid, sourceId, nodeId); + } + + void InternalListenRelay(string relayIp, int relayPort, NetworkID netGuid, SourceID sourceId, NodeID nodeId) + { + m_SimpleServerSimple.ListenRelay(relayIp, relayPort, netGuid, sourceId, nodeId); + s_Active = true; + RegisterMessageHandlers(); + } + + /// + /// Start the server on the given port number. Note that if a match has been created, this will listen using the Relay server instead of a local socket. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class Manager : MonoBehaviour + /// { + /// bool isAtStartup = true; + /// + /// void Update() + /// { + /// if (Input.GetKeyDown(KeyCode.S) && isAtStartup) + /// { + /// NetworkServer.Listen(4444); + /// NetworkServer.RegisterHandler(MsgType.Ready, OnPlayerReadyMessage); + /// isAtStartup = false; + /// } + /// } + /// + /// public void OnPlayerReadyMessage(NetworkMessage netMsg) + /// { + /// // TODO: create player and call PlayerIsReady() + /// } + /// } + /// + /// + /// Listen port number. + /// True if listen succeeded. + static public bool Listen(int serverPort) + { + return instance.InternalListen(null, serverPort); + } + + /// + /// Start the server on the given port number. Note that if a match has been created, this will listen using the Relay server instead of a local socket. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class Manager : MonoBehaviour + /// { + /// bool isAtStartup = true; + /// + /// void Update() + /// { + /// if (Input.GetKeyDown(KeyCode.S) && isAtStartup) + /// { + /// NetworkServer.Listen(4444); + /// NetworkServer.RegisterHandler(MsgType.Ready, OnPlayerReadyMessage); + /// isAtStartup = false; + /// } + /// } + /// + /// public void OnPlayerReadyMessage(NetworkMessage netMsg) + /// { + /// // TODO: create player and call PlayerIsReady() + /// } + /// } + /// + /// + /// The IP address to bind to (optional). + /// Listen port number. + /// True if listen succeeded. + static public bool Listen(string ipAddress, int serverPort) + { + return instance.InternalListen(ipAddress, serverPort); + } + + internal bool InternalListen(string ipAddress, int serverPort) + { + if (m_DontListen) + { + // dont start simpleServer - this mode uses external connections instead + m_SimpleServerSimple.Initialize(); + } + else + { + if (!m_SimpleServerSimple.Listen(ipAddress, serverPort)) + return false; + } + + maxPacketSize = hostTopology.DefaultConfig.PacketSize; + s_Active = true; + RegisterMessageHandlers(); + return true; + } + + /// + /// This allows a client that has been disconnected from a server, to become the host of a new version of the game. + /// + /// The client that was connected to the old host. + /// The port to listen on. + /// Match information (may be null). + /// + /// + /// + static public NetworkClient BecomeHost(NetworkClient oldClient, int port, MatchInfo matchInfo, int oldConnectionId, PeerInfoMessage[] peers) + { + return instance.BecomeHostInternal(oldClient, port, matchInfo, oldConnectionId, peers); + } + + internal NetworkClient BecomeHostInternal(NetworkClient oldClient, int port, MatchInfo matchInfo, int oldConnectionId, PeerInfoMessage[] peers) + { + if (s_Active) + { + if (LogFilter.logError) { Debug.LogError("BecomeHost already a server."); } + return null; + } + + if (!NetworkClient.active) + { + if (LogFilter.logError) { Debug.LogError("BecomeHost NetworkClient not active."); } + return null; + } + + // setup a server + + NetworkServer.Configure(hostTopology); + + if (matchInfo == null) + { + if (LogFilter.logDev) { Debug.Log("BecomeHost Listen on " + port); } + + if (!NetworkServer.Listen(port)) + { + if (LogFilter.logError) { Debug.LogError("BecomeHost bind failed."); } + return null; + } + } + else + { + if (LogFilter.logDev) { Debug.Log("BecomeHost match:" + matchInfo.networkId); } + NetworkServer.ListenRelay(matchInfo.address, matchInfo.port, matchInfo.networkId, Utility.GetSourceID(), matchInfo.nodeId); + } + + // setup server objects + foreach (var uv in ClientScene.objects.Values) + { + if (uv == null || uv.gameObject == null) + continue; + + NetworkIdentity.AddNetworkId(uv.netId.Value); + + //NOTE: have to pass false to isServer here so that onStartServer sets object up properly. + m_NetworkScene.SetLocalObject(uv.netId, uv.gameObject, false, false); + uv.OnStartServer(true); + } + + // reset the client peer info(?) + + if (LogFilter.logDev) { Debug.Log("NetworkServer BecomeHost done. oldConnectionId:" + oldConnectionId); } + RegisterMessageHandlers(); + + if (!NetworkClient.RemoveClient(oldClient)) + { + if (LogFilter.logError) { Debug.LogError("BecomeHost failed to remove client"); } + } + + if (LogFilter.logDev) { Debug.Log("BecomeHost localClient ready"); } + + // make a localclient for me + var newLocalClient = ClientScene.ReconnectLocalServer(); + ClientScene.Ready(newLocalClient.connection); + + // cause local players and objects to be reconnected + ClientScene.SetReconnectId(oldConnectionId, peers); + ClientScene.AddPlayer(ClientScene.readyConnection, 0); + + return newLocalClient; + } + + void InternalSetMaxDelay(float seconds) + { + // set on existing connections + for (int i = 0; i < connections.Count; i++) + { + NetworkConnection conn = connections[i]; + if (conn != null) + conn.SetMaxDelay(seconds); + } + + // save for future connections + m_MaxDelay = seconds; + } + + // called by LocalClient to add itself. dont call directly. + internal int AddLocalClient(LocalClient localClient) + { + if (m_LocalConnectionsFakeList.Count != 0) + { + Debug.LogError("Local Connection already exists"); + return -1; + } + + m_LocalConnection = new ULocalConnectionToClient(localClient); + m_LocalConnection.connectionId = 0; + m_SimpleServerSimple.SetConnectionAtIndex(m_LocalConnection); + + // this is for backwards compatibility with localConnections property + m_LocalConnectionsFakeList.Add(m_LocalConnection); + + m_LocalConnection.InvokeHandlerNoData(MsgType.Connect); + + return 0; + } + + internal void RemoveLocalClient(NetworkConnection localClientConnection) + { + for (int i = 0; i < m_LocalConnectionsFakeList.Count; ++i) + { + if (m_LocalConnectionsFakeList[i].connectionId == localClientConnection.connectionId) + { + m_LocalConnectionsFakeList.RemoveAt(i); + break; + } + } + + if (m_LocalConnection != null) + { + m_LocalConnection.Disconnect(); + m_LocalConnection.Dispose(); + m_LocalConnection = null; + } + m_LocalClientActive = false; + m_SimpleServerSimple.RemoveConnectionAtIndex(0); + } + + internal void SetLocalObjectOnServer(NetworkInstanceId netId, GameObject obj) + { + if (LogFilter.logDev) { Debug.Log("SetLocalObjectOnServer " + netId + " " + obj); } + + m_NetworkScene.SetLocalObject(netId, obj, false, true); + } + + internal void ActivateLocalClientScene() + { + if (m_LocalClientActive) + return; + + // ClientScene for a local connection is becoming active. any spawned objects need to be started as client objects + m_LocalClientActive = true; + foreach (var uv in objects.Values) + { + if (!uv.isClient) + { + if (LogFilter.logDev) { Debug.Log("ActivateClientScene " + uv.netId + " " + uv.gameObject); } + + ClientScene.SetLocalObject(uv.netId, uv.gameObject); + uv.OnStartClient(); + } + } + } + + /// + /// Send a message structure with the given type number to all connected clients. + /// This applies to clients that are ready and not-ready. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class MyMessageTypes + /// { + /// public static short MSG_LOGIN_RESPONSE = 1000; + /// public static short MSG_SCORE = 1005; + /// }; + /// + /// public class MyScoreMessage : MessageBase + /// { + /// public int score; + /// public Vector3 scorePos; + /// } + /// + /// class GameServer + /// { + /// void SendScore(int score, Vector3 scorePos) + /// { + /// MyScoreMessage msg = new MyScoreMessage(); + /// msg.score = score; + /// msg.scorePos = scorePos; + /// NetworkServer.SendToAll(MyMessageTypes.MSG_SCORE, msg); + /// } + /// } + /// + /// + /// Message type. + /// Message structure. + /// Message type. + /// + static public bool SendToAll(short msgType, MessageBase msg) + { + if (LogFilter.logDev) { Debug.Log("Server.SendToAll msgType:" + msgType); } + + bool result = true; + + // remote connections + for (int i = 0; i < connections.Count; i++) + { + NetworkConnection conn = connections[i]; + if (conn != null) + result &= conn.Send(msgType, msg); + } + + return result; + } + + // this is like SendToReady - but it doesn't check the ready flag on the connection. + // this is used for ObjectDestroy messages. + static bool SendToObservers(GameObject contextObj, short msgType, MessageBase msg) + { + if (LogFilter.logDev) { Debug.Log("Server.SendToObservers id:" + msgType); } + + bool result = true; + var uv = contextObj.GetComponent(); + if (uv == null || uv.observers == null) + return false; + + int count = uv.observers.Count; + for (int i = 0; i < count; i++) + { + var conn = uv.observers[i]; + result &= conn.Send(msgType, msg); + } + return result; + } + + /// + /// Send a message structure with the given type number to only clients which are ready. + /// See Networking.NetworkClient.Ready. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class ReadyMsgTypes + /// { + /// public static short MSG_LOGIN_RESPONSE = 1000; + /// public static short MSG_SCORE = 1005; + /// }; + /// + /// public class ReadyScoreMessage : MessageBase + /// { + /// public int score; + /// public Vector3 scorePos; + /// } + /// + /// class GameServer + /// { + /// public GameObject gameObject; + /// + /// void SendScore(int score, Vector3 scorePos) + /// { + /// ReadyScoreMessage msg = new ReadyScoreMessage(); + /// msg.score = score; + /// msg.scorePos = scorePos; + /// NetworkServer.SendToReady(gameObject, ReadyMsgTypes.MSG_SCORE, msg); + /// } + /// } + /// + /// + /// + /// Message type. + /// Message structure. + /// Success if message is sent. + static public bool SendToReady(GameObject contextObj, short msgType, MessageBase msg) + { + if (LogFilter.logDev) { Debug.Log("Server.SendToReady id:" + msgType); } + + if (contextObj == null) + { + for (int i = 0; i < connections.Count; i++) + { + NetworkConnection conn = connections[i]; + if (conn != null && conn.isReady) + { + conn.Send(msgType, msg); + } + } + return true; + } + + bool result = true; + var uv = contextObj.GetComponent(); + if (uv == null || uv.observers == null) + return false; + + int count = uv.observers.Count; + for (int i = 0; i < count; i++) + { + var conn = uv.observers[i]; + if (!conn.isReady) + continue; + + result &= conn.Send(msgType, msg); + } + return result; + } + + /// + /// Sends the contents of a NetworkWriter object to the ready players. + /// + /// + /// The writer object to send. + /// The QoS channel to send the data on. + static public void SendWriterToReady(GameObject contextObj, NetworkWriter writer, int channelId) + { + if (writer.AsArraySegment().Count > short.MaxValue) + { + throw new UnityException("NetworkWriter used buffer is too big!"); + } + SendBytesToReady(contextObj, writer.AsArraySegment().Array, writer.AsArraySegment().Count, channelId); + } + + /// + /// This sends an array of bytes to all ready players. + /// This bypasses the usual serialization and message structures, allowing raw bytes to be send to all ready players. The contents will be processed as a message on the client of the player, so it must be structured properly. + /// + /// + /// Array of bytes to send. + /// Size of array. + /// Transport layer channel id to send bytes on. + static public void SendBytesToReady(GameObject contextObj, byte[] buffer, int numBytes, int channelId) + { + if (contextObj == null) + { + // no context.. send to all ready connections + bool success = true; + for (int i = 0; i < connections.Count; i++) + { + NetworkConnection conn = connections[i]; + if (conn != null && conn.isReady) + { + if (!conn.SendBytes(buffer, numBytes, channelId)) + { + success = false; + } + } + } + if (!success) + { + if (LogFilter.logWarn) { Debug.LogWarning("SendBytesToReady failed"); } + } + return; + } + + var uv = contextObj.GetComponent(); + try + { + bool success = true; + int count = uv.observers.Count; + for (int i = 0; i < count; i++) + { + var conn = uv.observers[i]; + if (!conn.isReady) + continue; + + if (!conn.SendBytes(buffer, numBytes, channelId)) + { + success = false; + } + } + if (!success) + { + if (LogFilter.logWarn) { Debug.LogWarning("SendBytesToReady failed for " + contextObj); } + } + } + catch (NullReferenceException) + { + // observers may be null if object has not been spawned + if (LogFilter.logWarn) { Debug.LogWarning("SendBytesToReady object " + contextObj + " has not been spawned"); } + } + } + + /// + /// This sends an array of bytes to a specific player. + /// This bypasses the usual serialization and message structures, allowing raw bytes to be send to a player. The contents will be processed as a message on the client of the player, so it must be structured properly. + /// + /// The player to send the bytes to. + /// Array of bytes to send. + /// Size of array. + /// Transport layer channel id to send bytes on. + public static void SendBytesToPlayer(GameObject player, byte[] buffer, int numBytes, int channelId) + { + for (int i = 0; i < connections.Count; i++) + { + var conn = connections[i]; + if (conn == null) + continue; + + for (int j = 0; j < conn.playerControllers.Count; j++) + { + if (conn.playerControllers[j].IsValid && conn.playerControllers[j].gameObject == player) + { + conn.SendBytes(buffer, numBytes, channelId); + break; + } + } + } + } + + /// + /// Send given message structure as an unreliable message to all connected clients. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class UnreliableMsgTypes + /// { + /// public static short MSG_LOGIN_RESPONSE = 1000; + /// public static short MSG_SCORE = 1005; + /// }; + /// + /// public class UnreliableScoreMessage : MessageBase + /// { + /// public int score; + /// public Vector3 scorePos; + /// } + /// + /// class GameServer + /// { + /// void SendScore(int score, Vector3 scorePos) + /// { + /// UnreliableScoreMessage msg = new UnreliableScoreMessage(); + /// msg.score = score; + /// msg.scorePos = scorePos; + /// NetworkServer.SendUnreliableToAll(UnreliableMsgTypes.MSG_SCORE, msg); + /// } + /// } + /// + /// + /// Message type. + /// Message structure. + /// Success if message is sent. + static public bool SendUnreliableToAll(short msgType, MessageBase msg) + { + if (LogFilter.logDev) { Debug.Log("Server.SendUnreliableToAll msgType:" + msgType); } + + bool result = true; + for (int i = 0; i < connections.Count; i++) + { + NetworkConnection conn = connections[i]; + if (conn != null) + result &= conn.SendUnreliable(msgType, msg); + } + return result; + } + + /// + /// Send given message structure as an unreliable message only to ready clients. + /// See Networking.NetworkClient.Ready. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class UnreliableMessageTypes + /// { + /// public static short MSG_LOGIN_RESPONSE = 1000; + /// public static short MSG_SCORE = 1005; + /// }; + /// + /// public class UnreliableMessage : MessageBase + /// { + /// public int score; + /// public Vector3 scorePos; + /// } + /// + /// class GameServer + /// { + /// public GameObject gameObject; + /// + /// void SendScore(int score, Vector3 scorePos) + /// { + /// UnreliableMessage msg = new UnreliableMessage(); + /// msg.score = score; + /// msg.scorePos = scorePos; + /// NetworkServer.SendUnreliableToReady(gameObject, UnreliableMessageTypes.MSG_SCORE, msg); + /// } + /// } + /// + /// + /// + /// Message type. + /// Message structure. + /// Success if message is sent. + static public bool SendUnreliableToReady(GameObject contextObj, short msgType, MessageBase msg) + { + if (LogFilter.logDev) { Debug.Log("Server.SendUnreliableToReady id:" + msgType); } + + if (contextObj == null) + { + // no context.. send to all ready connections + for (int i = 0; i < connections.Count; i++) + { + var conn = connections[i]; + if (conn != null && conn.isReady) + { + conn.SendUnreliable(msgType, msg); + } + } + return true; + } + + bool result = true; + var uv = contextObj.GetComponent(); + int count = uv.observers.Count; + for (int i = 0; i < count; i++) + { + var conn = uv.observers[i]; + if (!conn.isReady) + continue; + + result &= conn.SendUnreliable(msgType, msg); + } + return result; + } + + /// + /// Sends a network message to all connected clients on a specified transport layer QoS channel. + /// + /// The message id. + /// The message to send. + /// The transport layer channel to use. + /// True if the message was sent. + static public bool SendByChannelToAll(short msgType, MessageBase msg, int channelId) + { + if (LogFilter.logDev) { Debug.Log("Server.SendByChannelToAll id:" + msgType); } + + bool result = true; + + for (int i = 0; i < connections.Count; i++) + { + var conn = connections[i]; + if (conn != null) + result &= conn.SendByChannel(msgType, msg, channelId); + } + return result; + } + + /// + /// Sends a network message to all connected clients that are "ready" on a specified transport layer QoS channel. + /// + /// An object to use for context when calculating object visibility. If null, then the message is sent to all ready clients. + /// The message id. + /// The message to send. + /// The transport layer channel to send on. + /// True if the message was sent. + static public bool SendByChannelToReady(GameObject contextObj, short msgType, MessageBase msg, int channelId) + { + if (LogFilter.logDev) { Debug.Log("Server.SendByChannelToReady msgType:" + msgType); } + + if (contextObj == null) + { + // no context.. send to all ready connections + for (int i = 0; i < connections.Count; i++) + { + var conn = connections[i]; + if (conn != null && conn.isReady) + { + conn.SendByChannel(msgType, msg, channelId); + } + } + return true; + } + + bool result = true; + var uv = contextObj.GetComponent(); + int count = uv.observers.Count; + for (int i = 0; i < count; i++) + { + var conn = uv.observers[i]; + if (!conn.isReady) + continue; + + result &= conn.SendByChannel(msgType, msg, channelId); + } + return result; + } + + /// + /// Disconnect all currently connected clients. + /// This can only be called on the server. Clients will receive the Disconnect message. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class Example : MonoBehaviour + /// { + /// enum GameState + /// { + /// kInit, + /// kStart + /// } + /// GameState state; + /// + /// public void Update() + /// { + /// if (state != GameState.kInit) + /// { + /// if (Input.GetKey(KeyCode.Escape)) + /// { + /// Debug.Log("Disconnecting all!"); + /// NetworkServer.DisconnectAll(); + /// Application.LoadLevel("empty"); + /// state = GameState.kStart; + /// } + /// } + /// } + /// } + /// + /// + static public void DisconnectAll() + { + instance.InternalDisconnectAll(); + } + + internal void InternalDisconnectAll() + { + m_SimpleServerSimple.DisconnectAllConnections(); + + if (m_LocalConnection != null) + { + m_LocalConnection.Disconnect(); + m_LocalConnection.Dispose(); + m_LocalConnection = null; + } + + m_LocalClientActive = false; + } + + // The user should never need to pump the update loop manually + internal static void Update() + { + if (s_Instance != null) + s_Instance.InternalUpdate(); + } + + void UpdateServerObjects() + { + foreach (var uv in objects.Values) + { + try + { + uv.UNetUpdate(); + } + catch (NullReferenceException) + { + //ignore nulls here.. they will be cleaned up by CheckForNullObjects below + } + catch (MissingReferenceException) + { + //ignore missing ref here.. they will be cleaned up by CheckForNullObjects below + } + } + + // check for nulls in this list every N updates. doing it every frame is expensive and unneccessary + if (m_RemoveListCount++ % k_RemoveListInterval == 0) + CheckForNullObjects(); + } + + void CheckForNullObjects() + { + // cant iterate through Values here, since we need the keys of null objects to add to remove list. + foreach (var k in objects.Keys) + { + var uv = objects[k]; + if (uv == null || uv.gameObject == null) + { + m_RemoveList.Add(k); + } + } + if (m_RemoveList.Count > 0) + { + foreach (var remove in m_RemoveList) + { + objects.Remove(remove); + } + m_RemoveList.Clear(); + } + } + + internal void InternalUpdate() + { + m_SimpleServerSimple.Update(); + + if (m_DontListen) + { + m_SimpleServerSimple.UpdateConnections(); + } + + UpdateServerObjects(); + } + + void OnConnected(NetworkConnection conn) + { + if (LogFilter.logDebug) { Debug.Log("Server accepted client:" + conn.connectionId); } + + // add player info + conn.SetMaxDelay(m_MaxDelay); + + conn.InvokeHandlerNoData(MsgType.Connect); + + SendCrc(conn); + } + + void OnDisconnected(NetworkConnection conn) + { + conn.InvokeHandlerNoData(MsgType.Disconnect); + + for (int i = 0; i < conn.playerControllers.Count; i++) + { + if (conn.playerControllers[i].gameObject != null) + { + //NOTE: should there be default behaviour here to destroy the associated player? + if (LogFilter.logWarn) { Debug.LogWarning("Player not destroyed when connection disconnected."); } + } + } + + if (LogFilter.logDebug) { Debug.Log("Server lost client:" + conn.connectionId); } + conn.RemoveObservers(); + conn.Dispose(); + } + + void OnData(NetworkConnection conn, int receivedSize, int channelId) + { +#if UNITY_EDITOR + Profiler.IncrementStatIncoming(MsgType.LLAPIMsg); +#endif + conn.TransportReceive(m_SimpleServerSimple.messageBuffer, receivedSize, channelId); + } + + private void GenerateConnectError(int error) + { + if (LogFilter.logError) { Debug.LogError("UNet Server Connect Error: " + error); } + GenerateError(null, error); + } + + private void GenerateDataError(NetworkConnection conn, int error) + { + NetworkError dataError = (NetworkError)error; + if (LogFilter.logError) { Debug.LogError("UNet Server Data Error: " + dataError); } + GenerateError(conn, error); + } + + private void GenerateDisconnectError(NetworkConnection conn, int error) + { + NetworkError disconnectError = (NetworkError)error; + if (LogFilter.logError) { Debug.LogError("UNet Server Disconnect Error: " + disconnectError + " conn:[" + conn + "]:" + conn.connectionId); } + GenerateError(conn, error); + } + + private void GenerateError(NetworkConnection conn, int error) + { + if (handlers.ContainsKey(MsgType.Error)) + { + ErrorMessage msg = new ErrorMessage(); + msg.errorCode = error; + + // write the message to a local buffer + NetworkWriter writer = new NetworkWriter(); + msg.Serialize(writer); + + // pass a reader (attached to local buffer) to handler + NetworkReader reader = new NetworkReader(writer); + conn.InvokeHandler(MsgType.Error, reader, 0); + } + } + + /// + /// Register a handler for a particular message type. + /// There are several system message types which you can add handlers for. You can also add your own message types. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class MyServer : NetworkManager + /// { + /// void Start() + /// { + /// Debug.Log("Registering server callbacks"); + /// NetworkServer.RegisterHandler(MsgType.Connect, OnConnected); + /// } + /// + /// void OnConnected(NetworkMessage netMsg) + /// { + /// Debug.Log("Client connected"); + /// } + /// } + /// + /// The system message types are listed below: + /// + /// class MsgType + /// { + /// public const short ObjectDestroy = 1; + /// public const short Rpc = 2; + /// public const short ObjectSpawn = 3; + /// public const short Owner = 4; + /// public const short Command = 5; + /// public const short LocalPlayerTransform = 6; + /// public const short SyncEvent = 7; + /// public const short UpdateVars = 8; + /// public const short SyncList = 9; + /// public const short ObjectSpawnScene = 10; + /// public const short NetworkInfo = 11; + /// public const short SpawnFinished = 12; + /// public const short ObjectHide = 13; + /// public const short CRC = 14; + /// public const short LocalClientAuthority = 15; + /// } + /// + ///Most of these messages are for internal use only. Users should not define message ids in this range. + /// + /// Message type number. + /// Function handler which will be invoked for when this message type is received. + static public void RegisterHandler(short msgType, NetworkMessageDelegate handler) + { + instance.m_SimpleServerSimple.RegisterHandler(msgType, handler); + } + + /// + /// Unregisters a handler for a particular message type. + /// + /// The message type to remove the handler for. + static public void UnregisterHandler(short msgType) + { + instance.m_SimpleServerSimple.UnregisterHandler(msgType); + } + + /// + /// Clear all registered callback handlers. + /// + static public void ClearHandlers() + { + instance.m_SimpleServerSimple.ClearHandlers(); + } + + /// + /// Clears all registered spawn prefab and spawn handler functions for this server. + /// + static public void ClearSpawners() + { + NetworkScene.ClearSpawners(); + } + + /// + /// Get outbound network statistics for the client. + /// + /// Number of messages sent so far (including collated messages send through buffer). + /// Number of messages sent through buffer. + /// Number of bytes sent so far. + /// Number of messages buffered for sending per second. + static public void GetStatsOut(out int numMsgs, out int numBufferedMsgs, out int numBytes, out int lastBufferedPerSecond) + { + numMsgs = 0; + numBufferedMsgs = 0; + numBytes = 0; + lastBufferedPerSecond = 0; + + for (int i = 0; i < connections.Count; i++) + { + var conn = connections[i]; + if (conn != null) + { + int snumMsgs; + int snumBufferedMsgs; + int snumBytes; + int slastBufferedPerSecond; + + conn.GetStatsOut(out snumMsgs, out snumBufferedMsgs, out snumBytes, out slastBufferedPerSecond); + + numMsgs += snumMsgs; + numBufferedMsgs += snumBufferedMsgs; + numBytes += snumBytes; + lastBufferedPerSecond += slastBufferedPerSecond; + } + } + } + + /// + /// Get inbound network statistics for the server. + /// + /// Number of messages received so far. + /// Number of bytes received so far. + static public void GetStatsIn(out int numMsgs, out int numBytes) + { + numMsgs = 0; + numBytes = 0; + for (int i = 0; i < connections.Count; i++) + { + var conn = connections[i]; + if (conn != null) + { + int cnumMsgs; + int cnumBytes; + + conn.GetStatsIn(out cnumMsgs, out cnumBytes); + + numMsgs += cnumMsgs; + numBytes += cnumBytes; + } + } + } + + /// + /// Send a message to the client which owns the given player object instance. + /// This function is not very efficient. It is better to send a message directly on the connection object of the player - which can be obtained from the "connectionToClient" member variable on NetworkBehaviour components. + /// + /// The players game object. + /// Message type. + /// Message struct. + // send this message to the player only + static public void SendToClientOfPlayer(GameObject player, short msgType, MessageBase msg) + { + for (int i = 0; i < connections.Count; i++) + { + var conn = connections[i]; + if (conn != null) + { + for (int j = 0; j < conn.playerControllers.Count; j++) + { + if (conn.playerControllers[j].IsValid && conn.playerControllers[j].gameObject == player) + { + conn.Send(msgType, msg); + return; + } + } + } + } + + if (LogFilter.logError) { Debug.LogError("Failed to send message to player object '" + player.name + ", not found in connection list"); } + } + + /// + /// Send a message to the client which owns the given connection ID. + /// It accepts the connection ID as a parameter as well as a message and MsgType. Remember to set the client up for receiving the messages by using NetworkClient.RegisterHandler. Also, for user messages you must use a MsgType with a higher ID number than MsgType.Highest. + /// + /// //The code shows how to set up a message, the MsgType and how to get the connectionID. + /// //It also shows how to send the message to the client, as well as receive it. + /// //Attach this script to a GameObject + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// using UnityEngine.Networking.NetworkSystem; + /// + /// //Create a class for the message you send to the Client + /// public class RegisterHostMessage : MessageBase + /// { + /// public string m_Name; + /// public string m_Comment; + /// } + /// + /// public class Example : NetworkManager + /// { + /// RegisterHostMessage m_Message; + /// //This is the Message Type you want to send to the Client. User messages must be above the Highest Message Type. + /// public const short m_MessageType = MsgType.Highest + 1; + /// + /// //Detect when a client connects to the Server + /// public override void OnServerConnect(NetworkConnection connection) + /// { + /// //Change the message to read the Player's connection ID and a comment + /// EditMessage("Player " + connection.connectionId, "Hi there."); + /// //Send the new message to the Client using the Server + /// NetworkServer.SendToClient(connection.connectionId, m_MessageType, m_Message); + /// } + /// + /// //On the Client's side, detect when it connects to a Server + /// public override void OnClientConnect(NetworkConnection connection) + /// { + /// //Register and receive the message on the Client's side + /// client.RegisterHandler(m_MessageType, ReceiveMessage); + /// } + /// + /// //Use this to edit the message to read what you want + /// void EditMessage(string myName, string myComment) + /// { + /// m_Message = new RegisterHostMessage(); + /// //Change the message name and comment to be the ones you set + /// m_Message.m_Name = myName; + /// m_Message.m_Comment = myComment; + /// } + /// + /// //Use this to receive the message from the Server on the Client's side + /// public void ReceiveMessage(NetworkMessage networkMessage) + /// { + /// //Read the message that comes in + /// RegisterHostMessage hostMessage = networkMessage.ReadMessage<RegisterHostMessage>(); + /// //Store the name and comment as variables + /// string receivedName = hostMessage.m_Name; + /// string receivedComment = hostMessage.m_Comment; + /// //Output the Player name and comment + /// Debug.Log("Player Name : " + receivedName); + /// Debug.Log("Player Comment : " + receivedComment); + /// } + /// } + /// + /// + /// Client connection ID. + /// Message struct to send. + /// Message type. + static public void SendToClient(int connectionId, short msgType, MessageBase msg) + { + if (connectionId < connections.Count) + { + var conn = connections[connectionId]; + if (conn != null) + { + conn.Send(msgType, msg); + return; + } + } + if (LogFilter.logError) { Debug.LogError("Failed to send message to connection ID '" + connectionId + ", not found in connection list"); } + } + + static public bool ReplacePlayerForConnection(NetworkConnection conn, GameObject player, short playerControllerId, NetworkHash128 assetId) + { + NetworkIdentity id; + if (GetNetworkIdentity(player, out id)) + { + id.SetDynamicAssetId(assetId); + } + return instance.InternalReplacePlayerForConnection(conn, player, playerControllerId); + } + + /// + /// This replaces the player object for a connection with a different player object. The old player object is not destroyed. + /// If a connection already has a player object, this can be used to replace that object with a different player object. This does NOT change the ready state of the connection, so it can safely be used while changing scenes. + /// + /// Connection which is adding the player. + /// Player object spawned for the player. + /// The player controller ID number as specified by client. + /// True if player was replaced. + static public bool ReplacePlayerForConnection(NetworkConnection conn, GameObject player, short playerControllerId) + { + return instance.InternalReplacePlayerForConnection(conn, player, playerControllerId); + } + + static public bool AddPlayerForConnection(NetworkConnection conn, GameObject player, short playerControllerId, NetworkHash128 assetId) + { + NetworkIdentity id; + if (GetNetworkIdentity(player, out id)) + { + id.SetDynamicAssetId(assetId); + } + return instance.InternalAddPlayerForConnection(conn, player, playerControllerId); + } + /// + /// When an AddPlayer message handler has received a request from a player, the server calls this to associate the player object with the connection. + /// When a player is added for a connection, the client for that connection is made ready automatically. The player object is automatically spawned, so you do not need to call NetworkServer.Spawn for that object. This function is used for "adding" a player, not for "replacing" the player on a connection. If there is already a player on this playerControllerId for this connection, this will fail. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// class MyServer : MonoBehaviour + /// { + /// public GameObject playerPrefab; + /// + /// void Start() + /// { + /// NetworkServer.RegisterHandler(MsgType.AddPlayer, OnAddPlayerMessage); + /// } + /// + /// void OnAddPlayerMessage(NetworkMessage netMsg) + /// { + /// GameObject thePlayer = (GameObject)Instantiate(playerPrefab, Vector3.zero, Quaternion.identity); + /// // This spawns the new player on all clients + /// NetworkServer.AddPlayerForConnection(conn, thePlayer, 0); + /// } + /// } + /// + /// + /// Connection which is adding the player. + /// Player object spawned for the player. + /// The player controller ID number as specified by client. + /// True if player was added. + static public bool AddPlayerForConnection(NetworkConnection conn, GameObject player, short playerControllerId) + { + return instance.InternalAddPlayerForConnection(conn, player, playerControllerId); + } + + internal bool InternalAddPlayerForConnection(NetworkConnection conn, GameObject playerGameObject, short playerControllerId) + { + NetworkIdentity playerNetworkIdentity; + if (!GetNetworkIdentity(playerGameObject, out playerNetworkIdentity)) + { + if (LogFilter.logError) { Debug.Log("AddPlayer: playerGameObject has no NetworkIdentity. Please add a NetworkIdentity to " + playerGameObject); } + return false; + } + playerNetworkIdentity.Reset(); + + if (!CheckPlayerControllerIdForConnection(conn, playerControllerId)) + return false; + + // cannot have a player object in "Add" version + PlayerController oldController = null; + GameObject oldPlayer = null; + if (conn.GetPlayerController(playerControllerId, out oldController)) + { + oldPlayer = oldController.gameObject; + } + if (oldPlayer != null) + { + if (LogFilter.logError) { Debug.Log("AddPlayer: player object already exists for playerControllerId of " + playerControllerId); } + return false; + } + + PlayerController newPlayerController = new PlayerController(playerGameObject, playerControllerId); + conn.SetPlayerController(newPlayerController); + + // Set the playerControllerId on the NetworkIdentity on the server, NetworkIdentity.SetLocalPlayer is not called on the server (it is on clients and that sets the playerControllerId there) + playerNetworkIdentity.SetConnectionToClient(conn, newPlayerController.playerControllerId); + + SetClientReady(conn); + + if (SetupLocalPlayerForConnection(conn, playerNetworkIdentity, newPlayerController)) + { + return true; + } + + if (LogFilter.logDebug) { Debug.Log("Adding new playerGameObject object netId: " + playerGameObject.GetComponent().netId + " asset ID " + playerGameObject.GetComponent().assetId); } + + FinishPlayerForConnection(conn, playerNetworkIdentity, playerGameObject); + if (playerNetworkIdentity.localPlayerAuthority) + { + playerNetworkIdentity.SetClientOwner(conn); + } + return true; + } + + static bool CheckPlayerControllerIdForConnection(NetworkConnection conn, short playerControllerId) + { + if (playerControllerId < 0) + { + if (LogFilter.logError) { Debug.LogError("AddPlayer: playerControllerId of " + playerControllerId + " is negative"); } + return false; + } + if (playerControllerId > PlayerController.MaxPlayersPerClient) + { + if (LogFilter.logError) { Debug.Log("AddPlayer: playerControllerId of " + playerControllerId + " is too high. max is " + PlayerController.MaxPlayersPerClient); } + return false; + } + if (playerControllerId > PlayerController.MaxPlayersPerClient / 2) + { + if (LogFilter.logWarn) { Debug.LogWarning("AddPlayer: playerControllerId of " + playerControllerId + " is unusually high"); } + } + return true; + } + + bool SetupLocalPlayerForConnection(NetworkConnection conn, NetworkIdentity uv, PlayerController newPlayerController) + { + if (LogFilter.logDev) { Debug.Log("NetworkServer SetupLocalPlayerForConnection netID:" + uv.netId); } + + var localConnection = conn as ULocalConnectionToClient; + if (localConnection != null) + { + if (LogFilter.logDev) { Debug.Log("NetworkServer AddPlayer handling ULocalConnectionToClient"); } + + // Spawn this player for other players, instead of SpawnObject: + if (uv.netId.IsEmpty()) + { + // it is allowed to provide an already spawned object as the new player object. + // so dont spawn it again. + uv.OnStartServer(true); + } + uv.RebuildObservers(true); + SendSpawnMessage(uv, null); + + // Set up local player instance on the client instance and update local object map + localConnection.localClient.AddLocalPlayer(newPlayerController); + uv.SetClientOwner(conn); + + // Trigger OnAuthority + uv.ForceAuthority(true); + + // Trigger OnStartLocalPlayer + uv.SetLocalPlayer(newPlayerController.playerControllerId); + return true; + } + return false; + } + + static void FinishPlayerForConnection(NetworkConnection conn, NetworkIdentity uv, GameObject playerGameObject) + { + if (uv.netId.IsEmpty()) + { + // it is allowed to provide an already spawned object as the new player object. + // so dont spawn it again. + Spawn(playerGameObject); + } + + OwnerMessage owner = new OwnerMessage(); + owner.netId = uv.netId; + owner.playerControllerId = uv.playerControllerId; + conn.Send(MsgType.Owner, owner); + } + + internal bool InternalReplacePlayerForConnection(NetworkConnection conn, GameObject playerGameObject, short playerControllerId) + { + NetworkIdentity playerNetworkIdentity; + if (!GetNetworkIdentity(playerGameObject, out playerNetworkIdentity)) + { + if (LogFilter.logError) { Debug.LogError("ReplacePlayer: playerGameObject has no NetworkIdentity. Please add a NetworkIdentity to " + playerGameObject); } + return false; + } + + if (!CheckPlayerControllerIdForConnection(conn, playerControllerId)) + return false; + + //NOTE: there can be an existing player + if (LogFilter.logDev) { Debug.Log("NetworkServer ReplacePlayer"); } + + // is there already an owner that is a different object?? + PlayerController oldOwner; + if (conn.GetPlayerController(playerControllerId, out oldOwner)) + { + oldOwner.unetView.SetNotLocalPlayer(); + oldOwner.unetView.ClearClientOwner(); + } + + PlayerController newPlayerController = new PlayerController(playerGameObject, playerControllerId); + conn.SetPlayerController(newPlayerController); + + // Set the playerControllerId on the NetworkIdentity on the server, NetworkIdentity.SetLocalPlayer is not called on the server (it is on clients and that sets the playerControllerId there) + playerNetworkIdentity.SetConnectionToClient(conn, newPlayerController.playerControllerId); + + //NOTE: DONT set connection ready. + + if (LogFilter.logDev) { Debug.Log("NetworkServer ReplacePlayer setup local"); } + + if (SetupLocalPlayerForConnection(conn, playerNetworkIdentity, newPlayerController)) + { + return true; + } + + if (LogFilter.logDebug) { Debug.Log("Replacing playerGameObject object netId: " + playerGameObject.GetComponent().netId + " asset ID " + playerGameObject.GetComponent().assetId); } + + FinishPlayerForConnection(conn, playerNetworkIdentity, playerGameObject); + if (playerNetworkIdentity.localPlayerAuthority) + { + playerNetworkIdentity.SetClientOwner(conn); + } + return true; + } + + static bool GetNetworkIdentity(GameObject go, out NetworkIdentity view) + { + view = go.GetComponent(); + if (view == null) + { + if (LogFilter.logError) { Debug.LogError("UNET failure. GameObject doesn't have NetworkIdentity."); } + return false; + } + return true; + } + + /// + /// Sets the client to be ready. + /// When a client has signaled that it is ready, this method tells the server that the client is ready to receive spawned objects and state synchronization updates. This is usually called in a handler for the SYSTEM_READY message. If there is not specific action a game needs to take for this message, relying on the default ready handler function is probably fine, so this call wont be needed. + /// + /// The connection of the client to make ready. + static public void SetClientReady(NetworkConnection conn) + { + instance.SetClientReadyInternal(conn); + } + + internal void SetClientReadyInternal(NetworkConnection conn) + { + if (LogFilter.logDebug) { Debug.Log("SetClientReadyInternal for conn:" + conn.connectionId); } + + if (conn.isReady) + { + if (LogFilter.logDebug) { Debug.Log("SetClientReady conn " + conn.connectionId + " already ready"); } + return; + } + + if (conn.playerControllers.Count == 0) + { + // this is now allowed + if (LogFilter.logDebug) { Debug.LogWarning("Ready with no player object"); } + } + + conn.isReady = true; + + var localConnection = conn as ULocalConnectionToClient; + if (localConnection != null) + { + if (LogFilter.logDev) { Debug.Log("NetworkServer Ready handling ULocalConnectionToClient"); } + + // Setup spawned objects for local player + // Only handle the local objects for the first player (no need to redo it when doing more local players) + // and don't handle player objects here, they were done above + foreach (NetworkIdentity uv in objects.Values) + { + // Need to call OnStartClient directly here, as it's already been added to the local object dictionary + // in the above SetLocalPlayer call + if (uv != null && uv.gameObject != null) + { + var vis = uv.OnCheckObserver(conn); + if (vis) + { + uv.AddObserver(conn); + } + if (!uv.isClient) + { + if (LogFilter.logDev) { Debug.Log("LocalClient.SetSpawnObject calling OnStartClient"); } + uv.OnStartClient(); + } + } + } + return; + } + + // Spawn/update all current server objects + if (LogFilter.logDebug) { Debug.Log("Spawning " + objects.Count + " objects for conn " + conn.connectionId); } + + ObjectSpawnFinishedMessage msg = new ObjectSpawnFinishedMessage(); + msg.state = 0; + conn.Send(MsgType.SpawnFinished, msg); + + foreach (NetworkIdentity uv in objects.Values) + { + if (uv == null) + { + if (LogFilter.logWarn) { Debug.LogWarning("Invalid object found in server local object list (null NetworkIdentity)."); } + continue; + } + if (!uv.gameObject.activeSelf) + { + continue; + } + + if (LogFilter.logDebug) { Debug.Log("Sending spawn message for current server objects name='" + uv.gameObject.name + "' netId=" + uv.netId); } + + var vis = uv.OnCheckObserver(conn); + if (vis) + { + uv.AddObserver(conn); + } + } + + msg.state = 1; + conn.Send(MsgType.SpawnFinished, msg); + } + + static internal void ShowForConnection(NetworkIdentity uv, NetworkConnection conn) + { + if (conn.isReady) + instance.SendSpawnMessage(uv, conn); + } + + static internal void HideForConnection(NetworkIdentity uv, NetworkConnection conn) + { + ObjectDestroyMessage msg = new ObjectDestroyMessage(); + msg.netId = uv.netId; + conn.Send(MsgType.ObjectHide, msg); + } + + /// + /// Marks all connected clients as no longer ready. + /// All clients will no longer be sent state synchronization updates. The player's clients can call ClientManager.Ready() again to re-enter the ready state. This is useful when switching scenes. + /// + // call this to make all the clients not ready, such as when changing levels. + static public void SetAllClientsNotReady() + { + for (int i = 0; i < connections.Count; i++) + { + var conn = connections[i]; + if (conn != null) + { + SetClientNotReady(conn); + } + } + } + + /// + /// Sets the client of the connection to be not-ready. + /// Clients that are not ready do not receive spawned objects or state synchronization updates. They client can be made ready again by calling SetClientReady(). + /// + /// The connection of the client to make not ready. + static public void SetClientNotReady(NetworkConnection conn) + { + instance.InternalSetClientNotReady(conn); + } + + internal void InternalSetClientNotReady(NetworkConnection conn) + { + if (conn.isReady) + { + if (LogFilter.logDebug) { Debug.Log("PlayerNotReady " + conn); } + conn.isReady = false; + conn.RemoveObservers(); + + NotReadyMessage msg = new NotReadyMessage(); + conn.Send(MsgType.NotReady, msg); + } + } + + // default ready handler. + static void OnClientReadyMessage(NetworkMessage netMsg) + { + if (LogFilter.logDebug) { Debug.Log("Default handler for ready message from " + netMsg.conn); } + SetClientReady(netMsg.conn); + } + + // default remove player handler + static void OnRemovePlayerMessage(NetworkMessage netMsg) + { + netMsg.ReadMessage(s_RemovePlayerMessage); + + PlayerController player = null; + netMsg.conn.GetPlayerController(s_RemovePlayerMessage.playerControllerId, out player); + if (player != null) + { + netMsg.conn.RemovePlayerController(s_RemovePlayerMessage.playerControllerId); + Destroy(player.gameObject); + } + else + { + if (LogFilter.logError) { Debug.LogError("Received remove player message but could not find the player ID: " + s_RemovePlayerMessage.playerControllerId); } + } + } + + // Handle command from specific player, this could be one of multiple players on a single client + static void OnCommandMessage(NetworkMessage netMsg) + { + int cmdHash = (int)netMsg.reader.ReadPackedUInt32(); + var netId = netMsg.reader.ReadNetworkId(); + + var cmdObject = FindLocalObject(netId); + if (cmdObject == null) + { + if (LogFilter.logWarn) { Debug.LogWarning("Instance not found when handling Command message [netId=" + netId + "]"); } + return; + } + + var uv = cmdObject.GetComponent(); + if (uv == null) + { + if (LogFilter.logWarn) { Debug.LogWarning("NetworkIdentity deleted when handling Command message [netId=" + netId + "]"); } + return; + } + + // Commands can be for player objects, OR other objects with client-authority + bool foundOwner = false; + for (int i = 0; i < netMsg.conn.playerControllers.Count; i++) + { + var p = netMsg.conn.playerControllers[i]; + if (p.gameObject != null && p.gameObject.GetComponent().netId == uv.netId) + { + foundOwner = true; + break; + } + } + if (!foundOwner) + { + if (uv.clientAuthorityOwner != netMsg.conn) + { + if (LogFilter.logWarn) { Debug.LogWarning("Command for object without authority [netId=" + netId + "]"); } + return; + } + } + + if (LogFilter.logDev) { Debug.Log("OnCommandMessage for netId=" + netId + " conn=" + netMsg.conn); } + uv.HandleCommand(cmdHash, netMsg.reader); + } + + internal void SpawnObject(GameObject obj) + { + if (!NetworkServer.active) + { + if (LogFilter.logError) { Debug.LogError("SpawnObject for " + obj + ", NetworkServer is not active. Cannot spawn objects without an active server."); } + return; + } + + NetworkIdentity objNetworkIdentity; + if (!GetNetworkIdentity(obj, out objNetworkIdentity)) + { + if (LogFilter.logError) { Debug.LogError("SpawnObject " + obj + " has no NetworkIdentity. Please add a NetworkIdentity to " + obj); } + return; + } + objNetworkIdentity.Reset(); + + objNetworkIdentity.OnStartServer(false); + + if (LogFilter.logDebug) { Debug.Log("SpawnObject instance ID " + objNetworkIdentity.netId + " asset ID " + objNetworkIdentity.assetId); } + + objNetworkIdentity.RebuildObservers(true); + //SendSpawnMessage(objNetworkIdentity, null); + } + + /* + TODO: optimize BuildSpawnMsg to not do allocations. + - this would need a static m_MsgStreamOut and m_MsgWriter. + - payload needs to be separate sub-msg? + + internal short BuildSpawnBytes(NetworkIdentity uv) + { + m_MsgStreamIn.Seek(0, SeekOrigin.Begin); + m_MsgWriter.Serialize((short)0); // space for size + m_MsgWriter.UWriteUInt32((uint)MsgType.ObjectSpawn); + m_MsgWriter.UWriteUInt32(uv.netId); + m_MsgWriter.Serialize(uv.spawnType); + m_MsgWriter.Serialize(uv.assetId); + m_MsgWriter.Serialize(uv.transform.position); + //payload - this is optional? + uv.UNetSerializeTransform(m_MsgWriter, true); + uv.UNetSerializeVars(m_MsgWriter, true); + + short sz = (short)(m_MsgStreamIn.Position - sizeof(short)); + m_MsgStreamIn.Seek(0, SeekOrigin.Begin); + m_MsgWriter.Serialize(sz); + + return (short)(sz + sizeof(short)); + }*/ + + internal void SendSpawnMessage(NetworkIdentity uv, NetworkConnection conn) + { + if (uv.serverOnly) + return; + + if (uv.sceneId.IsEmpty()) + { + ObjectSpawnMessage msg = new ObjectSpawnMessage(); + msg.netId = uv.netId; + msg.assetId = uv.assetId; + msg.position = uv.transform.position; + msg.rotation = uv.transform.rotation; + + // include synch data + NetworkWriter writer = new NetworkWriter(); + uv.UNetSerializeAllVars(writer); + if (writer.Position > 0) + { + msg.payload = writer.ToArray(); + } + + if (conn != null) + { + conn.Send(MsgType.ObjectSpawn, msg); + } + else + { + SendToReady(uv.gameObject, MsgType.ObjectSpawn, msg); + } + +#if UNITY_EDITOR + Profiler.IncrementStatOutgoing(MsgType.ObjectSpawn, uv.assetId.ToString()); +#endif + } + else + { + ObjectSpawnSceneMessage msg = new ObjectSpawnSceneMessage(); + msg.netId = uv.netId; + msg.sceneId = uv.sceneId; + msg.position = uv.transform.position; + + // include synch data + NetworkWriter writer = new NetworkWriter(); + uv.UNetSerializeAllVars(writer); + if (writer.Position > 0) + { + msg.payload = writer.ToArray(); + } + + if (conn != null) + { + conn.Send(MsgType.ObjectSpawnScene, msg); + } + else + { + SendToReady(uv.gameObject, MsgType.ObjectSpawn, msg); + } + +#if UNITY_EDITOR + Profiler.IncrementStatOutgoing(MsgType.ObjectSpawnScene, "sceneId"); +#endif + } + } + + /// + /// This destroys all the player objects associated with a NetworkConnections on a server. + /// This is used when a client disconnects, to remove the players for that client. This also destroys non-player objects that have client authority set for this connection. + /// + /// The connections object to clean up for. + static public void DestroyPlayersForConnection(NetworkConnection conn) + { + if (conn.playerControllers.Count == 0) + { + if (LogFilter.logWarn) { Debug.LogWarning("Empty player list given to NetworkServer.Destroy(), nothing to do."); } + return; + } + + if (conn.clientOwnedObjects != null) + { + var tmp = new HashSet(conn.clientOwnedObjects); + foreach (var netId in tmp) + { + var obj = FindLocalObject(netId); + if (obj != null) + { + DestroyObject(obj); + } + } + } + + for (int i = 0; i < conn.playerControllers.Count; i++) + { + var player = conn.playerControllers[i]; + if (player.IsValid) + { + if (player.unetView == null) + { + // the playerController's object has been destroyed, but RemovePlayerForConnection was never called. + // this is ok, just dont double destroy it. + } + else + { + DestroyObject(player.unetView, true); + } + player.gameObject = null; + } + } + conn.playerControllers.Clear(); + } + + static void UnSpawnObject(GameObject obj) + { + if (obj == null) + { + if (LogFilter.logDev) { Debug.Log("NetworkServer UnspawnObject is null"); } + return; + } + + NetworkIdentity objNetworkIdentity; + if (!GetNetworkIdentity(obj, out objNetworkIdentity)) return; + + UnSpawnObject(objNetworkIdentity); + } + + static void UnSpawnObject(NetworkIdentity uv) + { + DestroyObject(uv, false); + } + + static void DestroyObject(GameObject obj) + { + if (obj == null) + { + if (LogFilter.logDev) { Debug.Log("NetworkServer DestroyObject is null"); } + return; + } + + NetworkIdentity objNetworkIdentity; + if (!GetNetworkIdentity(obj, out objNetworkIdentity)) return; + + DestroyObject(objNetworkIdentity, true); + } + + static void DestroyObject(NetworkIdentity uv, bool destroyServerObject) + { + if (LogFilter.logDebug) { Debug.Log("DestroyObject instance:" + uv.netId); } + if (objects.ContainsKey(uv.netId)) + { + objects.Remove(uv.netId); + } + + if (uv.clientAuthorityOwner != null) + { + uv.clientAuthorityOwner.RemoveOwnedObject(uv); + } + +#if UNITY_EDITOR + Profiler.IncrementStatOutgoing(MsgType.ObjectDestroy, uv.assetId.ToString()); +#endif + + ObjectDestroyMessage msg = new ObjectDestroyMessage(); + msg.netId = uv.netId; + SendToObservers(uv.gameObject, MsgType.ObjectDestroy, msg); + + uv.ClearObservers(); + if (NetworkClient.active && instance.m_LocalClientActive) + { + uv.OnNetworkDestroy(); + ClientScene.SetLocalObject(msg.netId, null); + } + + // when unspawning, dont destroy the server's object + if (destroyServerObject) + { + Object.Destroy(uv.gameObject); + } + uv.MarkForReset(); + } + + /// + /// This clears all of the networked objects that the server is aware of. This can be required if a scene change deleted all of the objects without destroying them in the normal manner. + /// + static public void ClearLocalObjects() + { + objects.Clear(); + } + + /// + /// Spawn the given game object on all clients which are ready. + /// This will cause a new object to be instantiated from the registered prefab, or from a custom spawn function. + /// + /// //Attach this script to the GameObject you would like to be spawned. + /// //Attach a NetworkIdentity component to your GameObject. Click and drag the GameObject into the Assets directory so that it becomes a prefab. + /// //The GameObject you assign in the Inspector spawns when the Client connects. To spawn a prefab GameObject, use Instantiate first before spawning the GameObject. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class Example : NetworkBehaviour + /// { + /// //Assign the prefab in the Inspector + /// public GameObject m_MyGameObject; + /// GameObject m_MyInstantiated; + /// + /// void Start() + /// { + /// //Instantiate the prefab + /// m_MyInstantiated = Instantiate(m_MyGameObject); + /// //Spawn the GameObject you assign in the Inspector + /// NetworkServer.Spawn(m_MyInstantiated); + /// } + /// } + /// + /// + /// Game object with NetworkIdentity to spawn. + static public void Spawn(GameObject obj) + { + if (!VerifyCanSpawn(obj)) + { + return; + } + + instance.SpawnObject(obj); + } + + static bool CheckForPrefab(GameObject obj) + { +#if UNITY_EDITOR + return UnityEditor.PrefabUtility.IsPartOfPrefabAsset(obj); +#else + return false; +#endif + } + + static bool VerifyCanSpawn(GameObject obj) + { + if (CheckForPrefab(obj)) + { + Debug.LogErrorFormat("GameObject {0} is a prefab, it can't be spawned. This will cause errors in builds.", obj.name); + return false; + } + + return true; + } + + /// + /// This spawns an object like NetworkServer.Spawn() but also assigns Client Authority to the specified client. + /// This is the same as calling NetworkIdentity.AssignClientAuthority on the spawned object. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// class TestBehaviour : NetworkBehaviour + /// { + /// public GameObject otherPrefab; + /// [Command] + /// public void CmdSpawn() + /// { + /// GameObject go = (GameObject)Instantiate(otherPrefab, transform.position + new Vector3(0, 1, 0), Quaternion.identity); + /// NetworkServer.SpawnWithClientAuthority(go, connectionToClient); + /// } + /// } + /// + /// + /// The object to spawn. + /// The player object to set Client Authority to. + /// + static public Boolean SpawnWithClientAuthority(GameObject obj, GameObject player) + { + var uv = player.GetComponent(); + if (uv == null) + { + Debug.LogError("SpawnWithClientAuthority player object has no NetworkIdentity"); + return false; + } + + if (uv.connectionToClient == null) + { + Debug.LogError("SpawnWithClientAuthority player object is not a player."); + return false; + } + + return SpawnWithClientAuthority(obj, uv.connectionToClient); + } + + /// + /// This spawns an object like NetworkServer.Spawn() but also assigns Client Authority to the specified client. + /// This is the same as calling NetworkIdentity.AssignClientAuthority on the spawned object. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// class TestBehaviour : NetworkBehaviour + /// { + /// public GameObject otherPrefab; + /// [Command] + /// public void CmdSpawn() + /// { + /// GameObject go = (GameObject)Instantiate(otherPrefab, transform.position + new Vector3(0, 1, 0), Quaternion.identity); + /// NetworkServer.SpawnWithClientAuthority(go, connectionToClient); + /// } + /// } + /// + /// + /// The object to spawn. + /// The connection to set Client Authority to. + /// + static public bool SpawnWithClientAuthority(GameObject obj, NetworkConnection conn) + { + if (!conn.isReady) + { + Debug.LogError("SpawnWithClientAuthority NetworkConnection is not ready!"); + return false; + } + + Spawn(obj); + + var uv = obj.GetComponent(); + if (uv == null || !uv.isServer) + { + // spawning the object failed. + return false; + } + + return uv.AssignClientAuthority(conn); + } + + /// + /// This spawns an object like NetworkServer.Spawn() but also assigns Client Authority to the specified client. + /// This is the same as calling NetworkIdentity.AssignClientAuthority on the spawned object. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// class TestBehaviour : NetworkBehaviour + /// { + /// public GameObject otherPrefab; + /// [Command] + /// public void CmdSpawn() + /// { + /// GameObject go = (GameObject)Instantiate(otherPrefab, transform.position + new Vector3(0, 1, 0), Quaternion.identity); + /// NetworkServer.SpawnWithClientAuthority(go, connectionToClient); + /// } + /// } + /// + /// + /// The object to spawn. + /// The assetId of the object to spawn. Used for custom spawn handlers. + /// The connection to set Client Authority to. + /// + static public bool SpawnWithClientAuthority(GameObject obj, NetworkHash128 assetId, NetworkConnection conn) + { + Spawn(obj, assetId); + + var uv = obj.GetComponent(); + if (uv == null || !uv.isServer) + { + // spawning the object failed. + return false; + } + + return uv.AssignClientAuthority(conn); + } + + static public void Spawn(GameObject obj, NetworkHash128 assetId) + { + if (!VerifyCanSpawn(obj)) + { + return; + } + + NetworkIdentity id; + if (GetNetworkIdentity(obj, out id)) + { + id.SetDynamicAssetId(assetId); + } + instance.SpawnObject(obj); + } + + /// + /// Destroys this object and corresponding objects on all clients. + /// In some cases it is useful to remove an object but not delete it on the server. For that, use NetworkServer.UnSpawn() instead of NetworkServer.Destroy(). + /// + /// Game object to destroy. + static public void Destroy(GameObject obj) + { + DestroyObject(obj); + } + + /// + /// This takes an object that has been spawned and un-spawns it. + /// The object will be removed from clients that it was spawned on, or the custom spawn handler function on the client will be called for the object. + /// Unlike when calling NetworkServer.Destroy(), on the server the object will NOT be destroyed. This allows the server to re-use the object, even spawn it again later. + /// + /// The spawned object to be unspawned. + static public void UnSpawn(GameObject obj) + { + UnSpawnObject(obj); + } + + internal bool InvokeBytes(ULocalConnectionToServer conn, byte[] buffer, int numBytes, int channelId) + { + NetworkReader reader = new NetworkReader(buffer); + + reader.ReadInt16(); // size + short msgType = reader.ReadInt16(); + + if (handlers.ContainsKey(msgType) && m_LocalConnection != null) + { + // this must be invoked with the connection to the client, not the client's connection to the server + m_LocalConnection.InvokeHandler(msgType, reader, channelId); + return true; + } + return false; + } + + // invoked for local clients + internal bool InvokeHandlerOnServer(ULocalConnectionToServer conn, short msgType, MessageBase msg, int channelId) + { + if (handlers.ContainsKey(msgType) && m_LocalConnection != null) + { + // write the message to a local buffer + NetworkWriter writer = new NetworkWriter(); + msg.Serialize(writer); + + // pass a reader (attached to local buffer) to handler + NetworkReader reader = new NetworkReader(writer); + + // this must be invoked with the connection to the client, not the client's connection to the server + m_LocalConnection.InvokeHandler(msgType, reader, channelId); + return true; + } + if (LogFilter.logError) { Debug.LogError("Local invoke: Failed to find local connection to invoke handler on [connectionId=" + conn.connectionId + "] for MsgId:" + msgType); } + return false; + } + + /// + /// This finds the local NetworkIdentity object with the specified network Id. + /// Since netIds are the same on the server and all clients for a game, this allows clients to send a netId of a local game objects, and have the server find the corresponding server object. + /// + /// + /// The netId of the NetworkIdentity object to find. + /// The game object that matches the netId. + static public GameObject FindLocalObject(NetworkInstanceId netId) + { + return instance.m_NetworkScene.FindLocalObject(netId); + } + + /// + /// Gets aggregate packet stats for all connections. + /// + /// Dictionary of msg types and packet statistics. + static public Dictionary GetConnectionStats() + { + Dictionary stats = new Dictionary(); + + for (int i = 0; i < connections.Count; i++) + { + var conn = connections[i]; + if (conn != null) + { + foreach (short k in conn.packetStats.Keys) + { + if (stats.ContainsKey(k)) + { + NetworkConnection.PacketStat s = stats[k]; + s.count += conn.packetStats[k].count; + s.bytes += conn.packetStats[k].bytes; + stats[k] = s; + } + else + { + stats[k] = new NetworkConnection.PacketStat(conn.packetStats[k]); + } + } + } + } + return stats; + } + + /// + /// Resets the packet stats on all connections. + /// + static public void ResetConnectionStats() + { + for (int i = 0; i < connections.Count; i++) + { + var conn = connections[i]; + if (conn != null) + { + conn.ResetStats(); + } + } + } + + /// + /// This accepts a network connection from another external source and adds it to the server. + /// This connection will use the callbacks registered with the server, and can have players added to it like any other connection. + /// + /// Network connection to add. + /// True if added. + static public bool AddExternalConnection(NetworkConnection conn) + { + return instance.AddExternalConnectionInternal(conn); + } + + bool AddExternalConnectionInternal(NetworkConnection conn) + { + if (conn.connectionId < 0) + return false; + + if (conn.connectionId < connections.Count && connections[conn.connectionId] != null) + { + if (LogFilter.logError) { Debug.LogError("AddExternalConnection failed, already connection for id:" + conn.connectionId); } + return false; + } + + if (LogFilter.logDebug) { Debug.Log("AddExternalConnection external connection " + conn.connectionId); } + m_SimpleServerSimple.SetConnectionAtIndex(conn); + m_ExternalConnections.Add(conn.connectionId); + conn.InvokeHandlerNoData(MsgType.Connect); + + return true; + } + + /// + /// This removes an external connection added with AddExternalConnection(). + /// + /// The id of the connection to remove. + static public void RemoveExternalConnection(int connectionId) + { + instance.RemoveExternalConnectionInternal(connectionId); + } + + bool RemoveExternalConnectionInternal(int connectionId) + { + if (!m_ExternalConnections.Contains(connectionId)) + { + if (LogFilter.logError) { Debug.LogError("RemoveExternalConnection failed, no connection for id:" + connectionId); } + return false; + } + if (LogFilter.logDebug) { Debug.Log("RemoveExternalConnection external connection " + connectionId); } + + var conn = m_SimpleServerSimple.FindConnection(connectionId); + if (conn != null) + { + conn.RemoveObservers(); + } + m_SimpleServerSimple.RemoveConnectionAtIndex(connectionId); + + return true; + } + + static bool ValidateSceneObject(NetworkIdentity netId) + { + if (netId.gameObject.hideFlags == HideFlags.NotEditable || netId.gameObject.hideFlags == HideFlags.HideAndDontSave) + return false; + +#if UNITY_EDITOR + if (UnityEditor.EditorUtility.IsPersistent(netId.gameObject)) + return false; +#endif + + // If not a scene object + if (netId.sceneId.IsEmpty()) + return false; + + return true; + } + + /// + /// This causes NetworkIdentity objects in a scene to be spawned on a server. + /// NetworkIdentity objects in a scene are disabled by default. Calling SpawnObjects() causes these scene objects to be enabled and spawned. It is like calling NetworkServer.Spawn() for each of them. + /// + /// Success if objects where spawned. + static public bool SpawnObjects() + { + if (!active) + return true; + + NetworkIdentity[] netIds = Resources.FindObjectsOfTypeAll(); + for (int i = 0; i < netIds.Length; i++) + { + var netId = netIds[i]; + if (!ValidateSceneObject(netId)) + continue; + + if (LogFilter.logDebug) { Debug.Log("SpawnObjects sceneId:" + netId.sceneId + " name:" + netId.gameObject.name); } + netId.Reset(); + netId.gameObject.SetActive(true); + } + for (int i = 0; i < netIds.Length; i++) + { + var netId = netIds[i]; + if (!ValidateSceneObject(netId)) + continue; + + Spawn(netId.gameObject); + + // these objects are server authority - even if "localPlayerAuthority" is set on them + netId.ForceAuthority(true); + } + return true; + } + + static void SendCrc(NetworkConnection targetConnection) + { + if (NetworkCRC.singleton == null) + return; + + if (NetworkCRC.scriptCRCCheck == false) + return; + + CRCMessage crcMsg = new CRCMessage(); + + // build entries + List entries = new List(); + foreach (var name in NetworkCRC.singleton.scripts.Keys) + { + CRCMessageEntry entry = new CRCMessageEntry(); + entry.name = name; + entry.channel = (byte)NetworkCRC.singleton.scripts[name]; + entries.Add(entry); + } + crcMsg.scripts = entries.ToArray(); + + targetConnection.Send(MsgType.CRC, crcMsg); + } + + [Obsolete("moved to NetworkMigrationManager")] + public void SendNetworkInfo(NetworkConnection targetConnection) + { + } + + class ServerSimpleWrapper : NetworkServerSimple + { + NetworkServer m_Server; + + public ServerSimpleWrapper(NetworkServer server) + { + m_Server = server; + } + + public override void OnConnectError(int connectionId, byte error) + { + m_Server.GenerateConnectError(error); + } + + public override void OnDataError(NetworkConnection conn, byte error) + { + m_Server.GenerateDataError(conn, error); + } + + public override void OnDisconnectError(NetworkConnection conn, byte error) + { + m_Server.GenerateDisconnectError(conn, error); + } + + public override void OnConnected(NetworkConnection conn) + { + m_Server.OnConnected(conn); + } + + public override void OnDisconnected(NetworkConnection conn) + { + m_Server.OnDisconnected(conn); + } + + public override void OnData(NetworkConnection conn, int receivedSize, int channelId) + { + m_Server.OnData(conn, receivedSize, channelId); + } + } + }; +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkServerSimple.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkServerSimple.cs new file mode 100644 index 00000000..13eaa4d0 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkServerSimple.cs @@ -0,0 +1,673 @@ +using System; +using UnityEngine; +using System.Collections.Generic; +using UnityEngine.Networking.Types; +using System.Collections.ObjectModel; + + +namespace UnityEngine.Networking +{ + /// + /// The NetworkServerSimple is a basic server class without the "game" related functionality that the NetworkServer class has. + /// This class has no scene management, spawning, player objects, observers, or static interface like the NetworkServer class. It is simply a server that listens on a port, manages connections, and handles messages. There can be more than one instance of this class in a process. + /// Like the NetworkServer and NetworkClient classes, it allows the type of NetworkConnection class created for new connections to be specified with SetNetworkConnectionClass(), so custom types of network connections can be used with it. + /// This class can be used by overriding the virtual functions OnConnected, OnDisconnected and OnData; or by registering message handlers. + /// + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class NetworkServerSimple + { + bool m_Initialized = false; + int m_ListenPort; + int m_ServerHostId = -1; + int m_RelaySlotId = -1; + bool m_UseWebSockets; + + byte[] m_MsgBuffer = null; + NetworkReader m_MsgReader = null; + + Type m_NetworkConnectionClass = typeof(NetworkConnection); + HostTopology m_HostTopology; + List m_Connections = new List(); + ReadOnlyCollection m_ConnectionsReadOnly; + + NetworkMessageHandlers m_MessageHandlers = new NetworkMessageHandlers(); + + /// + /// The network port that the server is listening on. + /// + public int listenPort { get { return m_ListenPort; } set { m_ListenPort = value; }} + /// + /// The transport layer hostId of the server. + /// + public int serverHostId { get { return m_ServerHostId; } set { m_ServerHostId = value; }} + /// + /// The transport layer host-topology that the server is configured with. + /// A host topology object can be passed to the Listen() function, or a default host topology that is compatible with the default topology of NetworkClient will be used. + /// + public HostTopology hostTopology { get { return m_HostTopology; }} + /// + /// This causes the server to listen for WebSocket connections instead of regular transport layer connections. + /// This allows WebGL clients to talk to the server. + /// + public bool useWebSockets { get { return m_UseWebSockets; } set { m_UseWebSockets = value; } } + /// + /// A read-only list of the current connections being managed. + /// + public ReadOnlyCollection connections { get { return m_ConnectionsReadOnly; }} + /// + /// The message handler functions that are registered. + /// + public Dictionary handlers { get { return m_MessageHandlers.GetHandlers(); } } + + /// + /// The internal buffer that the server reads data from the network into. This will contain the most recent data read from the network when OnData() is called. + /// + public byte[] messageBuffer { get { return m_MsgBuffer; }} + /// + /// A NetworkReader object that is bound to the server's messageBuffer. + /// + public NetworkReader messageReader { get { return m_MsgReader; }} + + /// + /// The type of class to be created for new network connections from clients. + /// By default this is the NetworkConnection class, but it can be changed with SetNetworkConnectionClass() to classes derived from NetworkConnections. + /// + public Type networkConnectionClass + { + get { return m_NetworkConnectionClass; } + } + + /// + /// This sets the class that is used when creating new network connections. + /// The class must be derived from NetworkConnection. + /// + /// + public void SetNetworkConnectionClass() where T : NetworkConnection + { + m_NetworkConnectionClass = typeof(T); + } + + public NetworkServerSimple() + { + m_ConnectionsReadOnly = new ReadOnlyCollection(m_Connections); + } + + /// + /// Initialization function that is invoked when the server starts listening. This can be overridden to perform custom initialization such as setting the NetworkConnectionClass. + /// + public virtual void Initialize() + { + if (m_Initialized) + return; + + m_Initialized = true; + NetworkManager.activeTransport.Init(); + + m_MsgBuffer = new byte[NetworkMessage.MaxMessageSize]; + m_MsgReader = new NetworkReader(m_MsgBuffer); + + if (m_HostTopology == null) + { + var config = new ConnectionConfig(); + config.AddChannel(QosType.ReliableSequenced); + config.AddChannel(QosType.Unreliable); + m_HostTopology = new HostTopology(config, 8); + } + + if (LogFilter.logDebug) { Debug.Log("NetworkServerSimple initialize."); } + } + + /// + /// This configures the network transport layer of the server. + /// + /// The transport layer configuration to use. + /// Maximum number of network connections to allow. + /// True if configured. + public bool Configure(ConnectionConfig config, int maxConnections) + { + HostTopology top = new HostTopology(config, maxConnections); + return Configure(top); + } + + /// + /// This configures the network transport layer of the server. + /// + /// The transport layer host topology to use. + /// True if configured. + public bool Configure(HostTopology topology) + { + m_HostTopology = topology; + return true; + } + + /// + /// This starts the server listening for connections on the specified port. + /// + /// + /// The port to listen on. + /// True if able to listen. + public bool Listen(string ipAddress, int serverListenPort) + { + Initialize(); + m_ListenPort = serverListenPort; + + if (m_UseWebSockets) + { + m_ServerHostId = NetworkManager.activeTransport.AddWebsocketHost(m_HostTopology, serverListenPort, ipAddress); + } + else + { + m_ServerHostId = NetworkManager.activeTransport.AddHost(m_HostTopology, serverListenPort, ipAddress); + } + + if (m_ServerHostId == -1) + { + return false; + } + + if (LogFilter.logDebug) { Debug.Log("NetworkServerSimple listen: " + ipAddress + ":" + m_ListenPort); } + return true; + } + + /// + /// This starts the server listening for connections on the specified port. + /// + /// The port to listen on. + /// + public bool Listen(int serverListenPort) + { + return Listen(serverListenPort, m_HostTopology); + } + + /// + /// This starts the server listening for connections on the specified port. + /// + /// The port to listen on. + /// The transport layer host toplogy to configure with. + /// + public bool Listen(int serverListenPort, HostTopology topology) + { + m_HostTopology = topology; + Initialize(); + m_ListenPort = serverListenPort; + + if (m_UseWebSockets) + { + m_ServerHostId = NetworkManager.activeTransport.AddWebsocketHost(m_HostTopology, serverListenPort, null); + } + else + { + m_ServerHostId = NetworkManager.activeTransport.AddHost(m_HostTopology, serverListenPort, null); + } + + if (m_ServerHostId == -1) + { + return false; + } + + if (LogFilter.logDebug) { Debug.Log("NetworkServerSimple listen " + m_ListenPort); } + return true; + } + + /// + /// Starts a server using a Relay server. This is the manual way of using the Relay server, as the regular NetworkServer.Connect() will automatically use the Relay server if a match exists. + /// + /// Relay server IP Address. + /// Relay server port. + /// GUID of the network to create. + /// This server's sourceId. + /// The node to join the network with. + public void ListenRelay(string relayIp, int relayPort, NetworkID netGuid, SourceID sourceId, NodeID nodeId) + { + Initialize(); + + m_ServerHostId = NetworkManager.activeTransport.AddHost(m_HostTopology, listenPort, null); + if (LogFilter.logDebug) { Debug.Log("Server Host Slot Id: " + m_ServerHostId); } + + Update(); + + byte error; + NetworkManager.activeTransport.ConnectAsNetworkHost( + m_ServerHostId, + relayIp, + relayPort, + netGuid, + sourceId, + nodeId, + out error); + + m_RelaySlotId = 0; + if (LogFilter.logDebug) { Debug.Log("Relay Slot Id: " + m_RelaySlotId); } + } + + /// + /// This stops a server from listening. + /// + public void Stop() + { + if (LogFilter.logDebug) { Debug.Log("NetworkServerSimple stop "); } + NetworkManager.activeTransport.RemoveHost(m_ServerHostId); + m_ServerHostId = -1; + } + + internal void RegisterHandlerSafe(short msgType, NetworkMessageDelegate handler) + { + m_MessageHandlers.RegisterHandlerSafe(msgType, handler); + } + + /// + /// This registers a handler function for a message Id. + /// + /// Message Id to register handler for. + /// Handler function. + public void RegisterHandler(short msgType, NetworkMessageDelegate handler) + { + m_MessageHandlers.RegisterHandler(msgType, handler); + } + + /// + /// This unregisters a registered message handler function. + /// + /// The message id to unregister. + public void UnregisterHandler(short msgType) + { + m_MessageHandlers.UnregisterHandler(msgType); + } + + /// + /// Clears the message handlers that are registered. + /// + public void ClearHandlers() + { + m_MessageHandlers.ClearMessageHandlers(); + } + + /// + /// This function causes pending outgoing data on connections to be sent, but unlike Update() it works when the server is not listening. + /// When the server is using externally added connections and the dontListen flag is set, the regular connection flush in the Update() function does not happen. In this case, UpdateConnections can be called to pump the external connections. This is an advanced usage that should not be required unless the server uses custom NetworkConnection classes that do not use the built-in transport layer. + /// + // this can be used independantly of Update() - such as when using external connections and not listening. + public void UpdateConnections() + { + for (int i = 0; i < m_Connections.Count; i++) + { + NetworkConnection conn = m_Connections[i]; + if (conn != null) + conn.FlushChannels(); + } + } + + /// + /// This function pumps the server causing incoming network data to be processed, and pending outgoing data to be sent. + /// This should be called each frame, and is called automatically for the server used by NetworkServer. + /// + public void Update() + { + if (m_ServerHostId == -1) + return; + + int connectionId; + int channelId; + int receivedSize; + byte error; + + var networkEvent = NetworkEventType.DataEvent; + if (m_RelaySlotId != -1) + { + networkEvent = NetworkManager.activeTransport.ReceiveRelayEventFromHost(m_ServerHostId, out error); + if (NetworkEventType.Nothing != networkEvent) + { + if (LogFilter.logDebug) { Debug.Log("NetGroup event:" + networkEvent); } + } + if (networkEvent == NetworkEventType.ConnectEvent) + { + if (LogFilter.logDebug) { Debug.Log("NetGroup server connected"); } + } + if (networkEvent == NetworkEventType.DisconnectEvent) + { + if (LogFilter.logDebug) { Debug.Log("NetGroup server disconnected"); } + } + } + + do + { + networkEvent = NetworkManager.activeTransport.ReceiveFromHost(m_ServerHostId, out connectionId, out channelId, m_MsgBuffer, (int)m_MsgBuffer.Length, out receivedSize, out error); + if (networkEvent != NetworkEventType.Nothing) + { + if (LogFilter.logDev) { Debug.Log("Server event: host=" + m_ServerHostId + " event=" + networkEvent + " error=" + error); } + } + + switch (networkEvent) + { + case NetworkEventType.ConnectEvent: + { + HandleConnect(connectionId, error); + break; + } + + case NetworkEventType.DataEvent: + { + HandleData(connectionId, channelId, receivedSize, error); + break; + } + + case NetworkEventType.DisconnectEvent: + { + HandleDisconnect(connectionId, error); + break; + } + + case NetworkEventType.Nothing: + break; + + default: + if (LogFilter.logError) { Debug.LogError("Unknown network message type received: " + networkEvent); } + break; + } + } + while (networkEvent != NetworkEventType.Nothing); + + UpdateConnections(); + } + + /// + /// This looks up the network connection object for the specified connection Id. + /// + /// The connection id to look up. + /// A NetworkConnection objects, or null if no connection found. + public NetworkConnection FindConnection(int connectionId) + { + if (connectionId < 0 || connectionId >= m_Connections.Count) + return null; + + return m_Connections[connectionId]; + } + + /// + /// This adds a connection created by external code to the server's list of connections, at the connection's connectionId index. + /// Connections are usually added automatically, this is a low-level function for the rare special case of externally created connections. + /// + /// A new connection object. + /// True if added. + public bool SetConnectionAtIndex(NetworkConnection conn) + { + while (m_Connections.Count <= conn.connectionId) + { + m_Connections.Add(null); + } + + if (m_Connections[conn.connectionId] != null) + { + // already a connection at this index + return false; + } + + m_Connections[conn.connectionId] = conn; + conn.SetHandlers(m_MessageHandlers); + return true; + } + + /// + /// This removes a connection object from the server's list of connections. + /// This is a low-level function that should not be used for regular connections. It is only safe to remove connections added with SetConnectionAtIndex() using this function. + /// + /// The id of the connection to remove. + /// True if removed. + public bool RemoveConnectionAtIndex(int connectionId) + { + if (connectionId < 0 || connectionId >= m_Connections.Count) + return false; + + m_Connections[connectionId] = null; + return true; + } + + void HandleConnect(int connectionId, byte error) + { + if (LogFilter.logDebug) { Debug.Log("NetworkServerSimple accepted client:" + connectionId); } + + if (error != 0) + { + OnConnectError(connectionId, error); + return; + } + + string address; + int port; + NetworkID networkId; + NodeID node; + byte error2; + NetworkManager.activeTransport.GetConnectionInfo(m_ServerHostId, connectionId, out address, out port, out networkId, out node, out error2); + + NetworkConnection conn = (NetworkConnection)Activator.CreateInstance(m_NetworkConnectionClass); + conn.SetHandlers(m_MessageHandlers); + conn.Initialize(address, m_ServerHostId, connectionId, m_HostTopology); + conn.lastError = (NetworkError)error2; + + // add connection at correct index + while (m_Connections.Count <= connectionId) + { + m_Connections.Add(null); + } + m_Connections[connectionId] = conn; + + OnConnected(conn); + } + + void HandleDisconnect(int connectionId, byte error) + { + if (LogFilter.logDebug) { Debug.Log("NetworkServerSimple disconnect client:" + connectionId); } + + var conn = FindConnection(connectionId); + if (conn == null) + { + return; + } + conn.lastError = (NetworkError)error; + + if (error != 0) + { + if ((NetworkError)error != NetworkError.Timeout) + { + m_Connections[connectionId] = null; + if (LogFilter.logError) { Debug.LogError("Server client disconnect error, connectionId: " + connectionId + " error: " + (NetworkError)error); } + + OnDisconnectError(conn, error); + return; + } + } + + conn.Disconnect(); + m_Connections[connectionId] = null; + if (LogFilter.logDebug) { Debug.Log("Server lost client:" + connectionId); } + + OnDisconnected(conn); + } + + void HandleData(int connectionId, int channelId, int receivedSize, byte error) + { + var conn = FindConnection(connectionId); + if (conn == null) + { + if (LogFilter.logError) { Debug.LogError("HandleData Unknown connectionId:" + connectionId); } + return; + } + conn.lastError = (NetworkError)error; + + if (error != 0) + { + OnDataError(conn, error); + return; + } + + m_MsgReader.SeekZero(); + OnData(conn, receivedSize, channelId); + } + + /// + /// This sends the data in an array of bytes to the connected client. + /// + /// The id of the connection to send on. + /// The data to send. + /// The size of the data to send. + /// The channel to send the data on. + public void SendBytesTo(int connectionId, byte[] bytes, int numBytes, int channelId) + { + var outConn = FindConnection(connectionId); + if (outConn == null) + { + return; + } + outConn.SendBytes(bytes, numBytes, channelId); + } + + /// + /// This sends the contents of a NetworkWriter object to the connected client. + /// + /// The id of the connection to send on. + /// The writer object to send. + /// The channel to send the data on. + public void SendWriterTo(int connectionId, NetworkWriter writer, int channelId) + { + var outConn = FindConnection(connectionId); + if (outConn == null) + { + return; + } + outConn.SendWriter(writer, channelId); + } + + /// + /// This disconnects the connection of the corresponding connection id. + /// + /// The id of the connection to disconnect. + public void Disconnect(int connectionId) + { + var outConn = FindConnection(connectionId); + if (outConn == null) + { + return; + } + outConn.Disconnect(); + m_Connections[connectionId] = null; + } + + /// + /// This disconnects all of the active connections. + /// + public void DisconnectAllConnections() + { + for (int i = 0; i < m_Connections.Count; i++) + { + NetworkConnection conn = m_Connections[i]; + if (conn != null) + { + conn.Disconnect(); + conn.Dispose(); + } + } + } + + // --------------------------- virtuals --------------------------------------- + + /// + /// A virtual function that is invoked when there is a connection error. + /// + /// The id of the connection with the error. + /// The error code. + public virtual void OnConnectError(int connectionId, byte error) + { + Debug.LogError("OnConnectError error:" + error); + } + + /// + /// A virtual function that is called when a data error occurs on a connection. + /// + /// The connection object that the error occured on. + /// The error code. + public virtual void OnDataError(NetworkConnection conn, byte error) + { + Debug.LogError("OnDataError error:" + error); + } + + /// + /// A virtual function that is called when a disconnect error happens. + /// + /// The connection object that the error occured on. + /// The error code. + public virtual void OnDisconnectError(NetworkConnection conn, byte error) + { + Debug.LogError("OnDisconnectError error:" + error); + } + + /// + /// This virtual function can be overridden to perform custom functionality for new network connections. + /// By default OnConnected just invokes a connect event on the new connection. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public abstract class ExampleScript : NetworkManager + /// { + /// public virtual void OnConnected(NetworkConnection conn) + /// { + /// conn.InvokeHandlerNoData(MsgType.Connect); + /// } + /// } + /// + /// + /// The new connection object. + public virtual void OnConnected(NetworkConnection conn) + { + conn.InvokeHandlerNoData(MsgType.Connect); + } + + /// + /// This virtual function can be overridden to perform custom functionality for disconnected network connections. + /// By default OnConnected just invokes a disconnect event on the new connection. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public abstract class ExampleScript : NetworkManager + /// { + /// public virtual void OnDisconnected(NetworkConnection conn) + /// { + /// conn.InvokeHandlerNoData(MsgType.Disconnect); + /// } + /// } + /// + /// + /// + public virtual void OnDisconnected(NetworkConnection conn) + { + conn.InvokeHandlerNoData(MsgType.Disconnect); + } + + /// + /// This virtual function can be overridden to perform custom functionality when data is received for a connection. + /// By default this function calls HandleData() which will process the data and invoke message handlers for any messages that it finds. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public abstract class ExampleScript : NetworkManager + /// { + /// byte[] msgBuffer = new byte[1024]; + /// + /// public virtual void OnData(NetworkConnection conn, int channelId, int receivedSize) + /// { + /// conn.TransportRecieve(msgBuffer, receivedSize, channelId); + /// } + /// } + /// + /// + /// + /// + /// + public virtual void OnData(NetworkConnection conn, int receivedSize, int channelId) + { + conn.TransportReceive(m_MsgBuffer, receivedSize, channelId); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkStartPosition.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkStartPosition.cs new file mode 100644 index 00000000..ce1d6e85 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkStartPosition.cs @@ -0,0 +1,25 @@ +using System; +using UnityEngine; + +namespace UnityEngine.Networking +{ + /// + /// This component is used to make a gameObject a starting position for spawning player objects in multiplayer games. + /// This object's transform will be automatically registered and unregistered with the NetworkManager as a starting position. + /// + [DisallowMultipleComponent] + [AddComponentMenu("Network/NetworkStartPosition")] + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class NetworkStartPosition : MonoBehaviour + { + public void Awake() + { + NetworkManager.RegisterStartPosition(transform); + } + + public void OnDestroy() + { + NetworkManager.UnRegisterStartPosition(transform); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkTranformChild.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkTranformChild.cs new file mode 100644 index 00000000..30925b5b --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkTranformChild.cs @@ -0,0 +1,520 @@ +using System; +using UnityEngine; + +namespace UnityEngine.Networking +{ + /// + /// A component to synchronize the position of child transforms of networked objects. + /// There must be a NetworkTransform on the root object of the hierarchy. There can be multiple NetworkTransformChild components on an object. This does not use physics for synchronization, it simply synchronizes the localPosition and localRotation of the child transform and lerps towards the recieved values. + /// + [AddComponentMenu("Network/NetworkTransformChild")] + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class NetworkTransformChild : NetworkBehaviour + { + [SerializeField] + Transform m_Target; + + [SerializeField] + uint m_ChildIndex; + + NetworkTransform m_Root; + + [SerializeField] float m_SendInterval = 0.1f; + [SerializeField] NetworkTransform.AxisSyncMode m_SyncRotationAxis = NetworkTransform.AxisSyncMode.AxisXYZ; + [SerializeField] NetworkTransform.CompressionSyncMode m_RotationSyncCompression = NetworkTransform.CompressionSyncMode.None; + [SerializeField] float m_MovementThreshold = 0.001f; + + [SerializeField] float m_InterpolateRotation = 0.5f; + [SerializeField] float m_InterpolateMovement = 0.5f; + [SerializeField] NetworkTransform.ClientMoveCallback3D m_ClientMoveCallback3D; + + + // movement smoothing + Vector3 m_TargetSyncPosition; + Quaternion m_TargetSyncRotation3D; + + float m_LastClientSyncTime; // last time client received a sync from server + float m_LastClientSendTime; // last time client send a sync to server + + Vector3 m_PrevPosition; + Quaternion m_PrevRotation; + + const float k_LocalMovementThreshold = 0.00001f; + const float k_LocalRotationThreshold = 0.00001f; + + NetworkWriter m_LocalTransformWriter; + + // settings + /// + /// The child transform to be synchronized. + /// + public Transform target { get {return m_Target; } set { m_Target = value; OnValidate(); } } + /// + /// A unique Identifier for this NetworkTransformChild component on this root object. + /// + public uint childIndex { get { return m_ChildIndex; }} + /// + /// The sendInterval controls how often state updates are sent for this object. + /// + public float sendInterval { get { return m_SendInterval; } set { m_SendInterval = value; } } + /// + /// Which axis should rotation by synchronized for. + /// + public NetworkTransform.AxisSyncMode syncRotationAxis { get { return m_SyncRotationAxis; } set { m_SyncRotationAxis = value; } } + /// + /// How much to compress rotation sync updates. + /// + public NetworkTransform.CompressionSyncMode rotationSyncCompression { get { return m_RotationSyncCompression; } set { m_RotationSyncCompression = value; } } + /// + /// The distance that an object can move without sending a movement synchronization update. + /// This applies to the child object's localPosition, not it's world position. + /// + public float movementThreshold { get { return m_MovementThreshold; } set { m_MovementThreshold = value; } } + /// + /// The rate to interpolate to the target rotation. + /// A value of 1 will snap to the position, and lower positive values will interpolate more slowly. + /// + public float interpolateRotation { get { return m_InterpolateRotation; } set { m_InterpolateRotation = value; } } + /// + /// The rate to interpolate towards the target position. + /// A value of 1 will snap to the position, and lower positive values will interpolate more slowly. + /// + public float interpolateMovement { get { return m_InterpolateMovement; } set { m_InterpolateMovement = value; } } + /// + /// A callback function to allow server side validation of the movement of the child object. + /// + public NetworkTransform.ClientMoveCallback3D clientMoveCallback3D { get { return m_ClientMoveCallback3D; } set { m_ClientMoveCallback3D = value; } } + + // runtime data + /// + /// The most recent time when a movement synchronization packet arrived for this object. + /// + public float lastSyncTime { get { return m_LastClientSyncTime; } } + /// + /// The target position interpolating towards. + /// + public Vector3 targetSyncPosition { get { return m_TargetSyncPosition; } } + /// + /// The target rotation interpolating towards. + /// + public Quaternion targetSyncRotation3D { get { return m_TargetSyncRotation3D; } } + + void OnValidate() + { + // root parent of target must have a NetworkTransform + if (m_Target != null) + { + Transform parent = m_Target.parent; + if (parent == null) + { + if (LogFilter.logError) { Debug.LogError("NetworkTransformChild target cannot be the root transform."); } + m_Target = null; + return; + } + while (parent.parent != null) + { + parent = parent.parent; + } + + m_Root = parent.gameObject.GetComponent(); + if (m_Root == null) + { + if (LogFilter.logError) { Debug.LogError("NetworkTransformChild root must have NetworkTransform"); } + m_Target = null; + return; + } + } + + if (m_Root != null) + { + // childIndex is the index within all the NetworkChildTransforms on the root + m_ChildIndex = UInt32.MaxValue; + var childTransforms = m_Root.GetComponents(); + for (uint i = 0; i < childTransforms.Length; i++) + { + if (childTransforms[i] == this) + { + m_ChildIndex = i; + break; + } + } + if (m_ChildIndex == UInt32.MaxValue) + { + if (LogFilter.logError) { Debug.LogError("NetworkTransformChild component must be a child in the same hierarchy"); } + m_Target = null; + } + } + + if (m_SendInterval < 0) + { + m_SendInterval = 0; + } + + if (m_SyncRotationAxis < NetworkTransform.AxisSyncMode.None || m_SyncRotationAxis > NetworkTransform.AxisSyncMode.AxisXYZ) + { + m_SyncRotationAxis = NetworkTransform.AxisSyncMode.None; + } + + if (movementThreshold < 0) + { + movementThreshold = 0.00f; + } + + if (interpolateRotation < 0) + { + interpolateRotation = 0.01f; + } + if (interpolateRotation > 1.0f) + { + interpolateRotation = 1.0f; + } + + if (interpolateMovement < 0) + { + interpolateMovement = 0.01f; + } + if (interpolateMovement > 1.0f) + { + interpolateMovement = 1.0f; + } + } + + void Awake() + { + m_PrevPosition = m_Target.localPosition; + m_PrevRotation = m_Target.localRotation; + + // cache these to avoid per-frame allocations. + if (localPlayerAuthority) + { + m_LocalTransformWriter = new NetworkWriter(); + } + } + + public override bool OnSerialize(NetworkWriter writer, bool initialState) + { + if (initialState) + { + // always write initial state, no dirty bits + } + else if (syncVarDirtyBits == 0) + { + writer.WritePackedUInt32(0); + return false; + } + else + { + // dirty bits + writer.WritePackedUInt32(1); + } + + SerializeModeTransform(writer); + return true; + } + + void SerializeModeTransform(NetworkWriter writer) + { + // position + writer.Write(m_Target.localPosition); + + // rotation + if (m_SyncRotationAxis != NetworkTransform.AxisSyncMode.None) + { + NetworkTransform.SerializeRotation3D(writer, m_Target.localRotation, syncRotationAxis, rotationSyncCompression); + } + m_PrevPosition = m_Target.localPosition; + m_PrevRotation = m_Target.localRotation; + } + + public override void OnDeserialize(NetworkReader reader, bool initialState) + { + if (isServer && NetworkServer.localClientActive) + return; + + if (!initialState) + { + if (reader.ReadPackedUInt32() == 0) + return; + } + UnserializeModeTransform(reader, initialState); + + m_LastClientSyncTime = Time.time; + } + + void UnserializeModeTransform(NetworkReader reader, bool initialState) + { + if (hasAuthority) + { + // this component must read the data that the server wrote, even if it ignores it. + // otherwise the NetworkReader stream will still contain that data for the next component. + + // position + reader.ReadVector3(); + + if (syncRotationAxis != NetworkTransform.AxisSyncMode.None) + { + NetworkTransform.UnserializeRotation3D(reader, syncRotationAxis, rotationSyncCompression); + } + return; + } + + if (isServer && m_ClientMoveCallback3D != null) + { + var pos = reader.ReadVector3(); + var vel = Vector3.zero; + var rot = Quaternion.identity; + if (syncRotationAxis != NetworkTransform.AxisSyncMode.None) + { + rot = NetworkTransform.UnserializeRotation3D(reader, syncRotationAxis, rotationSyncCompression); + } + + if (m_ClientMoveCallback3D(ref pos, ref vel, ref rot)) + { + m_TargetSyncPosition = pos; + if (syncRotationAxis != NetworkTransform.AxisSyncMode.None) + { + m_TargetSyncRotation3D = rot; + } + } + else + { + // rejected by callback + return; + } + } + else + { + // position + m_TargetSyncPosition = reader.ReadVector3(); + + // rotation + if (syncRotationAxis != NetworkTransform.AxisSyncMode.None) + { + m_TargetSyncRotation3D = NetworkTransform.UnserializeRotation3D(reader, syncRotationAxis, rotationSyncCompression); + } + } + } + + void FixedUpdate() + { + if (isServer) + { + FixedUpdateServer(); + } + if (isClient) + { + FixedUpdateClient(); + } + } + + void FixedUpdateServer() + { + if (syncVarDirtyBits != 0) + return; + + // dont run if network isn't active + if (!NetworkServer.active) + return; + + // dont run if we haven't been spawned yet + if (!isServer) + return; + + // dont' auto-dirty if no send interval + if (GetNetworkSendInterval() == 0) + return; + + float distance = (m_Target.localPosition - m_PrevPosition).sqrMagnitude; + if (distance < movementThreshold) + { + distance = Quaternion.Angle(m_PrevRotation, m_Target.localRotation); + if (distance < movementThreshold) + { + return; + } + } + + // This will cause transform to be sent + SetDirtyBit(1); + } + + void FixedUpdateClient() + { + // dont run if we haven't received any sync data + if (m_LastClientSyncTime == 0) + return; + + // dont run if network isn't active + if (!NetworkServer.active && !NetworkClient.active) + return; + + // dont run if we haven't been spawned yet + if (!isServer && !isClient) + return; + + // dont run if not expecting continuous updates + if (GetNetworkSendInterval() == 0) + return; + + // dont run this if this client has authority over this player object + if (hasAuthority) + return; + + // interpolate on client + if (m_LastClientSyncTime != 0) + { + if (m_InterpolateMovement > 0) + { + m_Target.localPosition = Vector3.Lerp(m_Target.localPosition, m_TargetSyncPosition, m_InterpolateMovement); + } + else + { + m_Target.localPosition = m_TargetSyncPosition; + } + + if (m_InterpolateRotation > 0) + { + m_Target.localRotation = Quaternion.Slerp(m_Target.localRotation, m_TargetSyncRotation3D, m_InterpolateRotation); + } + else + { + m_Target.localRotation = m_TargetSyncRotation3D; + } + } + } + + // --------------------- local transform sync ------------------------ + + void Update() + { + if (!hasAuthority) + return; + + if (!localPlayerAuthority) + return; + + if (NetworkServer.active) + return; + + if (Time.time - m_LastClientSendTime > GetNetworkSendInterval()) + { + SendTransform(); + m_LastClientSendTime = Time.time; + } + } + + bool HasMoved() + { + float diff = 0; + + // check if position has changed + diff = (m_Target.localPosition - m_PrevPosition).sqrMagnitude; + if (diff > k_LocalMovementThreshold) + { + return true; + } + + // check if rotation has changed + diff = Quaternion.Angle(m_Target.localRotation, m_PrevRotation); + if (diff > k_LocalRotationThreshold) + { + return true; + } + + // check if velocty has changed + + return false; + } + + [Client] + void SendTransform() + { + if (!HasMoved() || ClientScene.readyConnection == null) + { + return; + } + + m_LocalTransformWriter.StartMessage(MsgType.LocalChildTransform); + m_LocalTransformWriter.Write(netId); + m_LocalTransformWriter.WritePackedUInt32(m_ChildIndex); + SerializeModeTransform(m_LocalTransformWriter); + + m_PrevPosition = m_Target.localPosition; + m_PrevRotation = m_Target.localRotation; + + + m_LocalTransformWriter.FinishMessage(); + +#if UNITY_EDITOR + Profiler.IncrementStatOutgoing(MsgType.LocalChildTransform, "16:LocalChildTransform"); +#endif + ClientScene.readyConnection.SendWriter(m_LocalTransformWriter, GetNetworkChannel()); + } + + static internal void HandleChildTransform(NetworkMessage netMsg) + { + NetworkInstanceId netId = netMsg.reader.ReadNetworkId(); + uint childIndex = netMsg.reader.ReadPackedUInt32(); + +#if UNITY_EDITOR + Profiler.IncrementStatIncoming(MsgType.LocalChildTransform, "16:LocalChildTransform"); +#endif + + GameObject foundObj = NetworkServer.FindLocalObject(netId); + if (foundObj == null) + { + if (LogFilter.logError) { Debug.LogError("Received NetworkTransformChild data for GameObject that doesn't exist"); } + return; + } + var children = foundObj.GetComponents(); + if (children == null || children.Length == 0) + { + if (LogFilter.logError) { Debug.LogError("HandleChildTransform no children"); } + return; + } + if (childIndex >= children.Length) + { + if (LogFilter.logError) { Debug.LogError("HandleChildTransform childIndex invalid"); } + return; + } + + NetworkTransformChild foundSync = children[childIndex]; + if (foundSync == null) + { + if (LogFilter.logError) { Debug.LogError("HandleChildTransform null target"); } + return; + } + if (!foundSync.localPlayerAuthority) + { + if (LogFilter.logError) { Debug.LogError("HandleChildTransform no localPlayerAuthority"); } + return; + } + + if (!netMsg.conn.clientOwnedObjects.Contains(netId)) + { + if (LogFilter.logWarn) { Debug.LogWarning("NetworkTransformChild netId:" + netId + " is not for a valid player"); } + return; + } + + foundSync.UnserializeModeTransform(netMsg.reader, false); + foundSync.m_LastClientSyncTime = Time.time; + + if (!foundSync.isClient) + { + // dedicated server wont interpolate, so snap. + foundSync.m_Target.localPosition = foundSync.m_TargetSyncPosition; + foundSync.m_Target.localRotation = foundSync.m_TargetSyncRotation3D; + } + } + + public override int GetNetworkChannel() + { + return Channels.DefaultUnreliable; + } + + public override float GetNetworkSendInterval() + { + return m_SendInterval; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkTransform.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkTransform.cs new file mode 100644 index 00000000..d8a5b2f7 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkTransform.cs @@ -0,0 +1,1793 @@ +using System; +using UnityEngine; + +namespace UnityEngine.Networking +{ + /// + /// A component to synchronize the position and rotation of networked objects. + /// The movement of game objects can be networked by this component. There are two models of authority for networked movement: + /// If the object has authority on the client, then it should be controlled locally on the owning client, then movement state information will be sent from the owning client to the server, then broadcast to all of the other clients. This is common for player objects. + /// If the object has authority on the server, then it should be controlled on the server and movement state information will be sent to all clients. This is common for objects not related to a specific client, such as an enemy unit. + /// + [DisallowMultipleComponent] + [AddComponentMenu("Network/NetworkTransform")] + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class NetworkTransform : NetworkBehaviour + { + /// + /// How to synchronize an object's position. + /// + public enum TransformSyncMode + { + /// + /// Dont synchronize. + /// + SyncNone = 0, + /// + /// Sync using the game object's base transform. + /// + SyncTransform = 1, + /// + /// Sync using the Rigidbody2D component. + /// + SyncRigidbody2D = 2, + /// + /// Sync using the Rigidbody component. + /// + SyncRigidbody3D = 3, + /// + /// Sync using the CharacterController component. + /// + SyncCharacterController = 4 + } + + /// + /// An axis or set of axis. + /// + public enum AxisSyncMode + { + /// + /// Do not sync. + /// + None, + /// + /// Only x axis. + /// + AxisX, + /// + /// Only the y axis. + /// + AxisY, + /// + /// Only the z axis. + /// + AxisZ, + /// + /// The x and y axis. + /// + AxisXY, + /// + /// The x and z axis. + /// + AxisXZ, + /// + /// The y and z axis. + /// + AxisYZ, + /// + /// The x, y and z axis. + /// + AxisXYZ + } + + /// + /// How much to compress sync data. + /// + public enum CompressionSyncMode + { + /// + /// Do not compress. + /// + None, + /// + /// A low amount of compression that preserves accuracy. + /// + Low, + /// + /// High Compression - sacrificing accuracy. + /// + High + } + + public delegate bool ClientMoveCallback3D(ref Vector3 position, ref Vector3 velocity, ref Quaternion rotation); + public delegate bool ClientMoveCallback2D(ref Vector2 position, ref Vector2 velocity, ref float rotation); + + [SerializeField] TransformSyncMode m_TransformSyncMode = TransformSyncMode.SyncNone; + [SerializeField] float m_SendInterval = 0.1f; + [SerializeField] AxisSyncMode m_SyncRotationAxis = AxisSyncMode.AxisXYZ; + [SerializeField] CompressionSyncMode m_RotationSyncCompression = CompressionSyncMode.None; + [SerializeField] bool m_SyncSpin; + [SerializeField] float m_MovementTheshold = 0.001f; + [SerializeField] float m_VelocityThreshold = 0.0001f; + + [SerializeField] float m_SnapThreshold = 5.0f; + [SerializeField] float m_InterpolateRotation = 1.0f; + [SerializeField] float m_InterpolateMovement = 1.0f; + [SerializeField] ClientMoveCallback3D m_ClientMoveCallback3D; + [SerializeField] ClientMoveCallback2D m_ClientMoveCallback2D; + + Rigidbody m_RigidBody3D; + Rigidbody2D m_RigidBody2D; + CharacterController m_CharacterController; + bool m_Grounded = true; + + // movement smoothing + + Vector3 m_TargetSyncPosition; + Vector3 m_TargetSyncVelocity; + + Vector3 m_FixedPosDiff; + + Quaternion m_TargetSyncRotation3D; + Vector3 m_TargetSyncAngularVelocity3D; + + float m_TargetSyncRotation2D; + float m_TargetSyncAngularVelocity2D; + + float m_LastClientSyncTime; // last time client received a sync from server + float m_LastClientSendTime; // last time client send a sync to server + + Vector3 m_PrevPosition; + Quaternion m_PrevRotation; + float m_PrevRotation2D; + float m_PrevVelocity; + + const float k_LocalMovementThreshold = 0.00001f; + const float k_LocalRotationThreshold = 0.00001f; + const float k_LocalVelocityThreshold = 0.00001f; + const float k_MoveAheadRatio = 0.1f; + + NetworkWriter m_LocalTransformWriter; + + // settings + + /// + /// What method to use to sync the object's position. + /// + public TransformSyncMode transformSyncMode { get { return m_TransformSyncMode; } set { m_TransformSyncMode = value; } } + /// + /// The sendInterval controls how often state updates are sent for this object. + /// Unlike most NetworkBehaviour scripts, for NetworkTransform this is implemented at a per-object level rather than at the per-script level. This allows more flexibility as this component is used in various situation. + /// If sendInterval is non-zero, then transform state updates are send at most once every sendInterval seconds. However, if an object is stationary, no updates are sent. + /// If sendInterval is zero, then no automatic updates are sent. In this case, calling SetDirtyBits() on the NetworkTransform will cause an updates to be sent. This could be used for objects like bullets that have a predictable trajectory. + /// + public float sendInterval { get { return m_SendInterval; } set { m_SendInterval = value; } } + /// + /// Which axis should rotation by synchronized for. + /// + public AxisSyncMode syncRotationAxis { get { return m_SyncRotationAxis; } set { m_SyncRotationAxis = value; } } + /// + /// How much to compress rotation sync updates. + /// + public CompressionSyncMode rotationSyncCompression { get { return m_RotationSyncCompression; } set { m_RotationSyncCompression = value; } } + public bool syncSpin { get { return m_SyncSpin; } set { m_SyncSpin = value; } } + /// + /// The distance that an object can move without sending a movement synchronization update. + /// + public float movementTheshold { get { return m_MovementTheshold; } set { m_MovementTheshold = value; } } + /// + /// The minimum velocity difference that will be synchronized over the network. + /// + public float velocityThreshold { get { return m_VelocityThreshold; } set { m_VelocityThreshold = value; } } + /// + /// If a movement update puts an object further from its current position that this value, it will snap to the position instead of moving smoothly. + /// + public float snapThreshold { get { return m_SnapThreshold; } set { m_SnapThreshold = value; } } + /// + /// Enables interpolation of the synchronized rotation. + /// If this is not set, object will snap to the new rotation. The larger this number is, the faster the object will interpolate to the target facing direction. + /// + public float interpolateRotation { get { return m_InterpolateRotation; } set { m_InterpolateRotation = value; } } + /// + /// Enables interpolation of the synchronized movement. + /// The larger this number is, the faster the object will interpolate to the target position. + /// + public float interpolateMovement { get { return m_InterpolateMovement; } set { m_InterpolateMovement = value; } } + /// + /// A callback that can be used to validate on the server, the movement of client authoritative objects. + /// This version of the callback works with objects that use 3D physics. The callback function may return false to reject the movement request completely. It may also modify the movement parameters - which are passed by reference. + /// The example below set the callback in OnStartServer, and will disconnect a client that moves an object into an invalid position after a number of failures. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class MyMover : NetworkManager + /// { + /// public int cheatCount = 0; + /// + /// public bool ValidateMove(ref Vector3 position, ref Vector3 velocity, ref Quaternion rotation) + /// { + /// Debug.Log("pos:" + position); + /// if (position.y > 9) + /// { + /// position.y = 9; + /// cheatCount += 1; + /// if (cheatCount == 10) + /// { + /// Invoke("DisconnectCheater", 0.1f); + /// } + /// } + /// return true; + /// } + /// + /// void DisconnectCheater() + /// { + /// GetComponent<NetworkIdentity>().connectionToClient.Disconnect(); + /// } + /// + /// public override void OnStartServer() + /// { + /// GetComponent<NetworkTransform>().clientMoveCallback3D = ValidateMove; + /// } + /// } + /// + /// This kind of server-side movement validation should be used in conjunction with client side movement validation. The callback should only detect a failure if a client is by-passing client side movement checks - by cheating. + /// + public ClientMoveCallback3D clientMoveCallback3D { get { return m_ClientMoveCallback3D; } set { m_ClientMoveCallback3D = value; } } + /// + /// A callback that can be used to validate on the server, the movement of client authoritative objects. + /// This version of the callback works with objects that use 2D physics. The callback function may return false to reject the movement request completely. It may also modify the movement parameters - which are passed by reference. + /// The example below set the callback in OnStartServer, and will disconnect a client that moves an object into an invalid position after a number of failures. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class MyMover : NetworkManager + /// { + /// public int cheatCount = 0; + /// + /// public bool ValidateMove(ref Vector2 position, ref Vector2 velocity, ref float rotation) + /// { + /// Debug.Log("pos:" + position); + /// if (position.y > 9) + /// { + /// position.y = 9; + /// cheatCount += 1; + /// if (cheatCount == 10) + /// { + /// Invoke("DisconnectCheater", 0.1f); + /// } + /// } + /// return true; + /// } + /// + /// void DisconnectCheater() + /// { + /// GetComponent<NetworkIdentity>().connectionToClient.Disconnect(); + /// } + /// + /// public override void OnStartServer() + /// { + /// GetComponent<NetworkTransform>().clientMoveCallback2D = ValidateMove; + /// } + /// } + /// + /// This kind of server-side movement validation should be used in conjunction with client side movement validation. The callback should only detect a failure if a client is by-passing client side movement checks - by cheating. + /// + public ClientMoveCallback2D clientMoveCallback2D { get { return m_ClientMoveCallback2D; } set { m_ClientMoveCallback2D = value; } } + + // runtime data + + /// + /// Cached CharacterController. + /// + public CharacterController characterContoller { get { return m_CharacterController; } } + /// + /// Cached Rigidbody. + /// + public Rigidbody rigidbody3D { get { return m_RigidBody3D; } } + /// + /// Cached Rigidbody2D. + /// +#pragma warning disable 109 + new public Rigidbody2D rigidbody2D { get { return m_RigidBody2D; } } +#pragma warning restore 109 + /// + /// The most recent time when a movement synchronization packet arrived for this object. + /// + public float lastSyncTime { get { return m_LastClientSyncTime; } } + /// + /// The target position interpolating towards. + /// + public Vector3 targetSyncPosition { get { return m_TargetSyncPosition; } } + /// + /// The velocity send for synchronization. + /// + public Vector3 targetSyncVelocity { get { return m_TargetSyncVelocity; } } + /// + /// The target position interpolating towards. + /// + public Quaternion targetSyncRotation3D { get { return m_TargetSyncRotation3D; } } + /// + /// The target rotation interpolating towards. + /// + public float targetSyncRotation2D { get { return m_TargetSyncRotation2D; } } + /// + /// Tells the NetworkTransform that it is on a surface (this is the default). + /// Object that are NOT grounded will not interpolate their vertical velocity. This avoid the problem of interpolation fighting with gravity on non-authoritative objects. This only works for RigidBody2D physics objects. + /// + public bool grounded { get { return m_Grounded; } set { m_Grounded = value; } } + + void OnValidate() + { + if (m_TransformSyncMode < TransformSyncMode.SyncNone || m_TransformSyncMode > TransformSyncMode.SyncCharacterController) + { + m_TransformSyncMode = TransformSyncMode.SyncTransform; + } + + if (m_SendInterval < 0) + { + m_SendInterval = 0; + } + + if (m_SyncRotationAxis < AxisSyncMode.None || m_SyncRotationAxis > AxisSyncMode.AxisXYZ) + { + m_SyncRotationAxis = AxisSyncMode.None; + } + + if (m_MovementTheshold < 0) + { + m_MovementTheshold = 0.00f; + } + + if (m_VelocityThreshold < 0) + { + m_VelocityThreshold = 0.00f; + } + + if (m_SnapThreshold < 0) + { + m_SnapThreshold = 0.01f; + } + + if (m_InterpolateRotation < 0) + { + m_InterpolateRotation = 0.01f; + } + + if (m_InterpolateMovement < 0) + { + m_InterpolateMovement = 0.01f; + } + } + + void Awake() + { + m_RigidBody3D = GetComponent(); + m_RigidBody2D = GetComponent(); + m_CharacterController = GetComponent(); + m_PrevPosition = transform.position; + m_PrevRotation = transform.rotation; + m_PrevVelocity = 0; + + // cache these to avoid per-frame allocations. + if (localPlayerAuthority) + { + m_LocalTransformWriter = new NetworkWriter(); + } + } + + public override void OnStartServer() + { + m_LastClientSyncTime = 0; + } + + public override bool OnSerialize(NetworkWriter writer, bool initialState) + { + if (initialState) + { + // always write initial state, no dirty bits + } + else if (syncVarDirtyBits == 0) + { + writer.WritePackedUInt32(0); + return false; + } + else + { + // dirty bits + writer.WritePackedUInt32(1); + } + + switch (transformSyncMode) + { + case TransformSyncMode.SyncNone: + { + return false; + } + case TransformSyncMode.SyncTransform: + { + SerializeModeTransform(writer); + break; + } + case TransformSyncMode.SyncRigidbody3D: + { + SerializeMode3D(writer); + break; + } + case TransformSyncMode.SyncRigidbody2D: + { + SerializeMode2D(writer); + break; + } + case TransformSyncMode.SyncCharacterController: + { + SerializeModeCharacterController(writer); + break; + } + } + return true; + } + + void SerializeModeTransform(NetworkWriter writer) + { + // position + writer.Write(transform.position); + + // no velocity + + // rotation + if (m_SyncRotationAxis != AxisSyncMode.None) + { + SerializeRotation3D(writer, transform.rotation, syncRotationAxis, rotationSyncCompression); + } + + // no spin + + m_PrevPosition = transform.position; + m_PrevRotation = transform.rotation; + m_PrevVelocity = 0; + } + + void VerifySerializeComponentExists() + { + bool throwError = false; + Type componentMissing = null; + + switch (transformSyncMode) + { + case TransformSyncMode.SyncCharacterController: + if (!m_CharacterController && !(m_CharacterController = GetComponent())) + { + throwError = true; + componentMissing = typeof(CharacterController); + } + break; + + case TransformSyncMode.SyncRigidbody2D: + if (!m_RigidBody2D && !(m_RigidBody2D = GetComponent())) + { + throwError = true; + componentMissing = typeof(Rigidbody2D); + } + break; + + case TransformSyncMode.SyncRigidbody3D: + if (!m_RigidBody3D && !(m_RigidBody3D = GetComponent())) + { + throwError = true; + componentMissing = typeof(Rigidbody); + } + break; + } + + if (throwError && componentMissing != null) + { + throw new InvalidOperationException(string.Format("transformSyncMode set to {0} but no {1} component was found, did you call NetworkServer.Spawn on a prefab?", transformSyncMode, componentMissing.Name)); + } + } + + void SerializeMode3D(NetworkWriter writer) + { + VerifySerializeComponentExists(); + + if (isServer && m_LastClientSyncTime != 0) + { + // target position + writer.Write(m_TargetSyncPosition); + + // target velocity + SerializeVelocity3D(writer, m_TargetSyncVelocity, CompressionSyncMode.None); + + if (syncRotationAxis != AxisSyncMode.None) + { + // target rotation + SerializeRotation3D(writer, m_TargetSyncRotation3D, syncRotationAxis, rotationSyncCompression); + } + } + else + { + // current position + writer.Write(m_RigidBody3D.position); + + // current velocity + SerializeVelocity3D(writer, m_RigidBody3D.velocity, CompressionSyncMode.None); + + if (syncRotationAxis != AxisSyncMode.None) + { + // current rotation + SerializeRotation3D(writer, m_RigidBody3D.rotation, syncRotationAxis, rotationSyncCompression); + } + } + + // spin + if (m_SyncSpin) + { + SerializeSpin3D(writer, m_RigidBody3D.angularVelocity, syncRotationAxis, rotationSyncCompression); + } + + m_PrevPosition = m_RigidBody3D.position; + m_PrevRotation = transform.rotation; + m_PrevVelocity = m_RigidBody3D.velocity.sqrMagnitude; + } + + void SerializeModeCharacterController(NetworkWriter writer) + { + VerifySerializeComponentExists(); + + if (isServer && m_LastClientSyncTime != 0) + { + // target position + writer.Write(m_TargetSyncPosition); + + // no velocity + + if (syncRotationAxis != AxisSyncMode.None) + { + // target rotation + SerializeRotation3D(writer, m_TargetSyncRotation3D, syncRotationAxis, rotationSyncCompression); + } + } + else + { + // current position + writer.Write(transform.position); + + // no velocity + + if (syncRotationAxis != AxisSyncMode.None) + { + // current rotation + SerializeRotation3D(writer, transform.rotation, syncRotationAxis, rotationSyncCompression); + } + } + + // no spin + + m_PrevPosition = transform.position; + m_PrevRotation = transform.rotation; + m_PrevVelocity = 0; + } + + void SerializeMode2D(NetworkWriter writer) + { + VerifySerializeComponentExists(); + + if (isServer && m_LastClientSyncTime != 0) + { + // target position + writer.Write((Vector2)m_TargetSyncPosition); + + // target velocity + SerializeVelocity2D(writer, m_TargetSyncVelocity, CompressionSyncMode.None); + + // target rotation + if (syncRotationAxis != AxisSyncMode.None) + { + float orientation = m_TargetSyncRotation2D % 360; + if (orientation < 0) orientation += 360; + SerializeRotation2D(writer, orientation, rotationSyncCompression); + } + } + else + { + // current position + writer.Write(m_RigidBody2D.position); + + // current velocity + SerializeVelocity2D(writer, m_RigidBody2D.velocity, CompressionSyncMode.None); + + // current rotation + if (syncRotationAxis != AxisSyncMode.None) + { + float orientation = m_RigidBody2D.rotation % 360; + if (orientation < 0) orientation += 360; + SerializeRotation2D(writer, orientation, rotationSyncCompression); + } + } + + // spin + if (m_SyncSpin) + { + SerializeSpin2D(writer, m_RigidBody2D.angularVelocity, rotationSyncCompression); + } + + m_PrevPosition = m_RigidBody2D.position; + m_PrevRotation = transform.rotation; + m_PrevVelocity = m_RigidBody2D.velocity.sqrMagnitude; + } + + public override void OnDeserialize(NetworkReader reader, bool initialState) + { + if (isServer && NetworkServer.localClientActive) + return; + + if (!initialState) + { + if (reader.ReadPackedUInt32() == 0) + return; + } + + switch (transformSyncMode) + { + case TransformSyncMode.SyncNone: + { + return; + } + case TransformSyncMode.SyncTransform: + { + UnserializeModeTransform(reader, initialState); + break; + } + case TransformSyncMode.SyncRigidbody3D: + { + UnserializeMode3D(reader, initialState); + break; + } + case TransformSyncMode.SyncRigidbody2D: + { + UnserializeMode2D(reader, initialState); + break; + } + case TransformSyncMode.SyncCharacterController: + { + UnserializeModeCharacterController(reader, initialState); + break; + } + } + m_LastClientSyncTime = Time.time; + } + + void UnserializeModeTransform(NetworkReader reader, bool initialState) + { + if (hasAuthority) + { + // this component must read the data that the server wrote, even if it ignores it. + // otherwise the NetworkReader stream will still contain that data for the next component. + + // position + reader.ReadVector3(); + + if (syncRotationAxis != AxisSyncMode.None) + { + UnserializeRotation3D(reader, syncRotationAxis, rotationSyncCompression); + } + return; + } + + if (isServer && m_ClientMoveCallback3D != null) + { + var pos = reader.ReadVector3(); + var vel = Vector3.zero; + var rot = Quaternion.identity; + if (syncRotationAxis != AxisSyncMode.None) + { + rot = UnserializeRotation3D(reader, syncRotationAxis, rotationSyncCompression); + } + + if (m_ClientMoveCallback3D(ref pos, ref vel, ref rot)) + { + transform.position = pos; + if (syncRotationAxis != AxisSyncMode.None) + { + transform.rotation = rot; + } + } + else + { + // rejected by callback + return; + } + } + else + { + // position + transform.position = reader.ReadVector3(); + + // no velocity + + // rotation + if (syncRotationAxis != AxisSyncMode.None) + { + transform.rotation = UnserializeRotation3D(reader, syncRotationAxis, rotationSyncCompression); + } + + // no spin + } + } + + void UnserializeMode3D(NetworkReader reader, bool initialState) + { + if (hasAuthority) + { + // this component must read the data that the server wrote, even if it ignores it. + // otherwise the NetworkReader stream will still contain that data for the next component. + + // position + reader.ReadVector3(); + + // velocity + reader.ReadVector3(); + + if (syncRotationAxis != AxisSyncMode.None) + { + UnserializeRotation3D(reader, syncRotationAxis, rotationSyncCompression); + } + if (syncSpin) + { + UnserializeSpin3D(reader, syncRotationAxis, rotationSyncCompression); + } + return; + } + + if (isServer && m_ClientMoveCallback3D != null) + { + var pos = reader.ReadVector3(); + var vel = reader.ReadVector3(); + Quaternion rot = Quaternion.identity; + if (syncRotationAxis != AxisSyncMode.None) + { + rot = UnserializeRotation3D(reader, syncRotationAxis, rotationSyncCompression); + } + + if (m_ClientMoveCallback3D(ref pos, ref vel, ref rot)) + { + m_TargetSyncPosition = pos; + m_TargetSyncVelocity = vel; + if (syncRotationAxis != AxisSyncMode.None) + { + m_TargetSyncRotation3D = rot; + } + } + else + { + // rejected by callback + return; + } + } + else + { + // position + m_TargetSyncPosition = reader.ReadVector3(); + + // velocity + m_TargetSyncVelocity = reader.ReadVector3(); + + // rotation + if (syncRotationAxis != AxisSyncMode.None) + { + m_TargetSyncRotation3D = UnserializeRotation3D(reader, syncRotationAxis, rotationSyncCompression); + } + } + // spin + if (syncSpin) + { + m_TargetSyncAngularVelocity3D = UnserializeSpin3D(reader, syncRotationAxis, rotationSyncCompression); + } + + if (m_RigidBody3D == null) + return; + + if (isServer && !isClient) + { + // dedicated server needs to apply immediately, there is no interpolation + m_RigidBody3D.MovePosition(m_TargetSyncPosition); + m_RigidBody3D.MoveRotation(m_TargetSyncRotation3D); + m_RigidBody3D.velocity = m_TargetSyncVelocity; + return; + } + + // handle zero send rate + if (GetNetworkSendInterval() == 0) + { + m_RigidBody3D.MovePosition(m_TargetSyncPosition); + m_RigidBody3D.velocity = m_TargetSyncVelocity; + if (syncRotationAxis != AxisSyncMode.None) + { + m_RigidBody3D.MoveRotation(m_TargetSyncRotation3D); + } + if (syncSpin) + { + m_RigidBody3D.angularVelocity = m_TargetSyncAngularVelocity3D; + } + return; + } + + // handle position snap threshold + float dist = (m_RigidBody3D.position - m_TargetSyncPosition).magnitude; + if (dist > snapThreshold) + { + m_RigidBody3D.position = m_TargetSyncPosition; + m_RigidBody3D.velocity = m_TargetSyncVelocity; + } + + // handle no rotation interpolation + if (interpolateRotation == 0 && syncRotationAxis != AxisSyncMode.None) + { + m_RigidBody3D.rotation = m_TargetSyncRotation3D; + if (syncSpin) + { + m_RigidBody3D.angularVelocity = m_TargetSyncAngularVelocity3D; + } + } + + // handle no movement interpolation + if (m_InterpolateMovement == 0) + { + m_RigidBody3D.position = m_TargetSyncPosition; + } + + if (initialState && syncRotationAxis != AxisSyncMode.None) + { + m_RigidBody3D.rotation = m_TargetSyncRotation3D; + } + } + + void UnserializeMode2D(NetworkReader reader, bool initialState) + { + if (hasAuthority) + { + // this component must read the data that the server wrote, even if it ignores it. + // otherwise the NetworkReader stream will still contain that data for the next component. + + // position + reader.ReadVector2(); + + // velocity + reader.ReadVector2(); + + if (syncRotationAxis != AxisSyncMode.None) + { + UnserializeRotation2D(reader, rotationSyncCompression); + } + + if (syncSpin) + { + UnserializeSpin2D(reader, rotationSyncCompression); + } + return; + } + + if (m_RigidBody2D == null) + return; + + if (isServer && m_ClientMoveCallback2D != null) + { + Vector2 pos = reader.ReadVector2(); + Vector2 vel = reader.ReadVector2(); + float rot = 0; + if (syncRotationAxis != AxisSyncMode.None) + { + rot = UnserializeRotation2D(reader, rotationSyncCompression); + } + + if (m_ClientMoveCallback2D(ref pos, ref vel, ref rot)) + { + m_TargetSyncPosition = pos; + m_TargetSyncVelocity = vel; + if (syncRotationAxis != AxisSyncMode.None) + { + m_TargetSyncRotation2D = rot; + } + } + else + { + // rejected by callback + return; + } + } + else + { + // position + m_TargetSyncPosition = reader.ReadVector2(); + + // velocity + m_TargetSyncVelocity = reader.ReadVector2(); + + // rotation + if (syncRotationAxis != AxisSyncMode.None) + { + m_TargetSyncRotation2D = UnserializeRotation2D(reader, rotationSyncCompression); + } + } + + // spin + if (syncSpin) + { + m_TargetSyncAngularVelocity2D = UnserializeSpin2D(reader, rotationSyncCompression); + } + + if (isServer && !isClient) + { + // dedicated server needs to apply immediately, there is no interpolation + transform.position = m_TargetSyncPosition; + m_RigidBody2D.MoveRotation(m_TargetSyncRotation2D); + m_RigidBody2D.velocity = m_TargetSyncVelocity; + return; + } + + // handle zero send rate + if (GetNetworkSendInterval() == 0) + { + // NOTE: cannot use m_RigidBody2D.MovePosition() and set velocity in the same frame, so use transform.position + transform.position = m_TargetSyncPosition; + m_RigidBody2D.velocity = m_TargetSyncVelocity; + if (syncRotationAxis != AxisSyncMode.None) + { + m_RigidBody2D.MoveRotation(m_TargetSyncRotation2D); + } + if (syncSpin) + { + m_RigidBody2D.angularVelocity = m_TargetSyncAngularVelocity2D; + } + return; + } + + // handle position snap threshold + float dist = (m_RigidBody2D.position - (Vector2)m_TargetSyncPosition).magnitude; + if (dist > snapThreshold) + { + m_RigidBody2D.position = m_TargetSyncPosition; + m_RigidBody2D.velocity = m_TargetSyncVelocity; + } + + // handle no rotation interpolation + if (interpolateRotation == 0 && syncRotationAxis != AxisSyncMode.None) + { + m_RigidBody2D.rotation = m_TargetSyncRotation2D; + if (syncSpin) + { + m_RigidBody2D.angularVelocity = m_TargetSyncAngularVelocity2D; + } + } + + // handle no movement interpolation + if (m_InterpolateMovement == 0) + { + m_RigidBody2D.position = m_TargetSyncPosition; + } + + if (initialState) + { + m_RigidBody2D.rotation = m_TargetSyncRotation2D; + } + } + + void UnserializeModeCharacterController(NetworkReader reader, bool initialState) + { + if (hasAuthority) + { + // this component must read the data that the server wrote, even if it ignores it. + // otherwise the NetworkReader stream will still contain that data for the next component. + + // position + reader.ReadVector3(); + + if (syncRotationAxis != AxisSyncMode.None) + { + UnserializeRotation3D(reader, syncRotationAxis, rotationSyncCompression); + } + return; + } + + if (isServer && m_ClientMoveCallback3D != null) + { + var pos = reader.ReadVector3(); + Quaternion rot = Quaternion.identity; + if (syncRotationAxis != AxisSyncMode.None) + { + rot = UnserializeRotation3D(reader, syncRotationAxis, rotationSyncCompression); + } + + if (m_CharacterController == null) + return; + + // no velocity in packet, use current local velocity + var vel = m_CharacterController.velocity; + + if (m_ClientMoveCallback3D(ref pos, ref vel, ref rot)) + { + m_TargetSyncPosition = pos; + m_TargetSyncVelocity = vel; + if (syncRotationAxis != AxisSyncMode.None) + { + m_TargetSyncRotation3D = rot; + } + } + else + { + // rejected by callback + return; + } + } + else + { + // position + m_TargetSyncPosition = reader.ReadVector3(); + + // no velocity + + // rotation + if (syncRotationAxis != AxisSyncMode.None) + { + m_TargetSyncRotation3D = UnserializeRotation3D(reader, syncRotationAxis, rotationSyncCompression); + } + + // no spin + } + + if (m_CharacterController == null) + return; + + // total distance away the target position is + var totalDistToTarget = (m_TargetSyncPosition - transform.position); // 5 units + var perSecondDist = totalDistToTarget / GetNetworkSendInterval(); + m_FixedPosDiff = perSecondDist * Time.fixedDeltaTime; + + if (isServer && !isClient) + { + // dedicated server needs to apply immediately, there is no interpolation + transform.position = m_TargetSyncPosition; + transform.rotation = m_TargetSyncRotation3D; + return; + } + + // handle zero send rate + if (GetNetworkSendInterval() == 0) + { + transform.position = m_TargetSyncPosition; + //m_RigidBody3D.velocity = m_TargetSyncVelocity; + if (syncRotationAxis != AxisSyncMode.None) + { + transform.rotation = m_TargetSyncRotation3D; + } + return; + } + + // handle position snap threshold + float dist = (transform.position - m_TargetSyncPosition).magnitude; + if (dist > snapThreshold) + { + transform.position = m_TargetSyncPosition; + } + + // handle no rotation interpolation + if (interpolateRotation == 0 && syncRotationAxis != AxisSyncMode.None) + { + transform.rotation = m_TargetSyncRotation3D; + } + + // handle no movement interpolation + if (m_InterpolateMovement == 0) + { + transform.position = m_TargetSyncPosition; + } + + if (initialState && syncRotationAxis != AxisSyncMode.None) + { + transform.rotation = m_TargetSyncRotation3D; + } + } + + void FixedUpdate() + { + if (isServer) + { + FixedUpdateServer(); + } + if (isClient) + { + FixedUpdateClient(); + } + } + + void FixedUpdateServer() + { + if (syncVarDirtyBits != 0) + return; + + // dont run if network isn't active + if (!NetworkServer.active) + return; + + // dont run if we haven't been spawned yet + if (!isServer) + return; + + // dont' auto-dirty if no send interval + if (GetNetworkSendInterval() == 0) + return; + + float distance = (transform.position - m_PrevPosition).magnitude; + if (distance < movementTheshold) + { + distance = Quaternion.Angle(m_PrevRotation, transform.rotation); + if (distance < movementTheshold) + { + if (!CheckVelocityChanged()) + { + return; + } + } + } + + // This will cause transform to be sent + SetDirtyBit(1); + } + + bool CheckVelocityChanged() + { + switch (transformSyncMode) + { + case TransformSyncMode.SyncRigidbody2D: + if (m_RigidBody2D && m_VelocityThreshold > 0) + { + return Mathf.Abs(m_RigidBody2D.velocity.sqrMagnitude - m_PrevVelocity) >= m_VelocityThreshold; + } + else + { + return false; + } + + case TransformSyncMode.SyncRigidbody3D: + if (m_RigidBody3D && m_VelocityThreshold > 0) + { + return Mathf.Abs(m_RigidBody3D.velocity.sqrMagnitude - m_PrevVelocity) >= m_VelocityThreshold; + } + else + { + return false; + } + + default: + return false; + } + } + + void FixedUpdateClient() + { + // dont run if we haven't received any sync data + if (m_LastClientSyncTime == 0) + return; + + // dont run if network isn't active + if (!NetworkServer.active && !NetworkClient.active) + return; + + // dont run if we haven't been spawned yet + if (!isServer && !isClient) + return; + + // dont run if not expecting continuous updates + if (GetNetworkSendInterval() == 0) + return; + + // dont run this if this client has authority over this player object + if (hasAuthority) + return; + + // interpolate on client + switch (transformSyncMode) + { + case TransformSyncMode.SyncNone: + { + return; + } + case TransformSyncMode.SyncTransform: + { + return; + } + case TransformSyncMode.SyncRigidbody3D: + { + InterpolateTransformMode3D(); + break; + } + case TransformSyncMode.SyncRigidbody2D: + { + InterpolateTransformMode2D(); + break; + } + + case TransformSyncMode.SyncCharacterController: + { + InterpolateTransformModeCharacterController(); + break; + } + } + } + + void InterpolateTransformMode3D() + { + if (m_InterpolateMovement != 0) + { + Vector3 newVelocity = (m_TargetSyncPosition - m_RigidBody3D.position) * m_InterpolateMovement / GetNetworkSendInterval(); + m_RigidBody3D.velocity = newVelocity; + } + + if (interpolateRotation != 0) + { + m_RigidBody3D.MoveRotation(Quaternion.Slerp( + m_RigidBody3D.rotation, + m_TargetSyncRotation3D, + Time.fixedDeltaTime * interpolateRotation)); + + //m_TargetSyncRotation3D *= Quaternion.Euler(m_TargetSyncAngularVelocity3D * Time.fixedDeltaTime); + + // move sync rotation slightly in rotation direction + //m_TargetSyncRotation3D += (m_TargetSyncAngularVelocity3D * Time.fixedDeltaTime * moveAheadRatio); + } + + // move sync position slightly in the position of velocity + m_TargetSyncPosition += (m_TargetSyncVelocity * Time.fixedDeltaTime * k_MoveAheadRatio); + } + + void InterpolateTransformModeCharacterController() + { + if (m_FixedPosDiff == Vector3.zero && m_TargetSyncRotation3D == transform.rotation) + return; + + if (m_InterpolateMovement != 0) + { + m_CharacterController.Move(m_FixedPosDiff * m_InterpolateMovement); + } + + if (interpolateRotation != 0) + { + transform.rotation = Quaternion.Slerp( + transform.rotation, + m_TargetSyncRotation3D, + Time.fixedDeltaTime * interpolateRotation * 10); + } + if (Time.time - m_LastClientSyncTime > GetNetworkSendInterval()) + { + // turn off interpolation if we go out of the time window for a new packet + m_FixedPosDiff = Vector3.zero; + + var diff = m_TargetSyncPosition - transform.position; + m_CharacterController.Move(diff); + } + } + + void InterpolateTransformMode2D() + { + if (m_InterpolateMovement != 0) + { + Vector2 oldVelocity = m_RigidBody2D.velocity; + Vector2 newVelocity = (((Vector2)m_TargetSyncPosition - m_RigidBody2D.position)) * m_InterpolateMovement / GetNetworkSendInterval(); + if (!m_Grounded && newVelocity.y < 0) + { + newVelocity.y = oldVelocity.y; + } + m_RigidBody2D.velocity = newVelocity; + } + + if (interpolateRotation != 0) + { + float orientation = m_RigidBody2D.rotation % 360; + if (orientation < 0) + { + orientation += 360; + } + + Quaternion newRotation = Quaternion.Slerp( + transform.rotation, + Quaternion.Euler(0, 0, m_TargetSyncRotation2D), + Time.fixedDeltaTime * interpolateRotation / GetNetworkSendInterval()); + + m_RigidBody2D.MoveRotation(newRotation.eulerAngles.z); + + // move sync rotation slightly in rotation direction + m_TargetSyncRotation2D += (m_TargetSyncAngularVelocity2D * Time.fixedDeltaTime * k_MoveAheadRatio); + } + + // move sync position slightly in the position of velocity + m_TargetSyncPosition += (m_TargetSyncVelocity * Time.fixedDeltaTime * k_MoveAheadRatio); + } + + // --------------------- local transform sync ------------------------ + + void Update() + { + if (!hasAuthority) + return; + + if (!localPlayerAuthority) + return; + + if (NetworkServer.active) + return; + + if (Time.time - m_LastClientSendTime > GetNetworkSendInterval()) + { + SendTransform(); + m_LastClientSendTime = Time.time; + } + } + + bool HasMoved() + { + float diff = 0; + + // check if position has changed + if (m_RigidBody3D != null) + { + diff = (m_RigidBody3D.position - m_PrevPosition).magnitude; + } + else if (m_RigidBody2D != null) + { + diff = (m_RigidBody2D.position - (Vector2)m_PrevPosition).magnitude; + } + else + { + diff = (transform.position - m_PrevPosition).magnitude; + } + + if (diff > k_LocalMovementThreshold) + { + return true; + } + + // check if rotation has changed + if (m_RigidBody3D != null) + { + diff = Quaternion.Angle(m_RigidBody3D.rotation, m_PrevRotation); + } + else if (m_RigidBody2D != null) + { + diff = Math.Abs(m_RigidBody2D.rotation - m_PrevRotation2D); + } + else + { + diff = Quaternion.Angle(transform.rotation, m_PrevRotation); + } + if (diff > k_LocalRotationThreshold) + { + return true; + } + + // check if velocty has changed + if (m_RigidBody3D != null) + { + diff = Mathf.Abs(m_RigidBody3D.velocity.sqrMagnitude - m_PrevVelocity); + } + else if (m_RigidBody2D != null) + { + diff = Mathf.Abs(m_RigidBody2D.velocity.sqrMagnitude - m_PrevVelocity); + } + if (diff > k_LocalVelocityThreshold) + { + return true; + } + + + return false; + } + + [Client] + void SendTransform() + { + if (!HasMoved() || ClientScene.readyConnection == null) + { + return; + } + + m_LocalTransformWriter.StartMessage(MsgType.LocalPlayerTransform); + m_LocalTransformWriter.Write(netId); + + switch (transformSyncMode) + { + case TransformSyncMode.SyncNone: + { + return; + } + case TransformSyncMode.SyncTransform: + { + SerializeModeTransform(m_LocalTransformWriter); + break; + } + case TransformSyncMode.SyncRigidbody3D: + { + SerializeMode3D(m_LocalTransformWriter); + break; + } + case TransformSyncMode.SyncRigidbody2D: + { + SerializeMode2D(m_LocalTransformWriter); + break; + } + case TransformSyncMode.SyncCharacterController: + { + SerializeModeCharacterController(m_LocalTransformWriter); + break; + } + } + + if (m_RigidBody3D != null) + { + m_PrevPosition = m_RigidBody3D.position; + m_PrevRotation = m_RigidBody3D.rotation; + m_PrevVelocity = m_RigidBody3D.velocity.sqrMagnitude; + } + else if (m_RigidBody2D != null) + { + m_PrevPosition = m_RigidBody2D.position; + m_PrevRotation2D = m_RigidBody2D.rotation; + m_PrevVelocity = m_RigidBody2D.velocity.sqrMagnitude; + } + else + { + m_PrevPosition = transform.position; + m_PrevRotation = transform.rotation; + } + + m_LocalTransformWriter.FinishMessage(); + +#if UNITY_EDITOR + Profiler.IncrementStatOutgoing(MsgType.LocalPlayerTransform, "6:LocalPlayerTransform"); +#endif + ClientScene.readyConnection.SendWriter(m_LocalTransformWriter, GetNetworkChannel()); + } + + static public void HandleTransform(NetworkMessage netMsg) + { + NetworkInstanceId netId = netMsg.reader.ReadNetworkId(); + +#if UNITY_EDITOR + Profiler.IncrementStatIncoming(MsgType.LocalPlayerTransform, "6:LocalPlayerTransform"); +#endif + + GameObject foundObj = NetworkServer.FindLocalObject(netId); + if (foundObj == null) + { + if (LogFilter.logError) { Debug.LogError("Received NetworkTransform data for GameObject that doesn't exist"); } + return; + } + NetworkTransform foundSync = foundObj.GetComponent(); + if (foundSync == null) + { + if (LogFilter.logError) { Debug.LogError("HandleTransform null target"); } + return; + } + if (!foundSync.localPlayerAuthority) + { + if (LogFilter.logError) { Debug.LogError("HandleTransform no localPlayerAuthority"); } + return; + } + if (netMsg.conn.clientOwnedObjects == null) + { + if (LogFilter.logError) { Debug.LogError("HandleTransform object not owned by connection"); } + return; + } + + if (netMsg.conn.clientOwnedObjects.Contains(netId)) + { + switch (foundSync.transformSyncMode) + { + case TransformSyncMode.SyncNone: + { + return; + } + case TransformSyncMode.SyncTransform: + { + foundSync.UnserializeModeTransform(netMsg.reader, false); + break; + } + case TransformSyncMode.SyncRigidbody3D: + { + foundSync.UnserializeMode3D(netMsg.reader, false); + break; + } + case TransformSyncMode.SyncRigidbody2D: + { + foundSync.UnserializeMode2D(netMsg.reader, false); + break; + } + case TransformSyncMode.SyncCharacterController: + { + foundSync.UnserializeModeCharacterController(netMsg.reader, false); + break; + } + } + foundSync.m_LastClientSyncTime = Time.time; + return; + } + + if (LogFilter.logWarn) { Debug.LogWarning("HandleTransform netId:" + netId + " is not for a valid player"); } + } + + // --------------------- Compression Helper functions ------------------------ + + static void WriteAngle(NetworkWriter writer, float angle, CompressionSyncMode compression) + { + switch (compression) + { + case CompressionSyncMode.None: + { + writer.Write(angle); + break; + } + case CompressionSyncMode.Low: + { + writer.Write((short)angle); + break; + } + case CompressionSyncMode.High: + { + //TODO + writer.Write((short)angle); + break; + } + } + } + + static float ReadAngle(NetworkReader reader, CompressionSyncMode compression) + { + switch (compression) + { + case CompressionSyncMode.None: + { + return reader.ReadSingle(); + } + case CompressionSyncMode.Low: + { + return reader.ReadInt16(); + } + case CompressionSyncMode.High: + { + //TODO + return reader.ReadInt16(); + } + } + return 0; + } + + // --------------------- Serialization Helper functions ------------------------ + + static public void SerializeVelocity3D(NetworkWriter writer, Vector3 velocity, CompressionSyncMode compression) + { + writer.Write(velocity); + } + + static public void SerializeVelocity2D(NetworkWriter writer, Vector2 velocity, CompressionSyncMode compression) + { + writer.Write(velocity); + } + + static public void SerializeRotation3D(NetworkWriter writer, Quaternion rot, AxisSyncMode mode, CompressionSyncMode compression) + { + switch (mode) + { + case AxisSyncMode.None: + break; + + case AxisSyncMode.AxisX: + WriteAngle(writer, rot.eulerAngles.x, compression); + break; + + case AxisSyncMode.AxisY: + WriteAngle(writer, rot.eulerAngles.y, compression); + break; + + case AxisSyncMode.AxisZ: + WriteAngle(writer, rot.eulerAngles.z, compression); + break; + + case AxisSyncMode.AxisXY: + WriteAngle(writer, rot.eulerAngles.x, compression); + WriteAngle(writer, rot.eulerAngles.y, compression); + break; + + case AxisSyncMode.AxisXZ: + WriteAngle(writer, rot.eulerAngles.x, compression); + WriteAngle(writer, rot.eulerAngles.z, compression); + break; + + case AxisSyncMode.AxisYZ: + WriteAngle(writer, rot.eulerAngles.y, compression); + WriteAngle(writer, rot.eulerAngles.z, compression); + break; + + case AxisSyncMode.AxisXYZ: + WriteAngle(writer, rot.eulerAngles.x, compression); + WriteAngle(writer, rot.eulerAngles.y, compression); + WriteAngle(writer, rot.eulerAngles.z, compression); + break; + } + } + + static public void SerializeRotation2D(NetworkWriter writer, float rot, CompressionSyncMode compression) + { + WriteAngle(writer, rot, compression); + } + + static public void SerializeSpin3D(NetworkWriter writer, Vector3 angularVelocity, AxisSyncMode mode, CompressionSyncMode compression) + { + switch (mode) + { + case AxisSyncMode.None: + break; + + case AxisSyncMode.AxisX: + WriteAngle(writer, angularVelocity.x, compression); + break; + + case AxisSyncMode.AxisY: + WriteAngle(writer, angularVelocity.y, compression); + break; + + case AxisSyncMode.AxisZ: + WriteAngle(writer, angularVelocity.z, compression); + break; + + case AxisSyncMode.AxisXY: + WriteAngle(writer, angularVelocity.x, compression); + WriteAngle(writer, angularVelocity.y, compression); + break; + + case AxisSyncMode.AxisXZ: + WriteAngle(writer, angularVelocity.x, compression); + WriteAngle(writer, angularVelocity.z, compression); + break; + + case AxisSyncMode.AxisYZ: + WriteAngle(writer, angularVelocity.y, compression); + WriteAngle(writer, angularVelocity.z, compression); + break; + + case AxisSyncMode.AxisXYZ: + WriteAngle(writer, angularVelocity.x, compression); + WriteAngle(writer, angularVelocity.y, compression); + WriteAngle(writer, angularVelocity.z, compression); + break; + } + } + + static public void SerializeSpin2D(NetworkWriter writer, float angularVelocity, CompressionSyncMode compression) + { + WriteAngle(writer, angularVelocity, compression); + } + + static public Vector3 UnserializeVelocity3D(NetworkReader reader, CompressionSyncMode compression) + { + return reader.ReadVector3(); + } + + static public Vector3 UnserializeVelocity2D(NetworkReader reader, CompressionSyncMode compression) + { + return reader.ReadVector2(); + } + + static public Quaternion UnserializeRotation3D(NetworkReader reader, AxisSyncMode mode, CompressionSyncMode compression) + { + Quaternion rotation = Quaternion.identity; + Vector3 rotv = Vector3.zero; + + switch (mode) + { + case AxisSyncMode.None: + break; + + case AxisSyncMode.AxisX: + rotv.Set(ReadAngle(reader, compression), 0, 0); + rotation.eulerAngles = rotv; + break; + + case AxisSyncMode.AxisY: + rotv.Set(0, ReadAngle(reader, compression), 0); + rotation.eulerAngles = rotv; + break; + + case AxisSyncMode.AxisZ: + rotv.Set(0, 0, ReadAngle(reader, compression)); + rotation.eulerAngles = rotv; + break; + + case AxisSyncMode.AxisXY: + rotv.Set(ReadAngle(reader, compression), ReadAngle(reader, compression), 0); + rotation.eulerAngles = rotv; + break; + + case AxisSyncMode.AxisXZ: + rotv.Set(ReadAngle(reader, compression), 0, ReadAngle(reader, compression)); + rotation.eulerAngles = rotv; + break; + + case AxisSyncMode.AxisYZ: + rotv.Set(0, ReadAngle(reader, compression), ReadAngle(reader, compression)); + rotation.eulerAngles = rotv; + break; + + case AxisSyncMode.AxisXYZ: + rotv.Set(ReadAngle(reader, compression), ReadAngle(reader, compression), ReadAngle(reader, compression)); + rotation.eulerAngles = rotv; + break; + } + return rotation; + } + + static public float UnserializeRotation2D(NetworkReader reader, CompressionSyncMode compression) + { + return ReadAngle(reader, compression); + } + + static public Vector3 UnserializeSpin3D(NetworkReader reader, AxisSyncMode mode, CompressionSyncMode compression) + { + Vector3 spin = Vector3.zero; + switch (mode) + { + case AxisSyncMode.None: + break; + + case AxisSyncMode.AxisX: + spin.Set(ReadAngle(reader, compression), 0, 0); + break; + + case AxisSyncMode.AxisY: + spin.Set(0, ReadAngle(reader, compression), 0); + break; + + case AxisSyncMode.AxisZ: + spin.Set(0, 0, ReadAngle(reader, compression)); + break; + + case AxisSyncMode.AxisXY: + spin.Set(ReadAngle(reader, compression), ReadAngle(reader, compression), 0); + break; + + case AxisSyncMode.AxisXZ: + spin.Set(ReadAngle(reader, compression), 0, ReadAngle(reader, compression)); + break; + + case AxisSyncMode.AxisYZ: + spin.Set(0, ReadAngle(reader, compression), ReadAngle(reader, compression)); + break; + + case AxisSyncMode.AxisXYZ: + spin.Set(ReadAngle(reader, compression), ReadAngle(reader, compression), ReadAngle(reader, compression)); + break; + } + return spin; + } + + static public float UnserializeSpin2D(NetworkReader reader, CompressionSyncMode compression) + { + return ReadAngle(reader, compression); + } + + public override int GetNetworkChannel() + { + return Channels.DefaultUnreliable; + } + + public override float GetNetworkSendInterval() + { + return m_SendInterval; + } + + public override void OnStartAuthority() + { + // must reset this timer, or the server will continue to send target position instead of current position + m_LastClientSyncTime = 0; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkTransformVisualizer.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkTransformVisualizer.cs new file mode 100644 index 00000000..684b3b9c --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkTransformVisualizer.cs @@ -0,0 +1,173 @@ +using System; +using System.ComponentModel; +using UnityEngine; + +namespace UnityEngine.Networking +{ + /// + /// This is a helper component to help understand and debug networked movement synchronization with the NetworkTransform component. + /// + [DisallowMultipleComponent] + [AddComponentMenu("Network/NetworkTransformVisualizer")] + [RequireComponent(typeof(NetworkTransform))] + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class NetworkTransformVisualizer : NetworkBehaviour + { + [Tooltip("The prefab to use for the visualization object.")] + [SerializeField] GameObject m_VisualizerPrefab; + + NetworkTransform m_NetworkTransform; + GameObject m_Visualizer; + + /// + /// The prefab to use for the visualization object. + /// + public GameObject visualizerPrefab { get { return m_VisualizerPrefab; } set { m_VisualizerPrefab = value; }} + + public override void OnStartClient() + { + if (m_VisualizerPrefab != null) + { + m_NetworkTransform = GetComponent(); + CreateLineMaterial(); + m_Visualizer = (GameObject)Instantiate(m_VisualizerPrefab, transform.position, Quaternion.identity); + } + } + + public override void OnStartLocalPlayer() + { + if (m_Visualizer == null) + return; + + if (m_NetworkTransform.localPlayerAuthority || isServer) + { + Destroy(m_Visualizer); + } + } + + void OnDestroy() + { + if (m_Visualizer != null) + { + Destroy(m_Visualizer); + } + } + + [ClientCallback] + void FixedUpdate() + { + if (m_Visualizer == null) + return; + + // dont run if network isn't active + if (!NetworkServer.active && !NetworkClient.active) + return; + + // dont run if we haven't been spawned yet + if (!isServer && !isClient) + return; + + // dont run this if this client has authority over this player object + if (hasAuthority && m_NetworkTransform.localPlayerAuthority) + return; + + m_Visualizer.transform.position = m_NetworkTransform.targetSyncPosition; + + if (m_NetworkTransform.rigidbody3D != null && m_Visualizer.GetComponent() != null) + { + m_Visualizer.GetComponent().velocity = m_NetworkTransform.targetSyncVelocity; + } + if (m_NetworkTransform.rigidbody2D != null && m_Visualizer.GetComponent() != null) + { + m_Visualizer.GetComponent().velocity = m_NetworkTransform.targetSyncVelocity; + } + + Quaternion targetFacing = Quaternion.identity; + if (m_NetworkTransform.rigidbody3D != null) + { + targetFacing = m_NetworkTransform.targetSyncRotation3D; + } + if (m_NetworkTransform.rigidbody2D != null) + { + targetFacing = Quaternion.Euler(0, 0, m_NetworkTransform.targetSyncRotation2D); + } + m_Visualizer.transform.rotation = targetFacing; + } + + // --------------------- local transform sync ------------------------ + + void OnRenderObject() + { + if (m_Visualizer == null) + return; + + if (m_NetworkTransform.localPlayerAuthority && hasAuthority) + return; + + if (m_NetworkTransform.lastSyncTime == 0) + return; + + s_LineMaterial.SetPass(0); + GL.Begin(GL.LINES); + GL.Color(Color.white); + GL.Vertex3(transform.position.x, transform.position.y, transform.position.z); + GL.Vertex3(m_NetworkTransform.targetSyncPosition.x, m_NetworkTransform.targetSyncPosition.y, m_NetworkTransform.targetSyncPosition.z); + GL.End(); + + DrawRotationInterpolation(); + } + + void DrawRotationInterpolation() + { + Quaternion targetFacing = Quaternion.identity; + if (m_NetworkTransform.rigidbody3D != null) + { + targetFacing = m_NetworkTransform.targetSyncRotation3D; + } + if (m_NetworkTransform.rigidbody2D != null) + { + targetFacing = Quaternion.Euler(0, 0, m_NetworkTransform.targetSyncRotation2D); + } + if (targetFacing == Quaternion.identity) + return; + + // draw line for actual facing + GL.Begin(GL.LINES); + GL.Color(Color.yellow); + GL.Vertex3(transform.position.x, transform.position.y, transform.position.z); + + Vector3 actualFront = transform.position + transform.right; + GL.Vertex3(actualFront.x, actualFront.y, actualFront.z); + GL.End(); + + // draw line for target (server) facing + GL.Begin(GL.LINES); + GL.Color(Color.green); + + GL.Vertex3(transform.position.x, transform.position.y, transform.position.z); + + Vector3 targetPositionOffset = (targetFacing * Vector3.right); + Vector3 targetFront = transform.position + targetPositionOffset; + GL.Vertex3(targetFront.x, targetFront.y, targetFront.z); + GL.End(); + } + + static Material s_LineMaterial; + + static void CreateLineMaterial() + { + if (s_LineMaterial) + return; + var shader = Shader.Find("Hidden/Internal-Colored"); + if (!shader) + { + Debug.LogWarning("Could not find Colored builtin shader"); + return; + } + s_LineMaterial = new Material(shader); + s_LineMaterial.hideFlags = HideFlags.HideAndDontSave; + s_LineMaterial.SetInt("_ZWrite", 0); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkWriter.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkWriter.cs new file mode 100644 index 00000000..4cdc86f2 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/NetworkWriter.cs @@ -0,0 +1,1385 @@ +using System; +using System.Text; +using UnityEngine; + +namespace UnityEngine.Networking +{ + /* + // Binary stream Writer. Supports simple types, buffers, arrays, structs, and nested types + */ + /// + /// General purpose serializer for UNET (for serializing data to byte arrays). + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class ExampleScript : MonoBehaviour + /// { + /// // Writing data to a NetworkWriter and then + /// // Converting this to a NetworkReader. + /// void Start() + /// { + /// // The data you add to your writer must be prefixed with a message type. + /// // This is in the form of a short. + /// short myMsgType = 143; + /// NetworkWriter writer = new NetworkWriter(); + /// // You start the message in your writer by passing in the message type. + /// // This is a short meaning that it will take up 2 bytes at the start of + /// // your message. + /// writer.StartMessage(myMsgType); + /// // You can now begin your message. In this case we will just use strings. + /// writer.Write("Test data 1"); + /// writer.Write("Test data 2"); + /// writer.Write("Test data 3"); + /// // Make sure to end your message with FinishMessage() + /// writer.FinishMessage(); + /// // You can now access the data in your writer. ToArray() returns a copy + /// // of the bytes that the writer is using and AsArray() returns the + /// // internal array of bytes, not a copy. + /// byte[] writerData = writer.ToArray(); + /// CreateNetworkReader(writerData); + /// } + /// + /// void CreateNetworkReader(byte[] data) + /// { + /// // We will create the NetworkReader using the data from our previous + /// // NetworkWriter. + /// NetworkReader networkReader = new NetworkReader(data); + /// // The first two bytes in the buffer represent the size + /// // of the message. This is equal to the NetworkReader.Length + /// // minus the size of the prefix. + /// byte[] readerMsgSizeData = networkReader.ReadBytes(2); + /// short readerMsgSize = (short)((readerMsgSizeData[1] << 8) + readerMsgSizeData[0]); + /// Debug.Log(readerMsgSize); + /// // The message type added in NetworkWriter.StartMessage + /// // is to be read now. It is a short and so consists of + /// // two bytes. It is the second two bytes on the buffer. + /// byte[] readerMsgTypeData = networkReader.ReadBytes(2); + /// short readerMsgType = (short)((readerMsgTypeData[1] << 8) + readerMsgTypeData[0]); + /// Debug.Log(readerMsgType); + /// // If all of your data is of the same type (in this case the + /// // data on our buffer is comprised of only strings) you can + /// // read all the data from the buffer using a loop like so. + /// while (networkReader.Position < networkReader.Length) + /// { + /// Debug.Log(networkReader.ReadString()); + /// } + /// } + /// } + /// + /// + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class NetworkWriter + { + const int k_MaxStringLength = 1024 * 32; + NetBuffer m_Buffer; + static Encoding s_Encoding; + static byte[] s_StringWriteBuffer; + + /// + /// Creates a new NetworkWriter object. + /// + public NetworkWriter() + { + m_Buffer = new NetBuffer(); + if (s_Encoding == null) + { + s_Encoding = new UTF8Encoding(); + s_StringWriteBuffer = new byte[k_MaxStringLength]; + } + } + + /// + /// Creates a new NetworkWriter object. + /// + /// A buffer to write into. This is not copied. + public NetworkWriter(byte[] buffer) + { + m_Buffer = new NetBuffer(buffer); + if (s_Encoding == null) + { + s_Encoding = new UTF8Encoding(); + s_StringWriteBuffer = new byte[k_MaxStringLength]; + } + } + + /// + /// The current position of the internal buffer. + /// See NetworkWriter for a code example. + /// + public short Position { get { return (short)m_Buffer.Position; } } + + /// + /// Returns a copy of internal array of bytes the writer is using, it copies only the bytes used. + /// See NetworkWriter for a code example. + /// + /// Copy of data used by the writer. + public byte[] ToArray() + { + var newArray = new byte[m_Buffer.AsArraySegment().Count]; + Array.Copy(m_Buffer.AsArraySegment().Array, newArray, m_Buffer.AsArraySegment().Count); + return newArray; + } + + /// + /// Returns the internal array of bytes the writer is using. This is NOT a copy. + /// + /// Internal buffer + public byte[] AsArray() + { + return AsArraySegment().Array; + } + + internal ArraySegment AsArraySegment() + { + return m_Buffer.AsArraySegment(); + } + + // http://sqlite.org/src4/doc/trunk/www/varint.wiki + /// + /// This writes the 32-bit value to the stream using variable-length-encoding. + /// + /// Value to write. + public void WritePackedUInt32(UInt32 value) + { + if (value <= 240) + { + Write((byte)value); + return; + } + if (value <= 2287) + { + Write((byte)((value - 240) / 256 + 241)); + Write((byte)((value - 240) % 256)); + return; + } + if (value <= 67823) + { + Write((byte)249); + Write((byte)((value - 2288) / 256)); + Write((byte)((value - 2288) % 256)); + return; + } + if (value <= 16777215) + { + Write((byte)250); + Write((byte)(value & 0xFF)); + Write((byte)((value >> 8) & 0xFF)); + Write((byte)((value >> 16) & 0xFF)); + return; + } + + // all other values of uint + Write((byte)251); + Write((byte)(value & 0xFF)); + Write((byte)((value >> 8) & 0xFF)); + Write((byte)((value >> 16) & 0xFF)); + Write((byte)((value >> 24) & 0xFF)); + } + + /// + /// This writes the 64-bit value to the stream using variable-length-encoding. + /// + /// Value to write. + public void WritePackedUInt64(UInt64 value) + { + if (value <= 240) + { + Write((byte)value); + return; + } + if (value <= 2287) + { + Write((byte)((value - 240) / 256 + 241)); + Write((byte)((value - 240) % 256)); + return; + } + if (value <= 67823) + { + Write((byte)249); + Write((byte)((value - 2288) / 256)); + Write((byte)((value - 2288) % 256)); + return; + } + if (value <= 16777215) + { + Write((byte)250); + Write((byte)(value & 0xFF)); + Write((byte)((value >> 8) & 0xFF)); + Write((byte)((value >> 16) & 0xFF)); + return; + } + if (value <= 4294967295) + { + Write((byte)251); + Write((byte)(value & 0xFF)); + Write((byte)((value >> 8) & 0xFF)); + Write((byte)((value >> 16) & 0xFF)); + Write((byte)((value >> 24) & 0xFF)); + return; + } + if (value <= 1099511627775) + { + Write((byte)252); + Write((byte)(value & 0xFF)); + Write((byte)((value >> 8) & 0xFF)); + Write((byte)((value >> 16) & 0xFF)); + Write((byte)((value >> 24) & 0xFF)); + Write((byte)((value >> 32) & 0xFF)); + return; + } + if (value <= 281474976710655) + { + Write((byte)253); + Write((byte)(value & 0xFF)); + Write((byte)((value >> 8) & 0xFF)); + Write((byte)((value >> 16) & 0xFF)); + Write((byte)((value >> 24) & 0xFF)); + Write((byte)((value >> 32) & 0xFF)); + Write((byte)((value >> 40) & 0xFF)); + return; + } + if (value <= 72057594037927935) + { + Write((byte)254); + Write((byte)(value & 0xFF)); + Write((byte)((value >> 8) & 0xFF)); + Write((byte)((value >> 16) & 0xFF)); + Write((byte)((value >> 24) & 0xFF)); + Write((byte)((value >> 32) & 0xFF)); + Write((byte)((value >> 40) & 0xFF)); + Write((byte)((value >> 48) & 0xFF)); + return; + } + + // all others + { + Write((byte)255); + Write((byte)(value & 0xFF)); + Write((byte)((value >> 8) & 0xFF)); + Write((byte)((value >> 16) & 0xFF)); + Write((byte)((value >> 24) & 0xFF)); + Write((byte)((value >> 32) & 0xFF)); + Write((byte)((value >> 40) & 0xFF)); + Write((byte)((value >> 48) & 0xFF)); + Write((byte)((value >> 56) & 0xFF)); + } + } + + /// + /// This writes a reference to an object, value, buffer or network message, together with a NetworkIdentity component to the stream. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class ExampleScript : MonoBehaviour + /// { + /// void Start() + /// { + /// short myMsgType = 444; + /// NetworkWriter writer = new NetworkWriter(); + /// writer.StartMessage(myMsgType); + /// writer.Write("test data"); + /// writer.FinishMessage(); + /// } + /// } + /// + /// See NetworkWriter for another code example. + /// + /// The object to write. + public void Write(NetworkInstanceId value) + { + WritePackedUInt32(value.Value); + } + + /// + /// This writes a reference to an object, value, buffer or network message, together with a NetworkIdentity component to the stream. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class ExampleScript : MonoBehaviour + /// { + /// void Start() + /// { + /// short myMsgType = 444; + /// NetworkWriter writer = new NetworkWriter(); + /// writer.StartMessage(myMsgType); + /// writer.Write("test data"); + /// writer.FinishMessage(); + /// } + /// } + /// + /// See NetworkWriter for another code example. + /// + /// The object to write. + public void Write(NetworkSceneId value) + { + WritePackedUInt32(value.Value); + } + + /// + /// This writes a reference to an object, value, buffer or network message, together with a NetworkIdentity component to the stream. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class ExampleScript : MonoBehaviour + /// { + /// void Start() + /// { + /// short myMsgType = 444; + /// NetworkWriter writer = new NetworkWriter(); + /// writer.StartMessage(myMsgType); + /// writer.Write("test data"); + /// writer.FinishMessage(); + /// } + /// } + /// + /// See NetworkWriter for another code example. + /// + /// The object to write. + public void Write(char value) + { + m_Buffer.WriteByte((byte)value); + } + + /// + /// This writes a reference to an object, value, buffer or network message, together with a NetworkIdentity component to the stream. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class ExampleScript : MonoBehaviour + /// { + /// void Start() + /// { + /// short myMsgType = 444; + /// NetworkWriter writer = new NetworkWriter(); + /// writer.StartMessage(myMsgType); + /// writer.Write("test data"); + /// writer.FinishMessage(); + /// } + /// } + /// + /// See NetworkWriter for another code example. + /// + /// The object to write. + public void Write(byte value) + { + m_Buffer.WriteByte(value); + } + + /// + /// This writes a reference to an object, value, buffer or network message, together with a NetworkIdentity component to the stream. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class ExampleScript : MonoBehaviour + /// { + /// void Start() + /// { + /// short myMsgType = 444; + /// NetworkWriter writer = new NetworkWriter(); + /// writer.StartMessage(myMsgType); + /// writer.Write("test data"); + /// writer.FinishMessage(); + /// } + /// } + /// + /// See NetworkWriter for another code example. + /// + /// The object to write. + public void Write(sbyte value) + { + m_Buffer.WriteByte((byte)value); + } + + /// + /// This writes a reference to an object, value, buffer or network message, together with a NetworkIdentity component to the stream. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class ExampleScript : MonoBehaviour + /// { + /// void Start() + /// { + /// short myMsgType = 444; + /// NetworkWriter writer = new NetworkWriter(); + /// writer.StartMessage(myMsgType); + /// writer.Write("test data"); + /// writer.FinishMessage(); + /// } + /// } + /// + /// See NetworkWriter for another code example. + /// + /// The object to write. + public void Write(short value) + { + m_Buffer.WriteByte2((byte)(value & 0xff), (byte)((value >> 8) & 0xff)); + } + + /// + /// This writes a reference to an object, value, buffer or network message, together with a NetworkIdentity component to the stream. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class ExampleScript : MonoBehaviour + /// { + /// void Start() + /// { + /// short myMsgType = 444; + /// NetworkWriter writer = new NetworkWriter(); + /// writer.StartMessage(myMsgType); + /// writer.Write("test data"); + /// writer.FinishMessage(); + /// } + /// } + /// + /// See NetworkWriter for another code example. + /// + /// The object to write. + public void Write(ushort value) + { + m_Buffer.WriteByte2((byte)(value & 0xff), (byte)((value >> 8) & 0xff)); + } + + /// + /// This writes a reference to an object, value, buffer or network message, together with a NetworkIdentity component to the stream. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class ExampleScript : MonoBehaviour + /// { + /// void Start() + /// { + /// short myMsgType = 444; + /// NetworkWriter writer = new NetworkWriter(); + /// writer.StartMessage(myMsgType); + /// writer.Write("test data"); + /// writer.FinishMessage(); + /// } + /// } + /// + /// See NetworkWriter for another code example. + /// + /// The object to write. + public void Write(int value) + { + // little endian... + m_Buffer.WriteByte4( + (byte)(value & 0xff), + (byte)((value >> 8) & 0xff), + (byte)((value >> 16) & 0xff), + (byte)((value >> 24) & 0xff)); + } + + /// + /// This writes a reference to an object, value, buffer or network message, together with a NetworkIdentity component to the stream. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class ExampleScript : MonoBehaviour + /// { + /// void Start() + /// { + /// short myMsgType = 444; + /// NetworkWriter writer = new NetworkWriter(); + /// writer.StartMessage(myMsgType); + /// writer.Write("test data"); + /// writer.FinishMessage(); + /// } + /// } + /// + /// See NetworkWriter for another code example. + /// + /// The object to write. + public void Write(uint value) + { + m_Buffer.WriteByte4( + (byte)(value & 0xff), + (byte)((value >> 8) & 0xff), + (byte)((value >> 16) & 0xff), + (byte)((value >> 24) & 0xff)); + } + + /// + /// This writes a reference to an object, value, buffer or network message, together with a NetworkIdentity component to the stream. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class ExampleScript : MonoBehaviour + /// { + /// void Start() + /// { + /// short myMsgType = 444; + /// NetworkWriter writer = new NetworkWriter(); + /// writer.StartMessage(myMsgType); + /// writer.Write("test data"); + /// writer.FinishMessage(); + /// } + /// } + /// + /// See NetworkWriter for another code example. + /// + /// The object to write. + public void Write(long value) + { + m_Buffer.WriteByte8( + (byte)(value & 0xff), + (byte)((value >> 8) & 0xff), + (byte)((value >> 16) & 0xff), + (byte)((value >> 24) & 0xff), + (byte)((value >> 32) & 0xff), + (byte)((value >> 40) & 0xff), + (byte)((value >> 48) & 0xff), + (byte)((value >> 56) & 0xff)); + } + + /// + /// This writes a reference to an object, value, buffer or network message, together with a NetworkIdentity component to the stream. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class ExampleScript : MonoBehaviour + /// { + /// void Start() + /// { + /// short myMsgType = 444; + /// NetworkWriter writer = new NetworkWriter(); + /// writer.StartMessage(myMsgType); + /// writer.Write("test data"); + /// writer.FinishMessage(); + /// } + /// } + /// + /// See NetworkWriter for another code example. + /// + /// The object to write. + public void Write(ulong value) + { + m_Buffer.WriteByte8( + (byte)(value & 0xff), + (byte)((value >> 8) & 0xff), + (byte)((value >> 16) & 0xff), + (byte)((value >> 24) & 0xff), + (byte)((value >> 32) & 0xff), + (byte)((value >> 40) & 0xff), + (byte)((value >> 48) & 0xff), + (byte)((value >> 56) & 0xff)); + } + + static UIntFloat s_FloatConverter; + + /// + /// This writes a reference to an object, value, buffer or network message, together with a NetworkIdentity component to the stream. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class ExampleScript : MonoBehaviour + /// { + /// void Start() + /// { + /// short myMsgType = 444; + /// NetworkWriter writer = new NetworkWriter(); + /// writer.StartMessage(myMsgType); + /// writer.Write("test data"); + /// writer.FinishMessage(); + /// } + /// } + /// + /// See NetworkWriter for another code example. + /// + /// The object to write. + public void Write(float value) + { + s_FloatConverter.floatValue = value; + Write(s_FloatConverter.intValue); + } + + /// + /// This writes a reference to an object, value, buffer or network message, together with a NetworkIdentity component to the stream. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class ExampleScript : MonoBehaviour + /// { + /// void Start() + /// { + /// short myMsgType = 444; + /// NetworkWriter writer = new NetworkWriter(); + /// writer.StartMessage(myMsgType); + /// writer.Write("test data"); + /// writer.FinishMessage(); + /// } + /// } + /// + /// See NetworkWriter for another code example. + /// + /// The object to write. + public void Write(double value) + { + s_FloatConverter.doubleValue = value; + Write(s_FloatConverter.longValue); + } + + /// + /// This writes a reference to an object, value, buffer or network message, together with a NetworkIdentity component to the stream. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class ExampleScript : MonoBehaviour + /// { + /// void Start() + /// { + /// short myMsgType = 444; + /// NetworkWriter writer = new NetworkWriter(); + /// writer.StartMessage(myMsgType); + /// writer.Write("test data"); + /// writer.FinishMessage(); + /// } + /// } + /// + /// See NetworkWriter for another code example. + /// + /// The object to write. + public void Write(decimal value) + { + Int32[] bits = decimal.GetBits(value); + Write(bits[0]); + Write(bits[1]); + Write(bits[2]); + Write(bits[3]); + } + + /// + /// This writes a reference to an object, value, buffer or network message, together with a NetworkIdentity component to the stream. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class ExampleScript : MonoBehaviour + /// { + /// void Start() + /// { + /// short myMsgType = 444; + /// NetworkWriter writer = new NetworkWriter(); + /// writer.StartMessage(myMsgType); + /// writer.Write("test data"); + /// writer.FinishMessage(); + /// } + /// } + /// + /// See NetworkWriter for another code example. + /// + /// The object to write. + public void Write(string value) + { + if (value == null) + { + m_Buffer.WriteByte2(0, 0); + return; + } + + int len = s_Encoding.GetByteCount(value); + + if (len >= k_MaxStringLength) + { + throw new IndexOutOfRangeException("Serialize(string) too long: " + value.Length); + } + + Write((ushort)(len)); + int numBytes = s_Encoding.GetBytes(value, 0, value.Length, s_StringWriteBuffer, 0); + m_Buffer.WriteBytes(s_StringWriteBuffer, (ushort)numBytes); + } + + /// + /// This writes a reference to an object, value, buffer or network message, together with a NetworkIdentity component to the stream. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class ExampleScript : MonoBehaviour + /// { + /// void Start() + /// { + /// short myMsgType = 444; + /// NetworkWriter writer = new NetworkWriter(); + /// writer.StartMessage(myMsgType); + /// writer.Write("test data"); + /// writer.FinishMessage(); + /// } + /// } + /// + /// See NetworkWriter for another code example. + /// + /// The object to write. + public void Write(bool value) + { + if (value) + m_Buffer.WriteByte(1); + else + m_Buffer.WriteByte(0); + } + + /// + /// This writes a reference to an object, value, buffer or network message, together with a NetworkIdentity component to the stream. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class ExampleScript : MonoBehaviour + /// { + /// void Start() + /// { + /// short myMsgType = 444; + /// NetworkWriter writer = new NetworkWriter(); + /// writer.StartMessage(myMsgType); + /// writer.Write("test data"); + /// writer.FinishMessage(); + /// } + /// } + /// + /// See NetworkWriter for another code example. + /// + /// The byte buffer to write. + /// The number of bytes in the byte buffer to write. + public void Write(byte[] buffer, int count) + { + if (count > UInt16.MaxValue) + { + if (LogFilter.logError) { Debug.LogError("NetworkWriter Write: buffer is too large (" + count + ") bytes. The maximum buffer size is 64K bytes."); } + return; + } + m_Buffer.WriteBytes(buffer, (UInt16)count); + } + + /// + /// This writes a reference to an object, value, buffer or network message, together with a NetworkIdentity component to the stream. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class ExampleScript : MonoBehaviour + /// { + /// void Start() + /// { + /// short myMsgType = 444; + /// NetworkWriter writer = new NetworkWriter(); + /// writer.StartMessage(myMsgType); + /// writer.Write("test data"); + /// writer.FinishMessage(); + /// } + /// } + /// + /// See NetworkWriter for another code example. + /// + /// The byte buffer to write. + /// The byte buffer array element to start writing from. + /// The number of bytes in the byte buffer to write. + public void Write(byte[] buffer, int offset, int count) + { + if (count > UInt16.MaxValue) + { + if (LogFilter.logError) { Debug.LogError("NetworkWriter Write: buffer is too large (" + count + ") bytes. The maximum buffer size is 64K bytes."); } + return; + } + m_Buffer.WriteBytesAtOffset(buffer, (ushort)offset, (ushort)count); + } + + /// + /// This writes a 16-bit count and an array of bytes of that length to the stream. + /// + /// Array of bytes to write. + /// Number of bytes from the array to write. + public void WriteBytesAndSize(byte[] buffer, int count) + { + if (buffer == null || count == 0) + { + Write((UInt16)0); + return; + } + + if (count > UInt16.MaxValue) + { + if (LogFilter.logError) { Debug.LogError("NetworkWriter WriteBytesAndSize: buffer is too large (" + count + ") bytes. The maximum buffer size is 64K bytes."); } + return; + } + + Write((UInt16)count); + m_Buffer.WriteBytes(buffer, (UInt16)count); + } + + /// + /// This writes a 16-bit count and an array of bytes of that size to the stream. + /// Note that this will be the full allocated size of the array. So if the array is partially filled with data to send - then you should be using WriteBytesAndSize instead. + /// + /// Bytes to write. + //NOTE: this will write the entire buffer.. including trailing empty space! + public void WriteBytesFull(byte[] buffer) + { + if (buffer == null) + { + Write((UInt16)0); + return; + } + if (buffer.Length > UInt16.MaxValue) + { + if (LogFilter.logError) { Debug.LogError("NetworkWriter WriteBytes: buffer is too large (" + buffer.Length + ") bytes. The maximum buffer size is 64K bytes."); } + return; + } + Write((UInt16)buffer.Length); + m_Buffer.WriteBytes(buffer, (UInt16)buffer.Length); + } + + /// + /// This writes a reference to an object, value, buffer or network message, together with a NetworkIdentity component to the stream. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class ExampleScript : MonoBehaviour + /// { + /// void Start() + /// { + /// short myMsgType = 444; + /// NetworkWriter writer = new NetworkWriter(); + /// writer.StartMessage(myMsgType); + /// writer.Write("test data"); + /// writer.FinishMessage(); + /// } + /// } + /// + /// See NetworkWriter for another code example. + /// + /// The object to write. + public void Write(Vector2 value) + { + Write(value.x); + Write(value.y); + } + + /// + /// This writes a reference to an object, value, buffer or network message, together with a NetworkIdentity component to the stream. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class ExampleScript : MonoBehaviour + /// { + /// void Start() + /// { + /// short myMsgType = 444; + /// NetworkWriter writer = new NetworkWriter(); + /// writer.StartMessage(myMsgType); + /// writer.Write("test data"); + /// writer.FinishMessage(); + /// } + /// } + /// + /// See NetworkWriter for another code example. + /// + /// The object to write. + public void Write(Vector3 value) + { + Write(value.x); + Write(value.y); + Write(value.z); + } + + /// + /// This writes a reference to an object, value, buffer or network message, together with a NetworkIdentity component to the stream. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class ExampleScript : MonoBehaviour + /// { + /// void Start() + /// { + /// short myMsgType = 444; + /// NetworkWriter writer = new NetworkWriter(); + /// writer.StartMessage(myMsgType); + /// writer.Write("test data"); + /// writer.FinishMessage(); + /// } + /// } + /// + /// See NetworkWriter for another code example. + /// + /// The object to write. + public void Write(Vector4 value) + { + Write(value.x); + Write(value.y); + Write(value.z); + Write(value.w); + } + + /// + /// This writes a reference to an object, value, buffer or network message, together with a NetworkIdentity component to the stream. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class ExampleScript : MonoBehaviour + /// { + /// void Start() + /// { + /// short myMsgType = 444; + /// NetworkWriter writer = new NetworkWriter(); + /// writer.StartMessage(myMsgType); + /// writer.Write("test data"); + /// writer.FinishMessage(); + /// } + /// } + /// + /// See NetworkWriter for another code example. + /// + /// The object to write. + public void Write(Color value) + { + Write(value.r); + Write(value.g); + Write(value.b); + Write(value.a); + } + + /// + /// This writes a reference to an object, value, buffer or network message, together with a NetworkIdentity component to the stream. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class ExampleScript : MonoBehaviour + /// { + /// void Start() + /// { + /// short myMsgType = 444; + /// NetworkWriter writer = new NetworkWriter(); + /// writer.StartMessage(myMsgType); + /// writer.Write("test data"); + /// writer.FinishMessage(); + /// } + /// } + /// + /// See NetworkWriter for another code example. + /// + /// The object to write. + public void Write(Color32 value) + { + Write(value.r); + Write(value.g); + Write(value.b); + Write(value.a); + } + + /// + /// This writes a reference to an object, value, buffer or network message, together with a NetworkIdentity component to the stream. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class ExampleScript : MonoBehaviour + /// { + /// void Start() + /// { + /// short myMsgType = 444; + /// NetworkWriter writer = new NetworkWriter(); + /// writer.StartMessage(myMsgType); + /// writer.Write("test data"); + /// writer.FinishMessage(); + /// } + /// } + /// + /// See NetworkWriter for another code example. + /// + /// The object to write. + public void Write(Quaternion value) + { + Write(value.x); + Write(value.y); + Write(value.z); + Write(value.w); + } + + /// + /// This writes a reference to an object, value, buffer or network message, together with a NetworkIdentity component to the stream. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class ExampleScript : MonoBehaviour + /// { + /// void Start() + /// { + /// short myMsgType = 444; + /// NetworkWriter writer = new NetworkWriter(); + /// writer.StartMessage(myMsgType); + /// writer.Write("test data"); + /// writer.FinishMessage(); + /// } + /// } + /// + /// See NetworkWriter for another code example. + /// + /// The object to write. + public void Write(Rect value) + { + Write(value.xMin); + Write(value.yMin); + Write(value.width); + Write(value.height); + } + + /// + /// This writes a reference to an object, value, buffer or network message, together with a NetworkIdentity component to the stream. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class ExampleScript : MonoBehaviour + /// { + /// void Start() + /// { + /// short myMsgType = 444; + /// NetworkWriter writer = new NetworkWriter(); + /// writer.StartMessage(myMsgType); + /// writer.Write("test data"); + /// writer.FinishMessage(); + /// } + /// } + /// + /// See NetworkWriter for another code example.s + /// + /// The object to write. + public void Write(Plane value) + { + Write(value.normal); + Write(value.distance); + } + + /// + /// This writes a reference to an object, value, buffer or network message, together with a NetworkIdentity component to the stream. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class ExampleScript : MonoBehaviour + /// { + /// void Start() + /// { + /// short myMsgType = 444; + /// NetworkWriter writer = new NetworkWriter(); + /// writer.StartMessage(myMsgType); + /// writer.Write("test data"); + /// writer.FinishMessage(); + /// } + /// } + /// + /// See NetworkWriter for another code example. + /// + /// The object to write. + public void Write(Ray value) + { + Write(value.direction); + Write(value.origin); + } + + /// + /// This writes a reference to an object, value, buffer or network message, together with a NetworkIdentity component to the stream. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class ExampleScript : MonoBehaviour + /// { + /// void Start() + /// { + /// short myMsgType = 444; + /// NetworkWriter writer = new NetworkWriter(); + /// writer.StartMessage(myMsgType); + /// writer.Write("test data"); + /// writer.FinishMessage(); + /// } + /// } + /// + /// See NetworkWriter for another code example. + /// + /// The object to write. + public void Write(Matrix4x4 value) + { + Write(value.m00); + Write(value.m01); + Write(value.m02); + Write(value.m03); + Write(value.m10); + Write(value.m11); + Write(value.m12); + Write(value.m13); + Write(value.m20); + Write(value.m21); + Write(value.m22); + Write(value.m23); + Write(value.m30); + Write(value.m31); + Write(value.m32); + Write(value.m33); + } + + /// + /// This writes a reference to an object, value, buffer or network message, together with a NetworkIdentity component to the stream. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class ExampleScript : MonoBehaviour + /// { + /// void Start() + /// { + /// short myMsgType = 444; + /// NetworkWriter writer = new NetworkWriter(); + /// writer.StartMessage(myMsgType); + /// writer.Write("test data"); + /// writer.FinishMessage(); + /// } + /// } + /// + /// See NetworkWriter for another code example. + /// + /// The object to write. + public void Write(NetworkHash128 value) + { + Write(value.i0); + Write(value.i1); + Write(value.i2); + Write(value.i3); + Write(value.i4); + Write(value.i5); + Write(value.i6); + Write(value.i7); + Write(value.i8); + Write(value.i9); + Write(value.i10); + Write(value.i11); + Write(value.i12); + Write(value.i13); + Write(value.i14); + Write(value.i15); + } + + /// + /// This writes a reference to an object, value, buffer or network message, together with a NetworkIdentity component to the stream. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class ExampleScript : MonoBehaviour + /// { + /// void Start() + /// { + /// short myMsgType = 444; + /// NetworkWriter writer = new NetworkWriter(); + /// writer.StartMessage(myMsgType); + /// writer.Write("test data"); + /// writer.FinishMessage(); + /// } + /// } + /// + /// See NetworkWriter for another code example. + /// + /// The object to write. + public void Write(NetworkIdentity value) + { + if (value == null) + { + WritePackedUInt32(0); + return; + } + Write(value.netId); + } + + /// + /// This writes a reference to an object, value, buffer or network message, together with a NetworkIdentity component to the stream. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class ExampleScript : MonoBehaviour + /// { + /// void Start() + /// { + /// short myMsgType = 444; + /// NetworkWriter writer = new NetworkWriter(); + /// writer.StartMessage(myMsgType); + /// writer.Write("test data"); + /// writer.FinishMessage(); + /// } + /// } + /// + /// See NetworkWriter for another code example. + /// + /// The object to write. + public void Write(Transform value) + { + if (value == null || value.gameObject == null) + { + WritePackedUInt32(0); + return; + } + var uv = value.gameObject.GetComponent(); + if (uv != null) + { + Write(uv.netId); + } + else + { + if (LogFilter.logWarn) { Debug.LogWarning("NetworkWriter " + value + " has no NetworkIdentity"); } + WritePackedUInt32(0); + } + } + + /// + /// This writes a reference to an object, value, buffer or network message, together with a NetworkIdentity component to the stream. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class ExampleScript : MonoBehaviour + /// { + /// void Start() + /// { + /// short myMsgType = 444; + /// NetworkWriter writer = new NetworkWriter(); + /// writer.StartMessage(myMsgType); + /// writer.Write("test data"); + /// writer.FinishMessage(); + /// } + /// } + /// + /// See NetworkWriter for another code example. + /// + /// The object to write. + public void Write(GameObject value) + { + if (value == null) + { + WritePackedUInt32(0); + return; + } + var uv = value.GetComponent(); + if (uv != null) + { + Write(uv.netId); + } + else + { + if (LogFilter.logWarn) { Debug.LogWarning("NetworkWriter " + value + " has no NetworkIdentity"); } + WritePackedUInt32(0); + } + } + + /// + /// This writes a reference to an object, value, buffer or network message, together with a NetworkIdentity component to the stream. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class ExampleScript : MonoBehaviour + /// { + /// void Start() + /// { + /// short myMsgType = 444; + /// NetworkWriter writer = new NetworkWriter(); + /// writer.StartMessage(myMsgType); + /// writer.Write("test data"); + /// writer.FinishMessage(); + /// } + /// } + /// + /// See NetworkWriter for another code example. + /// + /// The network message to write. + public void Write(MessageBase msg) + { + msg.Serialize(this); + } + + /// + /// Seeks to the start of the internal buffer. + /// + public void SeekZero() + { + m_Buffer.SeekZero(); + } + + /// + /// This begins a new message, which should be completed with FinishMessage() once the payload has been written. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class ExampleScript : MonoBehaviour + /// { + /// void Start() + /// { + /// short myMsgType = 444; + /// NetworkWriter writer = new NetworkWriter(); + /// writer.StartMessage(myMsgType); + /// writer.Write("test data"); + /// writer.FinishMessage(); + /// } + /// } + /// + /// See NetworkWriter for another code example. + /// + /// Message type. + public void StartMessage(short msgType) + { + SeekZero(); + + // two bytes for size, will be filled out in FinishMessage + m_Buffer.WriteByte2(0, 0); + + // two bytes for message type + Write(msgType); + } + + /// + /// This fills out the size header of a message begun with StartMessage(), so that it can be send using Send() functions. + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class ExampleScript : MonoBehaviour + /// { + /// void Start() + /// { + /// short myMsgType = 444; + /// NetworkWriter writer = new NetworkWriter(); + /// writer.StartMessage(myMsgType); + /// writer.Write("test data"); + /// writer.FinishMessage(); + /// } + /// } + /// + /// See NetworkWriter for another code example. + /// + public void FinishMessage() + { + // writes correct size into space at start of buffer + m_Buffer.FinishMessage(); + } + }; +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/PlayerController.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/PlayerController.cs new file mode 100644 index 00000000..864f3247 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/PlayerController.cs @@ -0,0 +1,61 @@ +using System; + +namespace UnityEngine.Networking +{ + /// + /// This represents a networked player. + /// + // This class represents the player entity in a network game, there can be multiple players per client + // when there are multiple people playing on one machine + // The server has one connection per client, and the connection has the player instances of that client + // The client has player instances as member variables (should this be removed and just go though the connection like the server does?) + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class PlayerController + { + internal const short kMaxLocalPlayers = 8; + + /// + /// The local player ID number of this player. + /// The HLAPI treats players and clients as separate GameObjects. In most cases, there is a single player for each client, but in some situations (for example, when there are multiple controllers connected to a console system) there might be multiple player GameObjects for a single connection. When there are multiple players for a single connection, use the playerControllerId property to tell them apart. This is an identifier that is scoped to the connection, so that it maps to the id of the controller associated with the player on that client. + /// + public short playerControllerId = -1; + /// + /// The NetworkIdentity component of the player. + /// + public NetworkIdentity unetView; + /// + /// The game object for this player. + /// + public GameObject gameObject; + + /// + /// The maximum number of local players that a client connection can have. + /// + public const int MaxPlayersPerClient = 32; + + public PlayerController() + { + } + + /// + /// Checks if this PlayerController has an actual player attached to it. + /// + public bool IsValid { get { return playerControllerId != -1; } } + + internal PlayerController(GameObject go, short playerControllerId) + { + gameObject = go; + unetView = go.GetComponent(); + this.playerControllerId = playerControllerId; + } + + /// + /// String representation of the player objects state. + /// + /// String with the object state. + public override string ToString() + { + return string.Format("ID={0} NetworkIdentity NetID={1} Player={2}", new object[] { playerControllerId, (unetView != null ? unetView.netId.ToString() : "null"), (gameObject != null ? gameObject.name : "null") }); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/Properties/AssemblyInfo.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..21390308 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/Properties/AssemblyInfo.cs @@ -0,0 +1,41 @@ +using System; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("UnityEngine.Networking")] +[assembly: AssemblyDescription("Networking High Level API")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Unity Technologies")] +[assembly: AssemblyProduct("UnityEngine.Networking")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] +[assembly: InternalsVisibleTo("UnityEditor.Networking")] +[assembly: InternalsVisibleTo("com.unity.multiplayer-hlapi.Editor")] +[assembly: InternalsVisibleTo("com.unity.multiplayer-hlapi.EditorTests")] +[assembly: InternalsVisibleTo("com.unity.multiplayer-hlapi.Editor-testable")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("87035389-1bb3-40e2-b2a9-c8707e7419ba")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/SyncList.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/SyncList.cs new file mode 100644 index 00000000..c7c49dc1 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/SyncList.cs @@ -0,0 +1,668 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; + +namespace UnityEngine.Networking +{ + /// + /// This is a list of strings that will be synchronized from the server to clients. + /// + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public sealed class SyncListString : SyncList + { + protected override void SerializeItem(NetworkWriter writer, string item) + { + writer.Write(item); + } + + protected override string DeserializeItem(NetworkReader reader) + { + return reader.ReadString(); + } + + [System.Obsolete("ReadReference is now used instead")] + static public SyncListString ReadInstance(NetworkReader reader) + { + ushort count = reader.ReadUInt16(); + var result = new SyncListString(); + for (ushort i = 0; i < count; i++) + { + result.AddInternal(reader.ReadString()); + } + return result; + } + + /// + /// An internal function used for serializing SyncList member variables. + /// + /// + /// + static public void ReadReference(NetworkReader reader, SyncListString syncList) + { + ushort count = reader.ReadUInt16(); + syncList.Clear(); + for (ushort i = 0; i < count; i++) + { + syncList.AddInternal(reader.ReadString()); + } + } + + static public void WriteInstance(NetworkWriter writer, SyncListString items) + { + writer.Write((ushort)items.Count); + for (int i = 0; i < items.Count; i++) + { + writer.Write(items[i]); + } + } + } + + /// + /// A list of floats that will be synchronized from server to clients. + /// + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public sealed class SyncListFloat : SyncList + { + protected override void SerializeItem(NetworkWriter writer, float item) + { + writer.Write(item); + } + + protected override float DeserializeItem(NetworkReader reader) + { + return reader.ReadSingle(); + } + + [System.Obsolete("ReadReference is now used instead")] + static public SyncListFloat ReadInstance(NetworkReader reader) + { + ushort count = reader.ReadUInt16(); + var result = new SyncListFloat(); + for (ushort i = 0; i < count; i++) + { + result.AddInternal(reader.ReadSingle()); + } + return result; + } + + /// + /// An internal function used for serializing SyncList member variables. + /// + /// + /// + static public void ReadReference(NetworkReader reader, SyncListFloat syncList) + { + ushort count = reader.ReadUInt16(); + syncList.Clear(); + for (ushort i = 0; i < count; i++) + { + syncList.AddInternal(reader.ReadSingle()); + } + } + + static public void WriteInstance(NetworkWriter writer, SyncListFloat items) + { + writer.Write((ushort)items.Count); + for (int i = 0; i < items.Count; i++) + { + writer.Write(items[i]); + } + } + } + + /// + /// A list of integers that will be synchronized from server to clients. + /// + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class SyncListInt : SyncList + { + protected override void SerializeItem(NetworkWriter writer, int item) + { + writer.WritePackedUInt32((uint)item); + } + + protected override int DeserializeItem(NetworkReader reader) + { + return (int)reader.ReadPackedUInt32(); + } + + [System.Obsolete("ReadReference is now used instead")] + static public SyncListInt ReadInstance(NetworkReader reader) + { + ushort count = reader.ReadUInt16(); + var result = new SyncListInt(); + for (ushort i = 0; i < count; i++) + { + result.AddInternal((int)reader.ReadPackedUInt32()); + } + return result; + } + + /// + /// An internal function used for serializing SyncList member variables. + /// + /// + /// + static public void ReadReference(NetworkReader reader, SyncListInt syncList) + { + ushort count = reader.ReadUInt16(); + syncList.Clear(); + for (ushort i = 0; i < count; i++) + { + syncList.AddInternal((int)reader.ReadPackedUInt32()); + } + } + + static public void WriteInstance(NetworkWriter writer, SyncListInt items) + { + writer.Write((ushort)items.Count); + + for (int i = 0; i < items.Count; i++) + { + writer.WritePackedUInt32((uint)items[i]); + } + } + } + + /// + /// A list of unsigned integers that will be synchronized from server to clients. + /// + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class SyncListUInt : SyncList + { + protected override void SerializeItem(NetworkWriter writer, uint item) + { + writer.WritePackedUInt32(item); + } + + protected override uint DeserializeItem(NetworkReader reader) + { + return reader.ReadPackedUInt32(); + } + + [System.Obsolete("ReadReference is now used instead")] + static public SyncListUInt ReadInstance(NetworkReader reader) + { + ushort count = reader.ReadUInt16(); + var result = new SyncListUInt(); + for (ushort i = 0; i < count; i++) + { + result.AddInternal(reader.ReadPackedUInt32()); + } + return result; + } + + /// + /// An internal function used for serializing SyncList member variables. + /// + /// + /// + static public void ReadReference(NetworkReader reader, SyncListUInt syncList) + { + ushort count = reader.ReadUInt16(); + syncList.Clear(); + for (ushort i = 0; i < count; i++) + { + syncList.AddInternal(reader.ReadPackedUInt32()); + } + } + + static public void WriteInstance(NetworkWriter writer, SyncListUInt items) + { + writer.Write((ushort)items.Count); + for (int i = 0; i < items.Count; i++) + { + writer.WritePackedUInt32(items[i]); + } + } + } + + /// + /// A list of booleans that will be synchronized from server to clients. + /// + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class SyncListBool : SyncList + { + protected override void SerializeItem(NetworkWriter writer, bool item) + { + writer.Write(item); + } + + protected override bool DeserializeItem(NetworkReader reader) + { + return reader.ReadBoolean(); + } + + [System.Obsolete("ReadReference is now used instead")] + static public SyncListBool ReadInstance(NetworkReader reader) + { + ushort count = reader.ReadUInt16(); + var result = new SyncListBool(); + for (ushort i = 0; i < count; i++) + { + result.AddInternal(reader.ReadBoolean()); + } + return result; + } + + /// + /// An internal function used for serializing SyncList member variables. + /// + /// + /// + static public void ReadReference(NetworkReader reader, SyncListBool syncList) + { + ushort count = reader.ReadUInt16(); + syncList.Clear(); + for (ushort i = 0; i < count; i++) + { + syncList.AddInternal(reader.ReadBoolean()); + } + } + + static public void WriteInstance(NetworkWriter writer, SyncListBool items) + { + writer.Write((ushort)items.Count); + for (int i = 0; i < items.Count; i++) + { + writer.Write(items[i]); + } + } + } + + /// + /// This class is used for lists of structs that are synchronized from the server to clients. + /// To use SyncListStruct, derive a new class with your struct as the generic parameter. + /// + /// + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class SyncListStruct : SyncList where T : struct + { + new public void AddInternal(T item) + { + base.AddInternal(item); + } + + protected override void SerializeItem(NetworkWriter writer, T item) + { + } + + protected override T DeserializeItem(NetworkReader reader) + { + return new T(); + } + + public T GetItem(int i) + { + return base[i]; + } + + new public ushort Count { get { return (ushort)base.Count; } } + } + + /// + /// This is the base class for type-specific SyncList classes. + /// A SyncList can only be of the following type; + /// + /// + /// + /// Basic type (byte, int, float, string, UInt64, etc) + /// + /// + /// Built-in Unity math type (Vector3, Quaternion, etc), + /// + /// + /// NetworkIdentity + /// + /// + /// NetworkInstanceId + /// + /// + /// NetworkHash128 + /// + /// + /// GameObject with a NetworkIdentity component attached. + /// + /// + /// + /// + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + abstract public class SyncList : IList + { + /// + /// A delegate that can be populated to recieve callbacks when the list changes. + /// For example this function is called when the m_ints list changes: + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// + /// public class MyBehaviour : NetworkBehaviour + /// { + /// public SyncListInt m_ints = new SyncListInt(); + /// + /// private void OnIntChanged(SyncListInt.Operation op, int index) + /// { + /// Debug.Log("list changed " + op); + /// } + /// + /// public override void OnStartClient() + /// { + /// m_ints.Callback = OnIntChanged; + /// } + /// } + /// + /// It is best to populate the delagate during the OnStartClient() callback function. Doing it earlier can lead to it being lost when the initial list value is applied. + /// + /// + /// + public delegate void SyncListChanged(Operation op, int itemIndex); + + List m_Objects = new List(); + + /// + /// Returns the number of elements in this SyncList. + /// + public int Count { get { return m_Objects.Count; } } + /// + /// Reports whether the SyncList is read-only. + /// + public bool IsReadOnly { get { return false; } } + /// + /// The delegate type used for SyncListChanged. + /// + public SyncListChanged Callback { get { return m_Callback; } set { m_Callback = value; } } + + /// + /// The types of operations that can occur for SyncLists. + /// + public enum Operation + { + /// + /// Item was added to the list. + /// + OP_ADD, + /// + /// The list was cleared. + /// + OP_CLEAR, + /// + /// An item was inserted into the list. + /// + OP_INSERT, + /// + /// An item was removed from the list. + /// + OP_REMOVE, + /// + /// An item was removed at an index from the list. + /// + OP_REMOVEAT, + /// + /// An item was set to a new value in the list. + /// + OP_SET, + /// + /// An item in the list was manually marked dirty. + /// + OP_DIRTY + }; + + NetworkBehaviour m_Behaviour; + int m_CmdHash; + SyncListChanged m_Callback; + + /// + /// This is used to write a value object from a SyncList to a stream. + /// + /// Stream to write to. + /// Item to write. + abstract protected void SerializeItem(NetworkWriter writer, T item); + /// + /// This method is used when deserializing SyncList items from a stream. + /// + /// Stream to read from. + /// New instance of the SyncList value type. + abstract protected T DeserializeItem(NetworkReader reader); + + + /// + /// Internal function. + /// + /// The behaviour the list belongs to. + /// Identifies this list. + public void InitializeBehaviour(NetworkBehaviour beh, int cmdHash) + { + m_Behaviour = beh; + m_CmdHash = cmdHash; + } + + void SendMsg(Operation op, int itemIndex, T item) + { + if (m_Behaviour == null) + { + if (LogFilter.logError) { Debug.LogError("SyncList not initialized"); } + return; + } + + var uv = m_Behaviour.GetComponent(); + if (uv == null) + { + if (LogFilter.logError) { Debug.LogError("SyncList no NetworkIdentity"); } + return; + } + + if (!uv.isServer) + { + // object is not spawned yet, so no need to send updates. + return; + } + + NetworkWriter writer = new NetworkWriter(); + writer.StartMessage(MsgType.SyncList); + writer.Write(uv.netId); + writer.WritePackedUInt32((uint)m_CmdHash); + writer.Write((byte)op); + writer.WritePackedUInt32((uint)itemIndex); + SerializeItem(writer, item); + writer.FinishMessage(); + + NetworkServer.SendWriterToReady(uv.gameObject, writer, m_Behaviour.GetNetworkChannel()); + +#if UNITY_EDITOR + Profiler.IncrementStatOutgoing(MsgType.SyncList, op.ToString()); +#endif + + // ensure it is invoked on host + if (m_Behaviour.isServer && m_Behaviour.isClient && m_Callback != null) + { + m_Callback.Invoke(op, itemIndex); + } + } + + void SendMsg(Operation op, int itemIndex) + { + SendMsg(op, itemIndex, default(T)); + } + + public void HandleMsg(NetworkReader reader) + { + byte op = reader.ReadByte(); + int itemIndex = (int)reader.ReadPackedUInt32(); + T item = DeserializeItem(reader); + + switch ((Operation)op) + { + case Operation.OP_ADD: + m_Objects.Add(item); + break; + + case Operation.OP_CLEAR: + m_Objects.Clear(); + break; + + case Operation.OP_INSERT: + m_Objects.Insert(itemIndex, item); + break; + + case Operation.OP_REMOVE: + m_Objects.Remove(item); + break; + + case Operation.OP_REMOVEAT: + m_Objects.RemoveAt(itemIndex); + break; + + case Operation.OP_SET: + case Operation.OP_DIRTY: + m_Objects[itemIndex] = item; + break; + } + if (m_Callback != null) + { + m_Callback.Invoke((Operation)op, itemIndex); + } + } + + // used to bypass Add message. + internal void AddInternal(T item) + { + m_Objects.Add(item); + } + + /// + /// Same as List:Add() but the item is added on clients. + /// + /// Item to add. + public void Add(T item) + { + m_Objects.Add(item); + SendMsg(Operation.OP_ADD, m_Objects.Count - 1, item); + } + + /// + /// Same as List:Clear() but the list is cleared on clients. + /// + public void Clear() + { + m_Objects.Clear(); + SendMsg(Operation.OP_CLEAR, 0); + } + + /// + /// Determines whether the list contains item item. + /// + /// Item to search for. + /// True if item contain + public bool Contains(T item) + { + return m_Objects.Contains(item); + } + + /// + /// Copies the elements of the SyncList to an Array, starting at a particular Array index. + /// + /// Array to copy elements to. + /// The zero-based index in array at which copying begins. + public void CopyTo(T[] array, int index) + { + m_Objects.CopyTo(array, index); + } + + /// + /// Determines the index of a specific item in the SyncList. + /// + /// The item to return the index for. + /// Index of the item + public int IndexOf(T item) + { + return m_Objects.IndexOf(item); + } + + /// + /// Same as List::Insert() but also inserts into list on clients. + /// + /// Where to insert the item. + /// Item to insert. + public void Insert(int index, T item) + { + m_Objects.Insert(index, item); + SendMsg(Operation.OP_INSERT, index, item); + } + + /// + /// Same as List:Remove except removes on clients also. + /// + /// Item to remove. + /// + public bool Remove(T item) + { + var result = m_Objects.Remove(item); + if (result) + { + SendMsg(Operation.OP_REMOVE, 0, item); + } + return result; + } + + /// + /// Same as List:Remove except it removes the index on clients also. + /// + /// Index to remove. + public void RemoveAt(int index) + { + m_Objects.RemoveAt(index); + SendMsg(Operation.OP_REMOVEAT, index); + } + + /// + /// Marks an item in the list as dirty, so it will be updated on clients. + /// + /// Index of item to dirty. + public void Dirty(int index) + { + SendMsg(Operation.OP_DIRTY, index, m_Objects[index]); + } + + public T this[int i] + { + get { return m_Objects[i]; } + set + { + bool changed = false; + if (m_Objects[i] == null) + { + if (value == null) + return; + else + changed = true; + } + else + { + changed = !m_Objects[i].Equals(value); + } + + m_Objects[i] = value; + if (changed) + { + SendMsg(Operation.OP_SET, i, value); + } + } + } + + /// + /// Returns an enumerator that iterates through the SyncList. + /// + /// + public IEnumerator GetEnumerator() + { + return m_Objects.GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/UNetwork.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/UNetwork.cs new file mode 100644 index 00000000..2450cc34 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/UNetwork.cs @@ -0,0 +1,429 @@ +using System; + +#pragma warning disable 618 +namespace UnityEngine.Networking +{ + // Handles network messages on client and server + public delegate void NetworkMessageDelegate(NetworkMessage netMsg); + + // Handles requests to spawn objects on the client + public delegate GameObject SpawnDelegate(Vector3 position, NetworkHash128 assetId); + + // Handles requests to unspawn objects on the client + public delegate void UnSpawnDelegate(GameObject spawned); + + /// + /// Container class for networking system built-in message types. + /// + // built-in system network messages + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class MsgType + { + // internal system messages - cannot be replaced by user code + /// + /// Internal networking system message for destroying objects. + /// + public const short ObjectDestroy = 1; + /// + /// Internal networking system message for sending a ClientRPC from server to client. + /// + public const short Rpc = 2; + /// + /// Internal networking system message for spawning objects. + /// + public const short ObjectSpawn = 3; + /// + /// Internal networking system message for telling clients they own a player object. + /// + public const short Owner = 4; + /// + /// Internal networking system message for sending a command from client to server. + /// + public const short Command = 5; + /// + /// Internal networking system message for sending tranforms from client to server. + /// + public const short LocalPlayerTransform = 6; + /// + /// Internal networking system message for sending a SyncEvent from server to client. + /// + public const short SyncEvent = 7; + /// + /// Internal networking system message for updating SyncVars on a client from a server. + /// + public const short UpdateVars = 8; + /// + /// Internal networking system message for sending a USyncList generic list. + /// + public const short SyncList = 9; + /// + /// Internal networking system message for spawning scene objects. + /// + public const short ObjectSpawnScene = 10; + /// + /// Internal networking system message for sending information about network peers to clients. + /// + public const short NetworkInfo = 11; + /// + /// Internal networking system messages used to tell when the initial contents of a scene is being spawned. + /// + public const short SpawnFinished = 12; + /// + /// Internal networking system message for hiding objects. + /// + public const short ObjectHide = 13; + /// + /// Internal networking system message for HLAPI CRC checking. + /// + public const short CRC = 14; + /// + /// Internal networking system message for setting authority to a client for an object. + /// + public const short LocalClientAuthority = 15; + /// + /// Internal networking system message for sending tranforms for client object from client to server. + /// + public const short LocalChildTransform = 16; + /// + /// Internal networking system message for identifying fragmented packets. + /// + public const short Fragment = 17; + /// + /// Internal networking system message for sending information about changes in authority for non-player objects to clients. + /// + public const short PeerClientAuthority = 18; + + // used for profiling + internal const short UserMessage = 0; + internal const short HLAPIMsg = 28; + internal const short LLAPIMsg = 29; + internal const short HLAPIResend = 30; + internal const short HLAPIPending = 31; + + /// + /// The highest value of internal networking system message ids. User messages must be above this value. User code cannot replace these handlers. + /// + public const short InternalHighest = 31; + + // public system messages - can be replaced by user code + /// + /// Internal networking system message for communicating a connection has occurred. + /// Ensure you use RegisterHandler on the client or server. Insert MsgType.Connect as a parameter to listen for connections. + /// + public const short Connect = 32; + /// + /// Internal networking system message for communicating a disconnect has occurred. + /// To help understand the reason for a disconnect, an IntegerMessage number is written to the message body, which can be read and converted to the error enum. + /// + public const short Disconnect = 33; + /// + /// Internal networking system message for communicating an error. + /// + public const short Error = 34; + /// + /// Internal networking system message for clients to tell server they are ready. + /// + public const short Ready = 35; + /// + /// Internal networking system message for server to tell clients they are no longer ready. + /// Can be used when switching scenes, to stop receiving network traffic during the switch. + /// + public const short NotReady = 36; + /// + /// Internal networking system message for adding player objects to client instances. + /// This is sent to the server when a client calls NetworkClient.AddPlayer(). The server should have a handler for this message type to add the player object to the game and notify the client with NetworkServer.AddPlayer(). + /// + public const short AddPlayer = 37; + /// + /// Internal networking system message for removing a player object which was spawned for a client. + /// + public const short RemovePlayer = 38; + /// + /// Internal networking system message that tells clients which scene to load when they connect to a server. + /// + public const short Scene = 39; + /// + /// Internal networking system message for sending synchronizing animation state. + /// Used by the NetworkAnimation component. + /// + public const short Animation = 40; + /// + /// Internal networking system message for sending synchronizing animation parameter state. + /// Used by the NetworkAnimation component. + /// + public const short AnimationParameters = 41; + /// + /// Internal networking system message for sending animation triggers. + /// Used by the NetworkAnimation component. + /// + public const short AnimationTrigger = 42; + /// + /// Internal networking system message for communicating a player is ready in the lobby. + /// + public const short LobbyReadyToBegin = 43; + /// + /// Internal networking system message for communicating a lobby player has loaded the game scene. + /// + public const short LobbySceneLoaded = 44; + /// + /// Internal networking system message for communicating failing to add lobby player. + /// + public const short LobbyAddPlayerFailed = 45; + /// + /// Internal networking system messages used to return the game to the lobby scene. + /// + public const short LobbyReturnToLobby = 46; + /// + /// Internal networking system message used when a client connects to the new host of a game. + /// + public const short ReconnectPlayer = 47; + + /// + /// The highest value of built-in networking system message ids. User messages must be above this value. + /// + //NOTE: update msgLabels below if this is changed. + public const short Highest = 47; + + static internal string[] msgLabels = + { + "none", + "ObjectDestroy", + "Rpc", + "ObjectSpawn", + "Owner", + "Command", + "LocalPlayerTransform", + "SyncEvent", + "UpdateVars", + "SyncList", + "ObjectSpawnScene", // 10 + "NetworkInfo", + "SpawnFinished", + "ObjectHide", + "CRC", + "LocalClientAuthority", + "LocalChildTransform", + "Fragment", + "PeerClientAuthority", + "", + "", // 20 + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", // 30 + "", // - SystemInternalHighest + "Connect", // 32, + "Disconnect", + "Error", + "Ready", + "NotReady", + "AddPlayer", + "RemovePlayer", + "Scene", + "Animation", // 40 + "AnimationParams", + "AnimationTrigger", + "LobbyReadyToBegin", + "LobbySceneLoaded", + "LobbyAddPlayerFailed", // 45 + "LobbyReturnToLobby", // 46 + "ReconnectPlayer", // 47 + }; + + /// + /// Returns the name of internal message types by their id. + /// + /// A internal message id value. + /// The name of the internal message. + static public string MsgTypeToString(short value) + { + if (value < 0 || value > Highest) + { + return String.Empty; + } + string result = msgLabels[value]; + if (string.IsNullOrEmpty(result)) + { + result = "[" + value + "]"; + } + return result; + } + } + + /// + /// The details of a network message received by a client or server on a network connection. + /// + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class NetworkMessage + { + /// + /// The size of the largest message in bytes that can be sent on a NetworkConnection. + /// Note that channels that are not Fragmented cannot send messages larger than the Maximum Transmission Unity (MTU) size, which is about 1400 bytes by default. + /// + public const int MaxMessageSize = (64 * 1024) - 1; + + /// + /// The id of the message type of the message. + /// + public short msgType; + /// + /// The connection the message was recieved on. + /// + public NetworkConnection conn; + /// + /// A NetworkReader object that contains the contents of the message. + /// For some built-in message types with no body, this can be null. + /// + public NetworkReader reader; + /// + /// The transport layer channel the message was sent on. + /// + public int channelId; + + /// + /// Returns a string with the numeric representation of each byte in the payload. + /// + /// Network message payload to dump. + /// Length of payload in bytes. + /// Dumped info from payload. + public static string Dump(byte[] payload, int sz) + { + string outStr = "["; + for (int i = 0; i < sz; i++) + { + outStr += (payload[i] + " "); + } + outStr += "]"; + return outStr; + } + + /// + /// ReadMessage is used to extract a typed network message from the NetworkReader of a NetworkMessage object. + /// For example in a handler for the AddPlayer message: + /// + /// using UnityEngine; + /// using UnityEngine.Networking; + /// using UnityEngine.Networking.NetworkSystem; + /// + /// public class MyManager : NetworkManager + /// { + /// void OnServerAddPlayerMessageInternal(NetworkMessage netMsg) + /// { + /// var msg = netMsg.ReadMessage<AddPlayerMessage>(); + /// OnServerAddPlayer(netMsg.conn, msg.playerControllerId); + /// } + /// } + /// + /// The AddPlayerMessage that is created will be populated by calling DeSerialize(). So when it is returned form ReadMessage it is ready to use. + /// + /// The type of the Network Message, must be derived from MessageBase. + /// + public TMsg ReadMessage() where TMsg : MessageBase, new() + { + var msg = new TMsg(); + msg.Deserialize(reader); + return msg; + } + + public void ReadMessage(TMsg msg) where TMsg : MessageBase + { + msg.Deserialize(reader); + } + } + + /// + /// Enumeration of Networking versions. + /// + public enum Version + { + /// + /// The current UNET version. + /// + Current = 1 + } + + /// + /// Class containing constants for default network channels. + /// + [Obsolete("The high level API classes are deprecated and will be removed in the future.")] + public class Channels + { + /// + /// The id of the default reliable channel used by the UNet HLAPI, This channel is used for state updates and spawning. + /// + public const int DefaultReliable = 0; + /// + /// The id of the default unreliable channel used for the UNet HLAPI. This channel is used for movement updates. + /// + public const int DefaultUnreliable = 1; + } + + /// + /// An enumeration of the options that can be set on a network channel. + /// + public enum ChannelOption + { + /// + /// The option to set the number of pending buffers for a channel. + /// These buffers are allocated dynamically as required when writes to the transport layer fail. Each buffer will be the size of maxPacketSize for the channel - usually around 1400 bytes. The default is 16 buffers. + /// This only applies to reliable channels. If a reliable channel runs out of pnding buffers, data will be lost. + /// + MaxPendingBuffers = 1, + AllowFragmentation = 2, + MaxPacketSize = 3 + // maybe add an InitialCapacity for Pending Buffers list if needed in the future + } + +#if UNITY_EDITOR + class Profiler + { + internal static void IncrementStatOutgoing(short msgType) + { + IncrementStatOutgoing(msgType, "msg"); + } + + internal static void IncrementStatOutgoing(short msgType, string name) + { + UnityEditor.NetworkDetailStats.IncrementStat( + UnityEditor.NetworkDetailStats.NetworkDirection.Outgoing, + msgType, name, 1); + } + + internal static void IncrementStatIncoming(short msgType) + { + IncrementStatIncoming(msgType, "msg"); + } + + internal static void IncrementStatIncoming(short msgType, string name) + { + UnityEditor.NetworkDetailStats.IncrementStat( + UnityEditor.NetworkDetailStats.NetworkDirection.Incoming, + msgType, name, 1); + } + + internal static void SetStatOutgoing(short msgType, int value) + { + UnityEditor.NetworkDetailStats.SetStat( + UnityEditor.NetworkDetailStats.NetworkDirection.Outgoing, + msgType, "msg", value); + } + + internal static void ResetAll() + { + UnityEditor.NetworkDetailStats.ResetAll(); + } + + internal static void NewProfilerTick() + { + UnityEditor.NetworkDetailStats.NewProfilerTick(Time.time); + } + } +#endif +} +#pragma warning disable 618 \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/com.unity.multiplayer-hlapi.Runtime.asmdef b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/com.unity.multiplayer-hlapi.Runtime.asmdef new file mode 100644 index 00000000..3fb3227a --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Runtime/com.unity.multiplayer-hlapi.Runtime.asmdef @@ -0,0 +1,6 @@ +{ + "name": "com.unity.multiplayer-hlapi.Runtime", + "references": [], + "includePlatforms": [], + "excludePlatforms": [] +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Editor/NetBufferTest.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Editor/NetBufferTest.cs new file mode 100644 index 00000000..c74a75b7 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Editor/NetBufferTest.cs @@ -0,0 +1,250 @@ +using System; +using System.Linq; +using NUnit.Framework; +using UnityEngine.Networking; + +[TestFixture] +public class NetBufferTest +{ + const int bufferLength = 10; + + private byte[] bytes; + private byte[] tempArray; + private NetBuffer buffer; + + [SetUp] + public void Setup() + { + tempArray = new byte[bufferLength]; + + bytes = Enumerable.Range(1, bufferLength).Select(i => (byte)i).ToArray(); + buffer = new NetBuffer(bytes); + } + + [Test] + public void BufferCreated_InitialParametersAreSet() + { + Assert.AreEqual(64, new NetBuffer().Length, "NetBuffer initial size is not 64 bytes after buffer was created"); + Assert.AreEqual(0, new NetBuffer().Position, "NetBuffer initial position is not 0 after buffer was created"); + } + + [Test] + public void BufferCreatedFromArrayOfBytesHasTheSameLengthAsOriginalArray() + { + Assert.AreEqual(0, buffer.Position, "NetBuffer initial position does not equal to 0 after buffer was created"); + Assert.AreEqual(buffer.Length, bufferLength, + "NetBuffer's size doesn't equal to the size of byte array it was created from"); + } + + [Test] + public void BufferReferencesTheArrayAndDoesNotCopyItsValues() + { + bytes[0] = 9; + + Assert.AreEqual(bytes[0], buffer.ReadByte(), + "ReadByte function didn't change the value when the value is changed in referenced array"); + } + + [Test] + public void CanReadOneByte() + { + Assert.AreEqual(bytes[0], buffer.ReadByte(), "ReadByte function read the first byte incorrectly"); + Assert.AreEqual(1, buffer.Position, "ReadByte function didn't changed buffer's position after byte was read"); + } + + [Test] + public void AttemptToReadByteOutOfBufferBounds_OutOfRangeExceptionRaises() + { + var testBuffer = new NetBuffer(new byte[1]); + testBuffer.ReadByte(); + + Assert.That(() => testBuffer.ReadByte(), + Throws.Exception.TypeOf() + .With.Message.EqualTo("NetworkReader:ReadByte out of range:NetBuf sz:1 pos:1")); + } + + [Test] + public void BunchOfBytesCanBeReadAtOnce() + { + buffer.ReadBytes(tempArray, bufferLength); + + for (var i = 0; i < bufferLength; i++) + { + Assert.AreEqual(bytes[i], tempArray[i], "ReadBytes function read a bunch of bytes at once and value of '" + i + "' byte is incorrect"); + } + + Assert.AreEqual(bufferLength, buffer.Position, "ReadBytes function changed position incorrectly after read a bunch of bytes"); + } + + [Test] + public void AttemptToReadABunchOfBytesOutOfBufferBounds_OutOfRangeExceptionRaises() + { + var testBuffer = new NetBuffer(new byte[1]); + + Assert.That(() => testBuffer.ReadBytes(new byte[2], 2), + Throws.Exception.TypeOf() + .With.Message.EqualTo("NetworkReader:ReadBytes out of range: (2) NetBuf sz:1 pos:0")); + } + + [Test] + public void CanWriteByte() + { + buffer.WriteByte(byte.MaxValue); + + Assert.AreEqual(byte.MaxValue, bytes[0], "WriteByte function cannot write byte to the provided array"); + Assert.AreEqual(1, buffer.Position, "WriteByte function didn't shift the NetBuffer's position"); + } + + [Test] + public void CanWriteTwoBytes() + { + buffer.WriteByte2(255, 127); + + Assert.AreEqual(255, bytes[0], "WriteByte2 function wrote incorrect first byte to the provided array"); + Assert.AreEqual(127, bytes[1], "WriteByte2 function wrote incorrect second byte to the provided array"); + + Assert.AreEqual(2, buffer.Position, "WriteByte2 function didn't shift the NetBuffer's position"); + } + + [Test] + public void CanWriteFourBytes() + { + buffer.WriteByte4(10, 11, 12, 13); + + Assert.AreEqual(10, bytes[0], "WriteByte4 function wrote incorrect first byte to the provided array"); + Assert.AreEqual(11, bytes[1], "WriteByte4 function wrote incorrect second byte to the provided array"); + Assert.AreEqual(12, bytes[2], "WriteByte4 function wrote incorrect third byte to the provided array"); + Assert.AreEqual(13, bytes[3], "WriteByte4 function wrote incorrect fourth byte to the provided array"); + + Assert.AreEqual(4, buffer.Position, "WriteByte4 function didn't shift the NetBuffer's position"); + } + + [Test] + public void CanWriteEightBytes() + { + buffer.WriteByte8(100, 110, 120, 130, 140, 150, 160, 170); + + Assert.AreEqual(100, bytes[0], "WriteByte8 function wrote incorrect first byte to the provided array"); + Assert.AreEqual(110, bytes[1], "WriteByte8 function wrote incorrect second byte to the provided array"); + Assert.AreEqual(120, bytes[2], "WriteByte8 function wrote incorrect third byte to the provided array"); + Assert.AreEqual(130, bytes[3], "WriteByte8 function wrote incorrect fourth byte to the provided array"); + Assert.AreEqual(140, bytes[4], "WriteByte8 function wrote incorrect fifth byte to the provided array"); + Assert.AreEqual(150, bytes[5], "WriteByte8 function wrote incorrect sixth byte to the provided array"); + Assert.AreEqual(160, bytes[6], "WriteByte8 function wrote incorrect seventh byte to the provided array"); + Assert.AreEqual(170, bytes[7], "WriteByte8 function wrote incorrect eighth byte to the provided array"); + + Assert.AreEqual(8, buffer.Position, "WriteByte8 function didn't shift the NetBuffer's position"); + } + + [TestCase(4, 14)] + public void BufferSizeGrowsSeveralTimesUntilNewSizeCanHandleAllValuesToWrite(int length, int expectedLength) + { + var testBuffer = new NetBuffer(new byte[length]); + testBuffer.WriteBytes(new byte[10], 10); + + Assert.AreEqual(expectedLength, testBuffer.Length, "New buffer length cannot handle all values"); + } + + [TestCase(bufferLength - 1, (ushort)(bufferLength - 1 - 5))] // array.Length < buffer.Length && bytes to write < array.Length + [TestCase(bufferLength - 1, (ushort)(bufferLength - 1))] // array.Length < buffer.Length && bytes to write == array.Length + [TestCase(bufferLength, (ushort)(bufferLength - 5))] // array.Length == buffer.Length && bytes to write < array.Length + [TestCase(bufferLength, (ushort)(bufferLength))] // array.Length == buffer.Length && bytes to write == array.Length + [TestCase(bufferLength + 1, (ushort)(bufferLength + 1 - 5))] // array.Length > buffer.Length && bytes to write < array.Length + [TestCase(bufferLength + 1, (ushort)(bufferLength + 1))] // array.Length > buffer.Length && bytes to write == array.Length + public void CanWriteABunchOfBytesAtOnce(int arraySize, ushort amountToWrite) + { + var sourceArray = Enumerable.Range(10, arraySize).Select(i => (byte)i).ToArray(); + + buffer.WriteBytes(sourceArray, amountToWrite); + + Assert.AreEqual(amountToWrite, buffer.Position, "WriteBytes function changed position incorrectly after read a bunch of bytes"); + + buffer.SeekZero(); + for (var i = 0; i < amountToWrite; i++) + { + Assert.AreEqual(sourceArray[i], buffer.ReadByte(), "WriteBytes function wrote a bunch of bytes at once and value of '" + i + "' byte is incorrect"); + } + } + + [TestCase((ushort) 5, (ushort) 4)] // offset < buffer size && offset + count < buffer size + [TestCase((ushort) 10, (ushort) 10)] // offset == buffer size && offset + count > buffer size + [TestCase((ushort) 20, (ushort) 20)] // offset > buffer size + [TestCase((ushort) 5, (ushort) 15)] // offset < buffer size && count > buffer size + [TestCase((ushort) 10, (ushort) 10)] // offset == buffer size && offset + count > buffer size + [TestCase((ushort) 20, (ushort) 20)] // offset > buffer size + public void CanWriteAtOffset(ushort offset, ushort count) + { + var sourceArray = Enumerable.Range(100, count).Select(i => (byte)i).ToArray(); + buffer.WriteBytesAtOffset(sourceArray, offset, count); + + Assert.AreEqual(offset + count, buffer.Position, "WriteAtOffset didn't shift buffer's position"); + + buffer.SeekZero(); + buffer.ReadBytes(new byte[offset], offset); + + for (var i = 0; i < count; i++) + { + Assert.AreEqual(sourceArray[i], buffer.ReadByte(), + "WriteAtOffset function wrote a bunch of bytes at offset '" + offset + "' " + "and value of '" + i + "' byte is incorrect"); + } + } + + [Test] + public void NewMemoryIsAllocated_ReferenceToOldArrayIsLost() + { + var sourceArray = Enumerable.Range(100, 10).Select(i => (byte)i).ToArray(); + buffer.WriteBytesAtOffset(sourceArray, (ushort)buffer.Length, 10); //size increased and new memory is allocated + buffer.SeekZero(); + + bytes[0] = 9; + + Assert.AreNotEqual(9, buffer.ReadByte(), "Link to previous referenced array is not lost and changes in referenced array affected internal buffer"); + } + + [Test] + public void SeekZeroMovesPositionToZero() + { + buffer.WriteByte(127); + buffer.SeekZero(); + Assert.AreEqual(0, buffer.Position, "SeekZero function didn't move position to zero"); + } + + [Test] + public void ReplaceFunctionReplacesInternalBufferWithProvidedOne() + { + var testBuffer = new NetBuffer(); + testBuffer.ReadByte(); + testBuffer.Replace(new byte[] {255}); + + Assert.AreEqual(0, testBuffer.Position, "Replace operation didn't move the postion of buffer to zero"); + Assert.AreEqual(1, testBuffer.Length, "New buffer length is not corresponding to the replaced array length"); + Assert.AreEqual(255, testBuffer.ReadByte(), "NetBuffer read incorrect value after replace operation"); + } + + [TestCase(100, 150)] + [TestCase(3, 5)] + [TestCase(1, 2)] + public void BufferSizeGrows_NewBufferLengthRoundedUp(int length, int expectedLength) + { + var testBuffer = new NetBuffer(new byte[length]); + + for (var i = 0; i < length; i++) + { + testBuffer.WriteByte(byte.MaxValue); + } + + Assert.AreEqual(expectedLength, testBuffer.Length, "New NetBuffer's length has unexpected value"); + } + + [Test] + public void WriteBytesCopiesBytesIntoBufferFromCurrentPosition() + { + var sourceArray = Enumerable.Range(100, bufferLength).Select(i => (byte)i).ToArray(); + buffer.ReadBytes(new byte[2], 2); // shift position to 2 + buffer.WriteBytes(sourceArray, bufferLength); //count == buffer.Length + buffer.SeekZero(); + + Assert.AreEqual(bytes[0], buffer.ReadByte(), "WriteBytes touched the values outside buffer position. First byte is wrong"); + Assert.AreEqual(bytes[1], buffer.ReadByte(), "WriteBytes touched the values outside buffer position. Second byte is wrong"); + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Editor/NetworkClientTest.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Editor/NetworkClientTest.cs new file mode 100644 index 00000000..8f3f48df --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Editor/NetworkClientTest.cs @@ -0,0 +1,38 @@ +using NUnit.Framework; +using UnityEngine; +using UnityEngine.Networking; +using UnityEngine.Networking.NetworkSystem; + +#pragma warning disable 618 +[TestFixture] +public class NetworkClientTest +{ + private NetworkClient m_Client; + private static string s_LatestLogMessage; + + static void HandleLog(string logString, string stackTrace, LogType type) + { + s_LatestLogMessage = type + ": " + logString + "\n" + stackTrace; + } + + [SetUp] + public void Setup() + { + Application.logMessageReceived += HandleLog; + } + + [TearDown] + public void Teardown() + { + Application.logMessageReceived -= HandleLog; + } + + [Test] + public void DisconnectWithoutConnectedConnection() + { + m_Client = new NetworkClient(new NetworkConnection()); + m_Client.Disconnect(); + Assert.AreEqual(null, s_LatestLogMessage); + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Editor/NetworkReaderWriter_BasicTypesTest.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Editor/NetworkReaderWriter_BasicTypesTest.cs new file mode 100644 index 00000000..16e61c7d --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Editor/NetworkReaderWriter_BasicTypesTest.cs @@ -0,0 +1,233 @@ +using NUnit.Framework; +using UnityEngine.Networking; + +#pragma warning disable 618 +[TestFixture] +public class NetworkReaderWriter_BasicTypesTest +{ + private NetworkWriter writer; + + [SetUp] + public void Setup() + { + writer = new NetworkWriter(); + } + + // ulong and uint cases have been taken from http://sqlite.org/src4/doc/trunk/www/varint.wiki + private static uint[] UInt32Cases = + { + uint.MinValue, 240, 241, 2287, 2288, 67823, 67824, 16777215, 16777216, 4294967295, uint.MaxValue + }; + private static ulong[] UInt64Cases = + { + ulong.MinValue, 240, 241, 2287, 2288, 67823, 67824, 16777215, 16777216, 4294967295, + 1099511627775, 1099511627776, 281474976710655, 281474976710656, + 72057594037927935, 72057594037927936, ulong.MaxValue + }; + + [Test, TestCaseSource("UInt32Cases")] + public void WriteAndReadPackedUInt32(uint testValue) + { + writer.WritePackedUInt32(testValue); + var reader = new NetworkReader(writer); + Assert.AreEqual(testValue, reader.ReadPackedUInt32(), "Writer and Reader have different values for packed 'uint' type"); + } + + [Test, TestCaseSource("UInt64Cases")] + public void WriteAndReadPackedUInt64(ulong testValue) + { + writer.WritePackedUInt64(testValue); + var reader = new NetworkReader(writer); + Assert.AreEqual(testValue, reader.ReadPackedUInt64(), "Writer and Reader have different values for packed 'ulong' type"); + } + + [Test, TestCaseSource("UInt32Cases")] + public void WriteAndReadUInt32(uint testValue) + { + writer.Write(testValue); + var reader = new NetworkReader(writer); + Assert.AreEqual(testValue, reader.ReadUInt32(), "Writer and Reader have different values for 'uint' type"); + } + + [Test, TestCaseSource("UInt64Cases")] + public void WriteAndReadUInt64(ulong testValue) + { + writer.Write(testValue); + var reader = new NetworkReader(writer); + Assert.AreEqual(testValue, reader.ReadUInt64(), "Writer and Reader have different values for 'ulong' type"); + } + + private static char[] CharCases = { char.MinValue, '\n', '\uFFF0', char.MaxValue }; + + [Ignore("848212")] + [Test, TestCaseSource("CharCases")] + public void WriteAndReadChar(char testValue) + { + writer.Write(testValue); + var reader = new NetworkReader(writer); + Assert.AreEqual(testValue, reader.ReadChar(), "Writer and Reader have different values for 'char' type"); + } + + private static byte[] ByteCases = { byte.MinValue, 127, byte.MaxValue }; + + [Test, TestCaseSource("ByteCases")] + public void WriteAndReadByte(byte testValue) + { + writer.Write(testValue); + var reader = new NetworkReader(writer); + Assert.AreEqual(testValue, reader.ReadByte(), "Writer and Reader have different values for 'byte' type"); + } + + private static sbyte[] SByteCases = { sbyte.MinValue, 0, -0, +0, sbyte.MaxValue }; + + [Test, TestCaseSource("SByteCases")] + public void WriteAndReadSByte(sbyte testValue) + { + writer.Write(testValue); + var reader = new NetworkReader(writer); + Assert.AreEqual(testValue, reader.ReadSByte(), "Writer and Reader have different values for 'sbyte' type"); + } + + private static short[] ShortCases = + { + short.MinValue, -127, 0, 128, 255, short.MaxValue + }; + + [Test, TestCaseSource("ShortCases")] + public void WriteAndReadShort(short testValue) + { + writer.Write(testValue); + var reader = new NetworkReader(writer); + Assert.AreEqual(testValue, reader.ReadInt16(), "Writer and Reader have different values for 'short' type"); + } + + private static ushort[] UshortCases = + { + ushort.MinValue, 128, 255, 32767, ushort.MaxValue + }; + + [Test, TestCaseSource("UshortCases")] + public void WriteAndReadUShort(ushort testValue) + { + writer.Write(testValue); + var reader = new NetworkReader(writer); + Assert.AreEqual(testValue, reader.ReadUInt16(), "Writer and Reader have different values for 'ushort' type"); + } + + private static int[] IntCases = + { + int.MinValue, -32768, -128, 0, 127, 255, 32767, int.MaxValue + }; + + [Test, TestCaseSource("IntCases")] + public void WriteAndReadInt(int testValue) + { + writer.Write(testValue); + var reader = new NetworkReader(writer); + Assert.AreEqual(testValue, reader.ReadInt32(), "Writer and Reader have different values for 'int' type"); + } + + private static long[] LongCases = + { + long.MinValue, -2147483648, -65536, -32768, -128, 0, 127, 255, 32767, 65535, 2147483647, long.MaxValue + }; + + [Test, TestCaseSource("LongCases")] + public void WriteAndReadLong(long testValue) + { + writer.Write(testValue); + var reader = new NetworkReader(writer); + Assert.AreEqual(testValue, reader.ReadInt64(), "Writer and Reader have different values for 'long' type"); + } + + private static float[] FloatCases = + { + float.MinValue, float.NaN, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.MaxValue + }; + + [Test, TestCaseSource("FloatCases")] + public void WriteAndReadFloat(float testValue) + { + writer.Write(testValue); + var reader = new NetworkReader(writer); + Assert.AreEqual(testValue, reader.ReadSingle(), "Writer and Reader have different values for 'float' type"); + } + + private static double[] DoubleCases = + { + double.MinValue, double.Epsilon, double.NaN, double.NegativeInfinity , double.PositiveInfinity, double.MaxValue, + float.MinValue, float.NaN, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.MaxValue + }; + + [Test, TestCaseSource("DoubleCases")] + public void WriteAndReadDouble(double testValue) + { + writer.Write(testValue); + var reader = new NetworkReader(writer); + Assert.AreEqual(testValue, reader.ReadDouble(), "Writer and Reader have different values for 'double' type"); + } + + private static decimal[] DecimalCases = + { + decimal.MinValue, decimal.MinusOne, decimal.One, decimal.Zero, decimal.MaxValue + }; + + [Test, TestCaseSource("DecimalCases")] + public void WriteAndReadDecimal(decimal testValue) + { + writer.Write(testValue); + var reader = new NetworkReader(writer); + Assert.AreEqual(testValue, reader.ReadDecimal(), "Writer and Reader have different values for 'decimal' type"); + } + + private static bool[] BoolCases = + { + true, false + }; + + [Test, TestCaseSource("BoolCases")] + public void WriteAndReadBool(bool testValue) + { + writer.Write(testValue); + var reader = new NetworkReader(writer); + Assert.AreEqual(testValue, reader.ReadBoolean(), "Writer and Reader have different values for 'bool' type"); + } + + // Cases have been taken from http://www.cl.cam.ac.uk/~mgk25/ucs/examples/quickbrown.txt + private static string[] StringCases = + { + bool.TrueString, bool.FalseString, string.Empty, + "Quizdeltagerne spiste jordbær med fløde, mens cirkusklovnen Wolther spillede på xylofon.", + "Falsches Üben von Xylophonmusik quält jeden größeren Zwerg", + "Γαζέες καὶ μυρτιὲς δὲν θὰ βρῶ πιὰ στὸ χρυσαφὶ ξέφωτο", + "The quick brown fox jumps over the lazy dog", + "El pingüino Wenceslao hizo kilómetros bajo exhaustiva lluvia y frío, añoraba a su querido cachorro.", + "Le cœur déçu mais l'âme plutôt naïve, Louÿs rêva de crapaüter en canoë au delà des îles, près du mälström où brûlent les novæ.", + "D'fhuascail Íosa, Úrmhac na hÓighe Beannaithe, pór Éava agus Ádhaimh", + "Árvíztűrő tükörfúrógép", + "Kæmi ný öxi hér ykist þjófum nú bæði víl og ádrepa. Sævör grét áðan því úlpan var ónýt", + "いろはにほへとちりぬるを", "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム", + "דג סקרן שט בים מאוכזב ולפתע מצא לו חברה איך הקליטה", + "Pchnąć w tę łódź jeża lub ośm skrzyń fig", + "В чащах юга жил бы цитрус? Да, но фальшивый экземпляр!", + "๏ เป็นมนุษย์สุดประเสริฐเลิศคุณค่า", " Pijamalı hasta, yağız şoföre çabucak güvendi." + }; + + [Test, TestCaseSource("StringCases")] + public void WriteAndReadString(string testValue) + { + writer.Write(testValue); + var reader = new NetworkReader(writer); + Assert.AreEqual(testValue, reader.ReadString(), "Writer and Reader have different values for 'string' type"); + } + + [Test] + public void WriteNullString_ReadEmptyString() + { + string testString = null; + writer.Write(testString); + var reader = new NetworkReader(writer); + Assert.AreEqual(string.Empty, reader.ReadString(), "Writer and Reader have different values for 'string' type"); + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Editor/WeaverILGenerationTests/WeaverILGenerationTests.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Editor/WeaverILGenerationTests/WeaverILGenerationTests.cs new file mode 100644 index 00000000..84fa3246 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Editor/WeaverILGenerationTests/WeaverILGenerationTests.cs @@ -0,0 +1,86 @@ +using Mono.Cecil; +using Mono.Cecil.Cil; +using NUnit.Framework; +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +[TestFixture] +public class WeaverILGenerationTests +{ + [Test] + public void TargetRPCServerClientChecks() + { + WeaverILMatcher.MatchMethodIL(typeof(WeaverILGenerationTests_TargetRPCServerClientChecks), "CallTargetRpcTest", false, 1, 1, + new MockInstruction(OpCodes.Isinst, "UnityEngine.Networking.ULocalConnectionToServer"), + new MockInstruction(OpCodes.Brfalse), + new MockInstruction(OpCodes.Ldstr), + new MockInstruction(OpCodes.Call, "System.Void UnityEngine.Debug::LogError(System.Object)"), + new MockInstruction(OpCodes.Ret) + ); + + WeaverILMatcher.MatchMethodIL(typeof(WeaverILGenerationTests_TargetRPCServerClientChecks), "CallTargetRpcTest", false, 1, 1, + new MockInstruction(OpCodes.Call, "System.Boolean UnityEngine.Networking.NetworkServer::get_active()"), + new MockInstruction(OpCodes.Brtrue), + new MockInstruction(OpCodes.Ldstr), + new MockInstruction(OpCodes.Call, "System.Void UnityEngine.Debug::LogError(System.Object)"), + new MockInstruction(OpCodes.Ret) + ); + } + + [Test] + public void RpcPassingEnumArrays() + { + WeaverILMatcher.MatchMethodIL(typeof(WeaverILGenerationTests_TargetRPCServerClientChecks), "CallRpcWithEnumArray", false, 1, 1, + new MockInstruction(OpCodes.Call, "System.Void Unity.GeneratedNetworkCode::_WriteArrayAttributeTargets_None(UnityEngine.Networking.NetworkWriter,System.AttributeTargets[])") + ); + } + + [Test] + public void SyncListsAreAutoInitializedInConstructor() + { + WeaverILMatcher.MatchMethodIL(typeof(WeaverILGenerationTests_SyncLists), ".ctor", false, 0, 1, + new MockInstruction(OpCodes.Ldarg_0), + new MockInstruction(OpCodes.Newobj, "System.Void UnityEngine.Networking.SyncListInt::.ctor()"), + new MockInstruction(OpCodes.Stfld, "UnityEngine.Networking.SyncListInt WeaverILGenerationTests_SyncLists::Inited") + ); + + /*WeaverILMatcher.MatchMethodIL(typeof(WeaverILGenerationTests_SyncLists), ".ctor", false, 0, 1, + new MockInstruction(OpCodes.Ldarg_0), + new MockInstruction(OpCodes.Newobj, "System.Void UnityEngine.Networking.SyncListInt::.ctor()"), + new MockInstruction(OpCodes.Stfld, "UnityEngine.Networking.SyncListInt WeaverILGenerationTests_SyncLists::NotInited") + );*/ + } + + [Test] + public void SyncListsAreOnlySerializedOnce() + { + WeaverILMatcher.MatchMethodIL(typeof(WeaverILGenerationTests_SyncLists), "OnSerialize", true, 2, 2, + new MockInstruction(OpCodes.Ldfld, "UnityEngine.Networking.SyncListInt WeaverILGenerationTests_SyncLists::Inited"), + new MockInstruction(OpCodes.Call, "System.Void UnityEngine.Networking.SyncListInt::WriteInstance(UnityEngine.Networking.NetworkWriter,UnityEngine.Networking.SyncListInt)") + ); + + /*WeaverILMatcher.MatchMethodIL(typeof(WeaverILGenerationTests_SyncLists), "OnSerialize", true, 2, 2, + new MockInstruction(OpCodes.Ldfld, "UnityEngine.Networking.SyncListInt WeaverILGenerationTests_SyncLists::NotInited"), + new MockInstruction(OpCodes.Call, "System.Void UnityEngine.Networking.SyncListInt::WriteInstance(UnityEngine.Networking.NetworkWriter,UnityEngine.Networking.SyncListInt)") + );*/ + } + + [Test] + public void SyncListsNetworkBehaviourWithSyncListCallsBaseClassAwakeMethod() + { + WeaverILMatcher.MatchMethodIL(typeof(WeaverILGenerationTests_SyncLists), "Awake", false, 0, 1, + new MockInstruction(OpCodes.Ldarg_0), + new MockInstruction(OpCodes.Call, "System.Void WeaverILGenerationTests_SyncLists_Base::Awake()") + ); + } + + [Test] + public void SyncNetworkBehaviourBaseClassPreStartClientMethodFromSubclass() + { + WeaverILMatcher.MatchMethodIL(typeof(WeaverILGenerationTests_SyncLists), "PreStartClient", false, 0, 1, + new MockInstruction(OpCodes.Ldarg_0), + new MockInstruction(OpCodes.Call, "System.Void WeaverILGenerationTests_SyncLists_Base::PreStartClient()") + ); + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Editor/WeaverILGenerationTests/WeaverILMatcher.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Editor/WeaverILGenerationTests/WeaverILMatcher.cs new file mode 100644 index 00000000..d209a329 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Editor/WeaverILGenerationTests/WeaverILMatcher.cs @@ -0,0 +1,164 @@ +using Mono.Cecil; +using System; +using System.Linq; +using System.Collections.Generic; +using NUnit.Framework; +using Mono.Cecil.Cil; +using UnityEngine; + +public struct MockInstruction +{ + public OpCode OpCode; + public object Operand; + + public MockInstruction(OpCode opCode) : this(opCode, null) + { + } + + public MockInstruction(OpCode opCode, object operand) + { + OpCode = opCode; + Operand = operand; + } + + public override string ToString() + { + if (Operand == null) + { + return OpCode.ToString(); + } + + if (Operand is String && OpCode == OpCodes.Ldstr) + { + return OpCode.ToString() + "\t\"" + Operand + " \""; + } + + return OpCode.ToString() + "\t" + Operand; + } +} + +public static class WeaverILMatcher +{ + static Dictionary AssemblyDefinitions; + static AssemblyDefinition AssemblyCSharp; + static AssemblyDefinition AssemblyCSharpEditortestable; + + static TypeDefinition GetTypeDef(Type type) + { + if (AssemblyDefinitions == null) + { + AssemblyDefinitions = new Dictionary(); + } + + AssemblyDefinition asmDef; + + if (AssemblyDefinitions.TryGetValue(type.Assembly.Location, out asmDef) == false) + { + // read up assembly + asmDef = AssemblyDefinition.ReadAssembly(type.Assembly.Location); + + // add to lookup so we don't need to read it every time + AssemblyDefinitions.Add(type.Assembly.Location, asmDef); + } + + var typeDef = asmDef.MainModule.Types.FirstOrDefault(x => x.FullName == type.FullName); + + Assert.NotNull(typeDef, "Could not find TypeDefinition for {0}", type); + + return typeDef; + } + + public static void MatchMethodIL(Type type, string method, int parameterCount, params MockInstruction[] match) + { + MatchMethodIL(type, method, false, parameterCount, 1, match); + } + + public static void MatchMethodIL(Type type, string method, bool hasReturnValue, int parameterCount, int matchCount, params MockInstruction[] match) + { + var typeDef = GetTypeDef(type); + var methodDef = typeDef.Methods.FirstOrDefault(x => x.Name == method && (x.ReturnType.Name != "Void") == hasReturnValue && x.Parameters.Count == parameterCount); + + Assert.NotNull(methodDef, "Could not find method {0} on type {1}", method, type); + + var matches = 0; + var instructions = methodDef.Body.Instructions.ToArray(); + + for (int i = 0; i < instructions.Length; ++i) + { + if (instructions[i].OpCode == match[0].OpCode) + { + if (MatchInstructions(instructions, i, match)) + { + // -1: means at least once, and don't check specific count + if (matchCount == -1) + { + return; + } + + ++matches; + } + } + } + + if (matches != matchCount) + { + Assert.Fail("Method {0} on type {1} did not match IL pattern exactly {3} times:\r\n{2}", method, type, string.Join("\r\n", match.Select(x => x.ToString()).ToArray()), matchCount); + } + } + + static bool MatchInstructions(Instruction[] instructions, int i, MockInstruction[] match) + { + for (int m = 0; m < match.Length; ++m) + { + // il out of bounds + if (m + i >= instructions.Length) + { + return false; + } + + var i_in = instructions[m + i]; + var m_in = match[m]; + + // miss-matching opcode + if (i_in.OpCode != m_in.OpCode) + { + return false; + } + + // special case when we pass a null-operand match value we only require the opcode to match + if (m_in.Operand == null) + { + continue; + } + + // miss-matching operand, expected an operand value but got none + if (i_in.Operand == null && m_in.Operand != null) + { + return false; + } + + // special case for "call/callvirt/newobj" verification where we match against a string instead of the actual MemberReference object + if ((m_in.OpCode == OpCodes.Call || m_in.OpCode == OpCodes.Callvirt || m_in.OpCode == OpCodes.Newobj || m_in.OpCode == OpCodes.Isinst || m_in.OpCode == OpCodes.Stfld || m_in.OpCode == OpCodes.Ldfld) && m_in.Operand is string) + { + if (i_in.Operand.ToString() != (string)m_in.Operand) + { + return false; + } + } + + // miss-matching operand type + if (i_in.Operand.GetType() != m_in.Operand.GetType()) + { + continue; + } + + // miss-matching operand value + if (i_in.Operand.Equals(m_in.Operand) == false) + { + return false; + } + } + + return true; + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Editor/com.unity.multiplayer-hlapi.EditorTests.asmdef b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Editor/com.unity.multiplayer-hlapi.EditorTests.asmdef new file mode 100644 index 00000000..59def3f0 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Editor/com.unity.multiplayer-hlapi.EditorTests.asmdef @@ -0,0 +1,19 @@ +{ + "name": "com.unity.multiplayer-hlapi.EditorTests", + "references": [ + "com.unity.multiplayer-hlapi.Editor", + "com.unity.multiplayer-hlapi.Runtime", + "com.unity.multiplayer-hlapi.Tests" + ], + "optionalUnityReferences": [ + "TestAssemblies" + ], + "includePlatforms": [ + "Editor" + ], + "excludePlatforms": [], + "overrideReferences": true, + "precompiledReferences": [ + "Mono.Cecil.dll" + ] +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/AuthorityOnSpawnedObjectsIsCorrect/AuthorityOnSpawnedObjectsIsCorrect.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/AuthorityOnSpawnedObjectsIsCorrect/AuthorityOnSpawnedObjectsIsCorrect.cs new file mode 100644 index 00000000..e02bb634 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/AuthorityOnSpawnedObjectsIsCorrect/AuthorityOnSpawnedObjectsIsCorrect.cs @@ -0,0 +1,40 @@ +using System.Collections; +using NUnit.Framework; +using UnityEngine.TestTools; +using UnityEngine; +using UnityEngine.Networking; + +#pragma warning disable 618 +public class AuthorityOnSpawnedObjectsIsCorrect +{ + public static bool isTestDone = false; + + [UnityTest] + public IEnumerator AuthorityOnSpawnedObjectsIsCorrectTest() + { + NetworkServer.Reset(); + NetworkClient.ShutdownAll(); + + GameObject nmObject = new GameObject(); + NetworkManager nmanager = nmObject.AddComponent(); + nmanager.playerPrefab = Resources.Load("PlayerWithAuthPrefab", typeof(GameObject)) as GameObject; + nmanager.spawnPrefabs.Add(Resources.Load("NoAuthObjPrefab", typeof(GameObject)) as GameObject); + nmanager.spawnPrefabs.Add(Resources.Load("AuthObjPrefab", typeof(GameObject)) as GameObject); + + Assert.IsNotNull(nmanager.playerPrefab, "Player prefab field is not set on NetworkManager"); + nmanager.StartHost(); + yield return null; + + Assert.IsTrue(NetworkServer.active, "Server is not active after StartHost"); + Assert.IsTrue(NetworkClient.active, "Client is not active after StartHost"); + + while (!isTestDone) + { + yield return null; + } + + nmanager.StopHost(); + Object.Destroy(nmObject); + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/AuthorityOnSpawnedObjectsIsCorrect/Resources/AuthObjPrefab.prefab b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/AuthorityOnSpawnedObjectsIsCorrect/Resources/AuthObjPrefab.prefab new file mode 100644 index 00000000..87fb62c7 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/AuthorityOnSpawnedObjectsIsCorrect/Resources/AuthObjPrefab.prefab @@ -0,0 +1,144 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!1001 &100100000 +Prefab: + m_ObjectHideFlags: 1 + serializedVersion: 2 + m_Modification: + m_TransformParent: {fileID: 0} + m_Modifications: [] + m_RemovedComponents: [] + m_ParentPrefab: {fileID: 0} + m_RootGameObject: {fileID: 1714307093068652} + m_IsPrefabParent: 1 +--- !u!1 &1714307093068652 +GameObject: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + serializedVersion: 5 + m_Component: + - component: {fileID: 4623073533655558} + - component: {fileID: 33667536636950200} + - component: {fileID: 23523400470116162} + - component: {fileID: 136575574917815900} + - component: {fileID: 114138697493695896} + - component: {fileID: 114274152422866264} + m_Layer: 0 + m_Name: AuthObjPrefab + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &4623073533655558 +Transform: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1714307093068652} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!23 &23523400470116162 +MeshRenderer: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1714307093068652} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RenderingLayerMask: 4294967295 + m_Materials: + - {fileID: 10303, guid: 0000000000000000f000000000000000, type: 0} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 +--- !u!33 &33667536636950200 +MeshFilter: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1714307093068652} + m_Mesh: {fileID: 10208, guid: 0000000000000000e000000000000000, type: 0} +--- !u!114 &114138697493695896 +MonoBehaviour: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1714307093068652} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 372142912, guid: dc443db3e92b4983b9738c1131f555cb, type: 3} + m_Name: + m_EditorClassIdentifier: + m_SceneId: + m_Value: 0 + m_AssetId: + i0: 251 + i1: 23 + i2: 188 + i3: 120 + i4: 171 + i5: 232 + i6: 172 + i7: 84 + i8: 203 + i9: 91 + i10: 249 + i11: 85 + i12: 216 + i13: 30 + i14: 114 + i15: 71 + m_ServerOnly: 0 + m_LocalPlayerAuthority: 1 +--- !u!114 &114274152422866264 +MonoBehaviour: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1714307093068652} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 7a63ea60b3539fc4a8a5aabd04005e05, type: 3} + m_Name: + m_EditorClassIdentifier: +--- !u!136 &136575574917815900 +CapsuleCollider: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1714307093068652} + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_Enabled: 1 + m_Radius: 0.5 + m_Height: 2 + m_Direction: 1 + m_Center: {x: 0, y: 0, z: 0} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/AuthorityOnSpawnedObjectsIsCorrect/Resources/AuthSpawnableObject.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/AuthorityOnSpawnedObjectsIsCorrect/Resources/AuthSpawnableObject.cs new file mode 100644 index 00000000..086c515c --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/AuthorityOnSpawnedObjectsIsCorrect/Resources/AuthSpawnableObject.cs @@ -0,0 +1,18 @@ +using NUnit.Framework; +using UnityEngine.Networking; + +#pragma warning disable 618 +public class AuthSpawnableObject : NetworkBehaviour +{ + // this object is spawned with client Authority + public override void OnStartAuthority() + { + Assert.IsTrue(hasAuthority); + } + + public override void OnStopAuthority() + { + Assert.Fail("OnStopAuthority on AuthSpawnableObject should not be called"); + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/AuthorityOnSpawnedObjectsIsCorrect/Resources/NoAuthObjPrefab.prefab b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/AuthorityOnSpawnedObjectsIsCorrect/Resources/NoAuthObjPrefab.prefab new file mode 100644 index 00000000..e4390550 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/AuthorityOnSpawnedObjectsIsCorrect/Resources/NoAuthObjPrefab.prefab @@ -0,0 +1,143 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!1001 &100100000 +Prefab: + m_ObjectHideFlags: 1 + serializedVersion: 2 + m_Modification: + m_TransformParent: {fileID: 0} + m_Modifications: [] + m_RemovedComponents: [] + m_ParentPrefab: {fileID: 0} + m_RootGameObject: {fileID: 1458795156556284} + m_IsPrefabParent: 1 +--- !u!1 &1458795156556284 +GameObject: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + serializedVersion: 5 + m_Component: + - component: {fileID: 4966032680941340} + - component: {fileID: 33729123460419368} + - component: {fileID: 23087036340302866} + - component: {fileID: 135227808896565270} + - component: {fileID: 114873357703664714} + - component: {fileID: 114579196398650772} + m_Layer: 0 + m_Name: NoAuthObjPrefab + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &4966032680941340 +Transform: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1458795156556284} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!23 &23087036340302866 +MeshRenderer: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1458795156556284} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RenderingLayerMask: 4294967295 + m_Materials: + - {fileID: 10303, guid: 0000000000000000f000000000000000, type: 0} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 +--- !u!33 &33729123460419368 +MeshFilter: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1458795156556284} + m_Mesh: {fileID: 10207, guid: 0000000000000000e000000000000000, type: 0} +--- !u!114 &114579196398650772 +MonoBehaviour: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1458795156556284} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: a8305c0bafcd2604fb3d8545b4092f56, type: 3} + m_Name: + m_EditorClassIdentifier: +--- !u!114 &114873357703664714 +MonoBehaviour: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1458795156556284} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 372142912, guid: dc443db3e92b4983b9738c1131f555cb, type: 3} + m_Name: + m_EditorClassIdentifier: + m_SceneId: + m_Value: 0 + m_AssetId: + i0: 24 + i1: 243 + i2: 216 + i3: 106 + i4: 30 + i5: 240 + i6: 1 + i7: 36 + i8: 136 + i9: 154 + i10: 34 + i11: 217 + i12: 11 + i13: 189 + i14: 16 + i15: 150 + m_ServerOnly: 0 + m_LocalPlayerAuthority: 1 +--- !u!135 &135227808896565270 +SphereCollider: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1458795156556284} + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_Enabled: 1 + serializedVersion: 2 + m_Radius: 0.5 + m_Center: {x: 0, y: 0, z: 0} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/AuthorityOnSpawnedObjectsIsCorrect/Resources/NoAuthSpawnableObject.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/AuthorityOnSpawnedObjectsIsCorrect/Resources/NoAuthSpawnableObject.cs new file mode 100644 index 00000000..1613c19f --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/AuthorityOnSpawnedObjectsIsCorrect/Resources/NoAuthSpawnableObject.cs @@ -0,0 +1,24 @@ +using NUnit.Framework; +using UnityEngine.Networking; + +#pragma warning disable 618 +public class NoAuthSpawnableObject : NetworkBehaviour +{ + // this object is spawned without client Authority, then set + public override void OnStartClient() + { + Assert.IsFalse(hasAuthority); + } + + public override void OnStartAuthority() + { + Assert.IsTrue(hasAuthority); + } + + public override void OnStopAuthority() + { + Assert.IsFalse(hasAuthority); + AuthorityOnSpawnedObjectsIsCorrect.isTestDone = true; + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/AuthorityOnSpawnedObjectsIsCorrect/Resources/PlayerWithAuthPrefab.prefab b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/AuthorityOnSpawnedObjectsIsCorrect/Resources/PlayerWithAuthPrefab.prefab new file mode 100644 index 00000000..13d9685f --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/AuthorityOnSpawnedObjectsIsCorrect/Resources/PlayerWithAuthPrefab.prefab @@ -0,0 +1,147 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!1001 &100100000 +Prefab: + m_ObjectHideFlags: 1 + serializedVersion: 2 + m_Modification: + m_TransformParent: {fileID: 0} + m_Modifications: [] + m_RemovedComponents: [] + m_ParentPrefab: {fileID: 0} + m_RootGameObject: {fileID: 1605537484536220} + m_IsPrefabParent: 1 +--- !u!1 &1605537484536220 +GameObject: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + serializedVersion: 5 + m_Component: + - component: {fileID: 4852699654151406} + - component: {fileID: 33082284501209378} + - component: {fileID: 23252609606156378} + - component: {fileID: 65920616948593688} + - component: {fileID: 114205998322145600} + - component: {fileID: 114538045202614566} + m_Layer: 0 + m_Name: PlayerWithAuthPrefab + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &4852699654151406 +Transform: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1605537484536220} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!23 &23252609606156378 +MeshRenderer: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1605537484536220} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RenderingLayerMask: 4294967295 + m_Materials: + - {fileID: 10303, guid: 0000000000000000f000000000000000, type: 0} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 +--- !u!33 &33082284501209378 +MeshFilter: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1605537484536220} + m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0} +--- !u!65 &65920616948593688 +BoxCollider: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1605537484536220} + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_Enabled: 1 + serializedVersion: 2 + m_Size: {x: 1, y: 1, z: 1} + m_Center: {x: 0, y: 0, z: 0} +--- !u!114 &114205998322145600 +MonoBehaviour: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1605537484536220} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 372142912, guid: dc443db3e92b4983b9738c1131f555cb, type: 3} + m_Name: + m_EditorClassIdentifier: + m_SceneId: + m_Value: 0 + m_AssetId: + i0: 85 + i1: 52 + i2: 183 + i3: 35 + i4: 254 + i5: 90 + i6: 182 + i7: 228 + i8: 25 + i9: 2 + i10: 97 + i11: 94 + i12: 194 + i13: 7 + i14: 60 + i15: 95 + m_ServerOnly: 0 + m_LocalPlayerAuthority: 1 +--- !u!114 &114538045202614566 +MonoBehaviour: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1605537484536220} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 385cfd3170b11b64aa9cbd23d6b0489f, type: 3} + m_Name: + m_EditorClassIdentifier: + objAuthPrefab: {fileID: 1714307093068652, guid: fb17bc78abe8ac54cb5bf955d81e7247, + type: 2} + objNoAuthPrefab: {fileID: 1458795156556284, guid: 18f3d86a1ef00124889a22d90bbd1096, + type: 2} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/AuthorityOnSpawnedObjectsIsCorrect/Resources/PlayerWithAuthority.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/AuthorityOnSpawnedObjectsIsCorrect/Resources/PlayerWithAuthority.cs new file mode 100644 index 00000000..ce7ca13b --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/AuthorityOnSpawnedObjectsIsCorrect/Resources/PlayerWithAuthority.cs @@ -0,0 +1,47 @@ +using UnityEngine; +using NUnit.Framework; +using UnityEngine.Networking; + +#pragma warning disable 618 +public class PlayerWithAuthority : NetworkBehaviour +{ + GameObject spawned; + public GameObject objAuthPrefab; + public GameObject objNoAuthPrefab; + + public override void OnStartAuthority() + { + Assert.IsTrue(hasAuthority); + } + + public override void OnStartLocalPlayer() + { + Assert.IsTrue(hasAuthority); + Assert.IsTrue(isLocalPlayer); + + CmdSpawnObj(); + } + + [Command] + void CmdSpawnObj() + { + // spawn auth object + var objAuth = (GameObject)Instantiate(objAuthPrefab, Vector3.zero, objAuthPrefab.transform.rotation); + NetworkServer.SpawnWithClientAuthority(objAuth, connectionToClient); + + // spawn no auth object + var objNoAuth = (GameObject)Instantiate(objNoAuthPrefab, Vector3.zero, objNoAuthPrefab.transform.rotation); + NetworkServer.Spawn(objNoAuth); + + objNoAuth.GetComponent().AssignClientAuthority(connectionToClient); + + spawned = objNoAuth; + Invoke("RemoveAuthority", 0.1f); + } + + void RemoveAuthority() + { + spawned.GetComponent().RemoveClientAuthority(connectionToClient); + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/ChannelBufferHandlesOverflow/ChannelBufferHandlesOverflow.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/ChannelBufferHandlesOverflow/ChannelBufferHandlesOverflow.cs new file mode 100644 index 00000000..162997ed --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/ChannelBufferHandlesOverflow/ChannelBufferHandlesOverflow.cs @@ -0,0 +1,88 @@ +using System.Collections; +using NUnit.Framework; +using UnityEngine.TestTools; +using UnityEngine; +using UnityEngine.Networking; + +#pragma warning disable 618 +public class ChannelBufferHandlesOverflow +{ + int kListenPort = 7073; + const int kPacketSize = 1000; + const short kMsgId = 155; + const int kNumMsgs = 14000; + + NetworkClient myClient; + + bool isTestDone; + + [UnityTest] + public IEnumerator ChannelBufferHandlesOverflowTest() + { + NetworkServer.Reset(); + NetworkClient.ShutdownAll(); + + ConnectionConfig config = new ConnectionConfig(); + config.AddChannel(QosType.ReliableSequenced); + config.AddChannel(QosType.Unreliable); + + myClient = new NetworkClient(); + if (!myClient.Configure(config, 10)) + { + Assert.Fail("Client configure failed"); + } + + NetworkServer.RegisterHandler(kMsgId, OnServerMsg); + myClient.RegisterHandler(MsgType.Connect, OnClientConnected); + + int retries = 0; + while (!NetworkServer.Listen("127.0.0.1", ++kListenPort)) + { + Assert.IsTrue(retries++ < 10, "Couldn't Listen for more than 10 retries"); + } + + myClient.Connect("127.0.0.1", kListenPort); + + while (!isTestDone) + { + yield return null; + } + //Debug.Log("Shutting down"); + //NetworkServer.DisconnectAll(); + //NetworkClient.ShutdownAll(); + //NetworkTransport.Shutdown(); + + yield return null; + } + + public void OnServerMsg(NetworkMessage netMsg) + { + //need this method simply to prevent "Unknown ID" error message + } + + public void OnClientConnected(NetworkMessage netMsg) + { + NetworkWriter writer = new NetworkWriter(); + writer.StartMessage(kMsgId); + byte[] data = new byte[kPacketSize]; + writer.Write(data, kPacketSize); + writer.FinishMessage(); + LogAssert.Expect(LogType.Error, "ChannelBuffer buffer limit of 16 packets reached."); + + // these messages do not all fit in the transport layer send queue. + // to be recieved on the server, they must be buffered by HLAPI + bool gotFailure = false; + for (int i = 0; i < kNumMsgs; i++) + { + if (!myClient.SendWriter(writer, Channels.DefaultReliable)) + { + gotFailure = true; + break; + } + } + + Assert.AreEqual(true, gotFailure); + isTestDone = true; + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/ClientCanConnectAfterFailure/ClientCanConnectAfterFailure.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/ClientCanConnectAfterFailure/ClientCanConnectAfterFailure.cs new file mode 100644 index 00000000..123e1750 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/ClientCanConnectAfterFailure/ClientCanConnectAfterFailure.cs @@ -0,0 +1,104 @@ +using System.Collections; +using NUnit.Framework; +using UnityEngine.TestTools; +using UnityEngine; +using UnityEngine.Networking; + +#pragma warning disable 618 +public class ClientCanConnectAfterFailure +{ + int kListenPort = 7073; + NetworkClient client1; + NetworkClient client2; + bool isClientConnected = false; + bool serverRecievedConnection = false; + ConnectionConfig config; + + bool isTestDone; + + [UnityTest] + public IEnumerator ClientCanConnectAfterFailureTest() + { + NetworkClient.ShutdownAll(); + NetworkServer.Reset(); + + NetworkServer.RegisterHandler(MsgType.Connect, OnServerConnected); + + config = new ConnectionConfig(); + config.AddChannel(QosType.ReliableFragmented); + if (!NetworkServer.Configure(config, 10)) + { + Assert.Fail("Server configure failed"); + } + + // Mismatched channels between client 1 and server, so connect will fail with CRCMismatch error + ConnectionConfig customConfig = new ConnectionConfig(); + customConfig.AddChannel(QosType.UnreliableFragmented); + + client1 = new NetworkClient(); + if (!client1.Configure(customConfig, 10)) + { + Assert.Fail("Client1 configure failed"); + } + + client1.RegisterHandler(MsgType.Connect, OnClient1Connected); + client1.RegisterHandler(MsgType.Disconnect, OnClient1Disconnected); + + int retries = 0; + while (!NetworkServer.Listen("127.0.0.1", ++kListenPort)) + { + Assert.IsTrue(retries++ < 10, "Couldn't Listen for more than 10 retries"); + } + + LogAssert.Expect(LogType.Error, "UNet Client Disconnect Error: CRCMismatch"); + client1.Connect("127.0.0.1", kListenPort); + + while (!serverRecievedConnection || !isClientConnected) + { + yield return null; + } + + NetworkServer.DisconnectAll(); + + while (!isTestDone) + { + yield return null; + } + } + + public void OnServerConnected(NetworkMessage netMsg) + { + serverRecievedConnection = true; + } + + public void OnClient1Connected(NetworkMessage netMsg) + { + Assert.Fail("Client1 connection should not happen"); + } + + public void OnClient1Disconnected(NetworkMessage netMsg) + { + client2 = new NetworkClient(); + if (!client2.Configure(config, 10)) + { + Assert.Fail("Client2 configure failed"); + } + + client2.RegisterHandler(MsgType.Connect, OnClient2Connected); + client2.RegisterHandler(MsgType.Disconnect, OnClient2Disconnected); + client2.Connect("127.0.0.1", kListenPort); + } + + public void OnClient2Connected(NetworkMessage netMsg) + { + isClientConnected = true; + } + + public void OnClient2Disconnected(NetworkMessage netMsg) + { + Assert.IsTrue(serverRecievedConnection); + Assert.IsTrue(isClientConnected); + isTestDone = true; + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/CommandsAndRPCCallsWork/CommandsAndRPCCallsWork.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/CommandsAndRPCCallsWork/CommandsAndRPCCallsWork.cs new file mode 100644 index 00000000..11225e9b --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/CommandsAndRPCCallsWork/CommandsAndRPCCallsWork.cs @@ -0,0 +1,225 @@ +using System; +using System.Collections; +using NUnit.Framework; +using UnityEngine.TestTools; +using UnityEngine; +using UnityEngine.Networking; +using Object = UnityEngine.Object; + +#pragma warning disable 618 +public class CommandsAndRPCCallsWork +{ + int kListenPort = 7073; + NetworkClient myClient; + static bool isTestDone; + + static NetworkHash128 playerHash = NetworkHash128.Parse("abcd1"); + + public static GameObject OnSpawnPlayer(Vector3 pos, NetworkHash128 assetId) + { + try + { + GameObject serverPlayer = new GameObject(); + serverPlayer.name = "MyPlayer"; + serverPlayer.AddComponent(); + serverPlayer.AddComponent(); + return serverPlayer; + } + catch (Exception e) + { + Assert.Fail("Spawn exception " + e); + return null; + } + } + + public static void OnUnSpawnPlayer(GameObject unspawned) + { + Object.Destroy(unspawned); + } + + [UnityTest] + public IEnumerator CommandsAndRPCCallsWorkTest() + { + NetworkClient.ShutdownAll(); + NetworkServer.Reset(); + + ConnectionConfig config = new ConnectionConfig(); + config.AddChannel(QosType.ReliableSequenced);// this test requires correct sequence of packets. + config.AddChannel(QosType.Unreliable); + + myClient = new NetworkClient(); + if (!myClient.Configure(config, 10)) + { + Assert.Fail("Client configure failed"); + } + + NetworkServer.RegisterHandler(MsgType.AddPlayer, OnAddPlayer); + myClient.RegisterHandler(MsgType.Connect, OnClientConnected); + myClient.RegisterHandler(MsgType.Error, OnClientError); + ClientScene.RegisterSpawnHandler(playerHash, OnSpawnPlayer, OnUnSpawnPlayer); + + int retries = 0; + while (!NetworkServer.Listen("127.0.0.1", ++kListenPort)) + { + Assert.IsTrue(retries++ < 10, "Couldn't Listen for more than 10 retries"); + } + + myClient.Connect("127.0.0.1", kListenPort); + + while (!isTestDone) + { + yield return null; + } + } + + public void OnAddPlayer(NetworkMessage netMsg) + { + var msg = netMsg.ReadMessage(); + + GameObject obj = OnSpawnPlayer(Vector3.zero, playerHash); + NetworkServer.AddPlayerForConnection(netMsg.conn, obj, msg.playerControllerId, playerHash); + + CommandTestPlayerBehaviour beh = obj.GetComponent(); + Assert.IsNotNull(beh, "No component CommandTestPlayerBehaviour"); + + string args = "foo"; + beh.RpcTestOnClient(args); + + beh.TargetTestOnOne(netMsg.conn, "one"); + } + + public void OnClientConnected(NetworkMessage netMsg) + { + ClientScene.AddPlayer(netMsg.conn, 1); + } + + public void OnClientError(NetworkMessage netMsg) + { + Assert.Fail("Connect Error"); + } + + // extra NetworkBehaviour component on the player, to check for multiple NetworkBehaviour issues + public class CommandTestPlayerBehaviourExtra : NetworkBehaviour + { + [SyncVar] + int extraData; + } + + public class CommandTestPlayerBehaviour : NetworkBehaviour + { + public struct Inner + { + public string aString; + public double aDouble; + } + public struct Outer + { + public float aFloat; + public int aInt; + public Inner aInner; + } + + public static int numEvents = 0; + + public delegate void IntegerEventDelegate(int value); + + private int testInt = 77; + private float testFloat = 55.5f; + private int testValue = 100; + private int testCmdCount = 0; + private int testCmdValidate = 0; + + [SyncEvent] + public event IntegerEventDelegate EventDoInt1; + + [SyncEvent] + public event IntegerEventDelegate EventDoInt2; + + void Awake() + { + // test multiple events in this script + EventDoInt1 += OnIntegerEvent1; + EventDoInt1 += OnIntegerEvent2; + + EventDoInt2 += OnIntegerEvent2; + } + + void OnIntegerEvent1(int value) + { + Debug.Log("OnIntegerEvent1"); + Assert.AreEqual(testValue, value); + numEvents += 1; + } + + void OnIntegerEvent2(int value) + { + Debug.Log("OnIntegerEvent2"); + Assert.AreEqual(testValue, value); + numEvents += 1; + } + + private void Update() + { + // 3 = 2 events from EventDo1 + 1 event from EventDo2 + if (numEvents == 3 && isClient) + { + // this tests that all commands arrive in the correct order + CmdCount(testCmdCount++); + if (testCmdCount == 100) + { + isTestDone = true; + } + + Outer outer = new Outer(); + outer.aInt = 99; + outer.aInner = new Inner(); + outer.aInner.aDouble = 1.2; + CmdDoOuter(outer); + } + } + + [Command] + void CmdCount(int count) + { + Assert.AreEqual(count, testCmdValidate++); + } + + [Command] + void CmdDoOuter(Outer outer) + { + Assert.AreEqual(99, outer.aInt); + Assert.AreEqual(1.2, outer.aInner.aDouble, 0.001); + } + + [Command] + public void CmdTestCommandOnServer(int arg1, float arg2) + { + Assert.AreEqual(testInt, arg1); + Assert.AreEqual(testFloat, arg2); + + if (EventDoInt1 != null) + { + EventDoInt1(testValue); + } + + if (EventDoInt2 != null) + { + EventDoInt2(testValue); + } + } + + [TargetRpc] + public void TargetTestOnOne(NetworkConnection target, string arg) + { + Assert.AreEqual(arg, "one"); + } + + [ClientRpc] + public void RpcTestOnClient(string arg) + { + Assert.AreEqual(arg, "foo"); + CmdTestCommandOnServer(testInt, testFloat); + } + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/ConnectLocalClientWorks/ConnectLocalClientWorks.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/ConnectLocalClientWorks/ConnectLocalClientWorks.cs new file mode 100644 index 00000000..44585204 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/ConnectLocalClientWorks/ConnectLocalClientWorks.cs @@ -0,0 +1,106 @@ +using System.Collections; +using NUnit.Framework; +using UnityEngine.TestTools; +using UnityEngine; +using UnityEngine.Networking; + +#pragma warning disable 618 +public class ConnectLocalClientWorks +{ + const int kMsgTest = 555; + const int kMsgTest2 = 556; + bool isTestDone; + + public class TestMessage : MessageBase + { + public int number; + public string str; + }; + + [UnityTest] + public IEnumerator ConnectLocalClientWorksTest() + { + NetworkClient.ShutdownAll(); + NetworkServer.Reset(); + + NetworkServer.RegisterHandler(MsgType.Connect, OnServerConnected); + NetworkServer.RegisterHandler(MsgType.AddPlayer, OnAddPlayer); + NetworkServer.RegisterHandler(kMsgTest, OnServerTestMsg); + + NetworkServer.Listen(9999); + NetworkClient client = ClientScene.ConnectLocalServer(); + + client.RegisterHandler(MsgType.Connect, OnClientConnected); + client.RegisterHandler(MsgType.Disconnect, OnClientDisconnected); + client.RegisterHandler(kMsgTest, OnClientTestMsg); + client.RegisterHandler(kMsgTest2, OnClientTestMsg2); + + while (!isTestDone) + { + yield return null; + } + } + + public void OnServerConnected(NetworkMessage netMsg) + { + Debug.Log("Server received client connection."); + } + + public void OnAddPlayer(NetworkMessage netMsg) + { + GameObject go = new GameObject(); + go.AddComponent(); + NetworkServer.AddPlayerForConnection(netMsg.conn, go, 0); + + TestMessage outMsg = new TestMessage(); + outMsg.number = 99; + outMsg.str = "addPlayer"; + NetworkServer.SendToAll(kMsgTest2, outMsg); + } + + public void OnClientConnected(NetworkMessage netMsg) + { + Debug.Log("Client connected to server."); + + TestMessage msg = new TestMessage(); + msg.number = 77; + msg.str = "testFromClient"; + + NetworkClient.allClients[0].Send(kMsgTest, msg); + } + + public void OnServerTestMsg(NetworkMessage netMsg) + { + TestMessage msg = netMsg.ReadMessage(); + Assert.AreEqual(77, msg.number); + Assert.AreEqual("testFromClient", msg.str); + + TestMessage outMsg = new TestMessage(); + outMsg.number = 99; + outMsg.str = "testFromServer"; + + NetworkServer.SendToAll(kMsgTest, outMsg); + } + + public void OnClientTestMsg(NetworkMessage netMsg) + { + Debug.Log("Client received test message"); + TestMessage msg = netMsg.ReadMessage(); + Assert.AreEqual(99, msg.number); + Assert.AreEqual("testFromServer", msg.str); + ClientScene.AddPlayer(netMsg.conn, 0); + } + + public void OnClientTestMsg2(NetworkMessage netMsg) + { + Assert.AreEqual(ClientScene.localPlayers.Count, 1); + NetworkClient.allClients[0].Disconnect(); + } + + public void OnClientDisconnected(NetworkMessage netMsg) + { + Debug.Log("Client disconnected from server."); + isTestDone = true; + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/ConnectWithDNSWorks/ConnectWithDNSWorks.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/ConnectWithDNSWorks/ConnectWithDNSWorks.cs new file mode 100644 index 00000000..fdd66e49 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/ConnectWithDNSWorks/ConnectWithDNSWorks.cs @@ -0,0 +1,82 @@ +using System.Collections; +using NUnit.Framework; +using UnityEngine.TestTools; +using UnityEngine; +using UnityEngine.Networking; + +#pragma warning disable 618 +public class ConnectWithDNSWorks +{ + int kListenPort = 7073; + int steps = 0; + + [UnityTest] + public IEnumerator ConnectWithDNSWorksTest() + { + NetworkServer.Reset(); + NetworkClient.ShutdownAll(); + + ConnectionConfig config = new ConnectionConfig(); + config.AddChannel(QosType.ReliableSequenced); + config.AddChannel(QosType.Unreliable); + + NetworkClient client1 = new NetworkClient(); + if (!client1.Configure(config, 20)) + { + Assert.Fail("client1 configure failed"); + } + client1.RegisterHandler(MsgType.Error, OnError1); + + NetworkClient client2 = new NetworkClient(); + if (!client2.Configure(config, 20)) + { + Assert.Fail("client2 configure failed"); + } + client2.RegisterHandler(MsgType.Connect, OnConnectIncrementStep); + + NetworkClient client3 = new NetworkClient(); + if (!client3.Configure(config, 20)) + { + Assert.Fail("client3 configure failed"); + } + client3.RegisterHandler(MsgType.Connect, OnConnectIncrementStep); + + int retries = 0; + while (!NetworkServer.Listen("127.0.0.1", ++kListenPort)) + { + Assert.IsTrue(retries++ < 10, "Couldn't Listen for more than 10 retries"); + } + + // wait for errors from client1 +#if PLATFORM_WINRT && !ENABLE_IL2CPP + LogAssert.Expect(LogType.Error, "DNS resolution failed: HostNotFound"); + LogAssert.Expect(LogType.Error, "UNet Client Error Connect Error: 11"); +#else + LogAssert.Expect(LogType.Error, "DNS resolution failed: 11001"); + LogAssert.Expect(LogType.Error, "UNet Client Error Connect Error: 11"); +#endif + client1.Connect("444.555.444.333", kListenPort); + + // These are successful and should increment the step counter + client2.Connect("localhost", kListenPort); + client3.Connect("127.0.0.1", kListenPort); + + while (steps < 3) + { + yield return null; + } + } + + void OnError1(NetworkMessage netMsg) + { + UnityEngine.Networking.NetworkSystem.ErrorMessage msg = netMsg.ReadMessage(); + Assert.AreEqual(NetworkError.DNSFailure, (NetworkError)msg.errorCode); + steps += 1; + } + + void OnConnectIncrementStep(NetworkMessage netMsg) + { + steps += 1; + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/DisconnectAllWorks/DisconnectAllWorks.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/DisconnectAllWorks/DisconnectAllWorks.cs new file mode 100644 index 00000000..667ac144 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/DisconnectAllWorks/DisconnectAllWorks.cs @@ -0,0 +1,77 @@ +using System.Collections; +using NUnit.Framework; +using UnityEngine.TestTools; +using UnityEngine; +using UnityEngine.Networking; + +#pragma warning disable 618 +public class DisconnectAllWorks +{ + int kListenPort = 7073; + int maxConnections = 10; + int numClients = 5; + int clientsConnected = 0; + int serverConnections = 0; + int clientsDisccnnected = 0; + + [UnityTest] + public IEnumerator DisconnectAllWorksTest() + { + NetworkClient.ShutdownAll(); + NetworkServer.Reset(); + + ConnectionConfig config = new ConnectionConfig(); + config.AddChannel(QosType.ReliableSequenced); + config.AddChannel(QosType.Unreliable); + + NetworkServer.Configure(config, maxConnections); + NetworkServer.RegisterHandler(MsgType.Connect, OnServerConnected); + + int retries = 0; + while (!NetworkServer.Listen("127.0.0.1", ++kListenPort)) + { + Assert.IsTrue(retries++ < 10, "Couldn't Listen for more than 10 retries"); + } + + for (int i = 0; i < numClients; ++i) + { + NetworkClient myClient = new NetworkClient(); + if (!myClient.Configure(config, maxConnections)) + { + Assert.Fail("Client configure failed"); + } + myClient.RegisterHandler(MsgType.Connect, OnClientConnected); + myClient.RegisterHandler(MsgType.Disconnect, OnClientDisconnected); + myClient.Connect("127.0.0.1", kListenPort); + } + + while (serverConnections != numClients || clientsConnected != numClients) + { + yield return null; + } + NetworkServer.DisconnectAll(); + + while (clientsDisccnnected != numClients) + { + yield return null; + } + + Assert.IsTrue(NetworkServer.active, "NetworkServer should still be active after DisconnectAll()"); + } + + public void OnServerConnected(NetworkMessage netMsg) + { + serverConnections += 1; + } + + public void OnClientConnected(NetworkMessage netMsg) + { + clientsConnected += 1; + } + + public void OnClientDisconnected(NetworkMessage netMsg) + { + clientsDisccnnected += 1; + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/GetCurrentRTTCallDoesntCrashWhenUseWebSockets/GetCurrentRTTCallDoesntCrashWhenUseWebSockets.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/GetCurrentRTTCallDoesntCrashWhenUseWebSockets/GetCurrentRTTCallDoesntCrashWhenUseWebSockets.cs new file mode 100644 index 00000000..cf9287c3 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/GetCurrentRTTCallDoesntCrashWhenUseWebSockets/GetCurrentRTTCallDoesntCrashWhenUseWebSockets.cs @@ -0,0 +1,46 @@ +using System.Collections; +using UnityEngine.TestTools; +using NUnit.Framework; +using UnityEngine; +using UnityEngine.Networking; + +#pragma warning disable 618 +public class GetCurrentRTTCallDoesntCrashWhenUseWebSockets +{ + [UnityTest] + [UnityPlatform(RuntimePlatform.WindowsPlayer)] + [UnityPlatform(RuntimePlatform.LinuxPlayer)] + [UnityPlatform(RuntimePlatform.OSXPlayer)] + public IEnumerator GetCurrentRTTCallDoesntCrashWhenUseWebSocketsTest() + { + NetworkClient.ShutdownAll(); + NetworkServer.Reset(); + + GameObject nmObject = new GameObject(); + NetworkManager nmanager = nmObject.AddComponent(); + nmanager.playerPrefab = Resources.Load("GetCurrentRTTCallDoesntCrashWhenUseWebSockets_PlayerPrefab", typeof(GameObject)) as GameObject; + nmanager.networkAddress = "localhost"; + nmanager.useWebSockets = true; + + LogAssert.Expect(LogType.Error, "the function called has not been supported for web sockets communication"); + nmanager.StartHost(); + yield return null; + + Assert.IsTrue(NetworkServer.active, "Server is not active after StartHost"); + Assert.IsTrue(NetworkClient.active, "Client is not active after StartHost"); + + yield return null; + GameObject player = GameObject.Find("GetCurrentRTTCallDoesntCrashWhenUseWebSockets_PlayerPrefab(Clone)"); + + while (!player.GetComponent().isDone) + { + yield return null; + } + nmanager.StopHost(); + yield return null; + Assert.IsNull(GameObject.Find("GetCurrentRTTCallDoesntCrashWhenUseWebSockets_PlayerPrefab(Clone)"), "PlayerPrefab(Clone) object should be destroyed after calling StopHost"); + + Object.Destroy(nmObject); + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/GetCurrentRTTCallDoesntCrashWhenUseWebSockets/Resources/GetCurrentRTTCallDoesntCrashWhenUseWebSockets_PlayerPrefab.prefab b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/GetCurrentRTTCallDoesntCrashWhenUseWebSockets/Resources/GetCurrentRTTCallDoesntCrashWhenUseWebSockets_PlayerPrefab.prefab new file mode 100644 index 00000000..5a2c47dc --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/GetCurrentRTTCallDoesntCrashWhenUseWebSockets/Resources/GetCurrentRTTCallDoesntCrashWhenUseWebSockets_PlayerPrefab.prefab @@ -0,0 +1,144 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!1001 &100100000 +Prefab: + m_ObjectHideFlags: 1 + serializedVersion: 2 + m_Modification: + m_TransformParent: {fileID: 0} + m_Modifications: [] + m_RemovedComponents: [] + m_ParentPrefab: {fileID: 0} + m_RootGameObject: {fileID: 1902095678767368} + m_IsPrefabParent: 1 +--- !u!1 &1902095678767368 +GameObject: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + serializedVersion: 5 + m_Component: + - component: {fileID: 4934951114835214} + - component: {fileID: 33422791935304546} + - component: {fileID: 23298508799286280} + - component: {fileID: 65564879027641614} + - component: {fileID: 114483071129414552} + - component: {fileID: 114330367389354536} + m_Layer: 0 + m_Name: GetCurrentRTTCallDoesntCrashWhenUseWebSockets_PlayerPrefab + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &4934951114835214 +Transform: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1902095678767368} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!23 &23298508799286280 +MeshRenderer: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1902095678767368} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RenderingLayerMask: 4294967295 + m_Materials: + - {fileID: 10303, guid: 0000000000000000f000000000000000, type: 0} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 +--- !u!33 &33422791935304546 +MeshFilter: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1902095678767368} + m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0} +--- !u!65 &65564879027641614 +BoxCollider: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1902095678767368} + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_Enabled: 1 + serializedVersion: 2 + m_Size: {x: 1, y: 1, z: 1} + m_Center: {x: 0, y: 0, z: 0} +--- !u!114 &114330367389354536 +MonoBehaviour: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1902095678767368} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 70fd9431a22924742bf19e22aeeaa118, type: 3} + m_Name: + m_EditorClassIdentifier: + isDone: 0 +--- !u!114 &114483071129414552 +MonoBehaviour: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1902095678767368} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 372142912, guid: dc443db3e92b4983b9738c1131f555cb, type: 3} + m_Name: + m_EditorClassIdentifier: + m_SceneId: + m_Value: 0 + m_AssetId: + i0: 84 + i1: 129 + i2: 11 + i3: 217 + i4: 137 + i5: 118 + i6: 55 + i7: 228 + i8: 153 + i9: 20 + i10: 82 + i11: 183 + i12: 249 + i13: 172 + i14: 186 + i15: 19 + m_ServerOnly: 0 + m_LocalPlayerAuthority: 1 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/GetCurrentRTTCallDoesntCrashWhenUseWebSockets/UnetPlayerWithGetCurrentRTTCallScript.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/GetCurrentRTTCallDoesntCrashWhenUseWebSockets/UnetPlayerWithGetCurrentRTTCallScript.cs new file mode 100644 index 00000000..7ef8565e --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/GetCurrentRTTCallDoesntCrashWhenUseWebSockets/UnetPlayerWithGetCurrentRTTCallScript.cs @@ -0,0 +1,19 @@ +using UnityEngine.Networking; + +#pragma warning disable 618 +public class UnetPlayerWithGetCurrentRTTCallScript : NetworkBehaviour +{ + public bool isDone; + + public void Start() + { + byte error; + if (isServer) + { + NetworkTransport.GetCurrentRTT(NetworkServer.serverHostId, connectionToClient.connectionId, out error); + if ((NetworkError)error != NetworkError.Ok) + isDone = true; + } + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/HavingManyLocalClientsSimultaneouslyWorks/HavingManyLocalClientsSimultaneouslyWorks.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/HavingManyLocalClientsSimultaneouslyWorks/HavingManyLocalClientsSimultaneouslyWorks.cs new file mode 100644 index 00000000..3631ec7e --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/HavingManyLocalClientsSimultaneouslyWorks/HavingManyLocalClientsSimultaneouslyWorks.cs @@ -0,0 +1,96 @@ +using System.Collections; +using NUnit.Framework; +using UnityEngine.TestTools; +using UnityEngine; +using UnityEngine.Networking.NetworkSystem; +using UnityEngine.Networking; + +#pragma warning disable 618 +public class HavingManyLocalClientsSimultaneouslyWorks +{ + int kListenPort = 7073; + int maxConnections = 100; + const int kMsgTest = 555; + public class TestMessage : MessageBase + { + public int number; + public string str; + }; + private int numClients = 15; // Maximum hosts per process is 16 so 15 client + 1 server + int clientsConnected = 0; + int serverConnections = 0; + int msgCountClientRecieved = 0; + + [UnityTest] + public IEnumerator HavingManyLocalClientsSimultaneouslyWorksTest() + { + NetworkClient.ShutdownAll(); + NetworkServer.Reset(); + + ConnectionConfig config = new ConnectionConfig(); + config.AddChannel(QosType.ReliableSequenced); + config.AddChannel(QosType.Unreliable); + + NetworkServer.Configure(config, maxConnections); + NetworkServer.RegisterHandler(MsgType.Connect, OnServerConnected); + + int retries = 0; + while (!NetworkServer.Listen("127.0.0.1", ++kListenPort)) + { + Assert.IsTrue(retries++ < 10, "Couldn't Listen for more than 10 retries"); + } + + for (int i = 0; i < numClients; ++i) + { + NetworkClient myClient = new NetworkClient(); + if (!myClient.Configure(config, maxConnections)) + { + Assert.Fail("Client configure failed"); + } + myClient.RegisterHandler(MsgType.Connect, OnClientConnected); + myClient.RegisterHandler(MsgType.Error, OnError); + myClient.RegisterHandler(kMsgTest, OnClientTest); + myClient.Connect("127.0.0.1", kListenPort); + } + + while (serverConnections != numClients || clientsConnected != numClients) + { + yield return null; + } + + TestMessage testMsg = new TestMessage(); + testMsg.number = 98756; + testMsg.str = "teststring"; + + NetworkServer.SendToAll(kMsgTest, testMsg); + + while (msgCountClientRecieved != numClients) + { + yield return null; + } + } + + public void OnServerConnected(NetworkMessage netMsg) + { + serverConnections += 1; + } + + public void OnClientTest(NetworkMessage netMsg) + { + msgCountClientRecieved += 1; + var receivedMessage = netMsg.reader.ReadMessage(); + StringAssert.IsMatch("teststring", receivedMessage.str, "Received message has invalid sting"); + } + + public void OnClientConnected(NetworkMessage netMsg) + { + clientsConnected += 1; + } + + public void OnError(NetworkMessage netMsg) + { + ErrorMessage msg = netMsg.ReadMessage(); + Assert.Fail("Error: " + msg.errorCode); + } +} +#pragma warning restore 618 \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/IsConnectedPropertyWorksOnDifferentClients/IsConnectedPropertyWorksOnDifferentClients.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/IsConnectedPropertyWorksOnDifferentClients/IsConnectedPropertyWorksOnDifferentClients.cs new file mode 100644 index 00000000..c1e9084d --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/IsConnectedPropertyWorksOnDifferentClients/IsConnectedPropertyWorksOnDifferentClients.cs @@ -0,0 +1,68 @@ +using System.Collections; +using NUnit.Framework; +using UnityEngine.TestTools; +using UnityEngine; +using UnityEngine.Networking; + +#pragma warning disable 618 +public class IsConnectedPropertyWorksOnDifferentClients +{ + int kListenPort = 7073; + NetworkClient remoteClient; + NetworkClient localClient = null; + bool isTestDone; + + [UnityTest] + public IEnumerator IsConnectedPropertyWorksOnDifferentClientsTest() + { + NetworkClient.ShutdownAll(); + NetworkServer.Reset(); + + ConnectionConfig config = new ConnectionConfig(); + config.AddChannel(QosType.ReliableSequenced); + config.AddChannel(QosType.Unreliable); + + remoteClient = new NetworkClient(); + if (!remoteClient.Configure(config, 10)) + { + Assert.Fail("Client configure failed"); + } + + remoteClient.RegisterHandler(MsgType.Connect, OnClientConnected); + Assert.IsFalse(remoteClient.isConnected); + + + int retries = 0; + while (!NetworkServer.Listen("127.0.0.1", ++kListenPort)) + { + Assert.IsTrue(retries++ < 10, "Couldn't Listen for more than 10 retries"); + } + + remoteClient.Connect("127.0.0.1", kListenPort); + + while (!isTestDone) + { + yield return null; + } + } + + public void OnClientConnected(NetworkMessage netMsg) + { + Assert.IsTrue(remoteClient.isConnected); + + if (localClient == null) + { + localClient = ClientScene.ConnectLocalServer(); + Assert.IsTrue(localClient.isConnected); + + remoteClient.Disconnect(); + localClient.Disconnect(); + + Assert.IsFalse(remoteClient.isConnected); + Assert.IsFalse(localClient.isConnected); + + isTestDone = true; + } + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkBehaviourCallbacksOrderOnTheHost/NetworkBehaviourCallbacksOrderOnTheHost.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkBehaviourCallbacksOrderOnTheHost/NetworkBehaviourCallbacksOrderOnTheHost.cs new file mode 100644 index 00000000..d5d800f2 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkBehaviourCallbacksOrderOnTheHost/NetworkBehaviourCallbacksOrderOnTheHost.cs @@ -0,0 +1,54 @@ +using UnityEngine; +using UnityEngine.TestTools; +using NUnit.Framework; +using System.Collections; +using System.Collections.Generic; +using UnityEngine.Networking; + +#pragma warning disable 618 +public class NetworkBehaviourCallbacksOrderOnTheHost +{ + public static List expectedListOfCallbacks = new List() + { + "OnStartServer", + "OnStartClient", + "OnRebuildObservers", + "OnStartAuthority", + "OnStartLocalPlayer", + "Start", + "OnSetLocalVisibility", + "OnSetLocalVisibility" + }; + + //[KnownFailure(855941, "OnSetLocalVisibility callback should appear only once ")] + [UnityTest] + public IEnumerator CallbacksOrderInNetworkBehaviourOnTheHostIsCorrect() + { + NetworkClient.ShutdownAll(); + NetworkServer.Reset(); + + GameObject nmObject = new GameObject(); + NetworkManager nmanager = nmObject.AddComponent(); + nmanager.playerPrefab = Resources.Load("PlayerCallbacksOrderOnTheHost_PlayerPrefab", typeof(GameObject)) as GameObject; + + Assert.IsNotNull(nmanager.playerPrefab, "Player prefab field is not set on NetworkManager"); + + nmanager.StartHost(); + yield return null; + + Assert.IsTrue(NetworkServer.active, "Server is not active after StartHost"); + Assert.IsTrue(NetworkClient.active, "Client is not active after StartHost"); + yield return null; + GameObject player = GameObject.Find("PlayerCallbacksOrderOnTheHost_PlayerPrefab(Clone)"); + yield return null; + + while (!player.GetComponent().isDone) + { + yield return null; + } + nmanager.StopHost(); + CollectionAssert.AreEqual(expectedListOfCallbacks, player.GetComponent().actualListOfCallbacks, "Wrong order of callbacks or some callback is missing"); + Object.Destroy(nmObject); + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkBehaviourCallbacksOrderOnTheHost/PlayerCallbacksOrderOnTheHostScript.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkBehaviourCallbacksOrderOnTheHost/PlayerCallbacksOrderOnTheHostScript.cs new file mode 100644 index 00000000..c7569df9 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkBehaviourCallbacksOrderOnTheHost/PlayerCallbacksOrderOnTheHostScript.cs @@ -0,0 +1,47 @@ +using System.Collections.Generic; +using UnityEngine.Networking; + +#pragma warning disable 618 +public class PlayerCallbacksOrderOnTheHostScript : NetworkBehaviour +{ + public List actualListOfCallbacks = new List(); + public bool isDone = false; + + public void Start() + { + actualListOfCallbacks.Add("Start"); + } + + public override void OnStartServer() + { + actualListOfCallbacks.Add("OnStartServer"); + } + + public override void OnStartClient() + { + actualListOfCallbacks.Add("OnStartClient"); + } + + public override void OnStartLocalPlayer() + { + actualListOfCallbacks.Add("OnStartLocalPlayer"); + } + + public override void OnStartAuthority() + { + actualListOfCallbacks.Add("OnStartAuthority"); + } + + public override bool OnRebuildObservers(HashSet observers, bool initialize) + { + actualListOfCallbacks.Add("OnRebuildObservers"); + return false; + } + + public override void OnSetLocalVisibility(bool vis) + { + actualListOfCallbacks.Add("OnSetLocalVisibility"); + isDone = true; + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkBehaviourCallbacksOrderOnTheHost/Resources/PlayerCallbacksOrderOnTheHost_PlayerPrefab.prefab b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkBehaviourCallbacksOrderOnTheHost/Resources/PlayerCallbacksOrderOnTheHost_PlayerPrefab.prefab new file mode 100644 index 00000000..11d32ead --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkBehaviourCallbacksOrderOnTheHost/Resources/PlayerCallbacksOrderOnTheHost_PlayerPrefab.prefab @@ -0,0 +1,145 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!1001 &100100000 +Prefab: + m_ObjectHideFlags: 1 + serializedVersion: 2 + m_Modification: + m_TransformParent: {fileID: 0} + m_Modifications: [] + m_RemovedComponents: [] + m_ParentPrefab: {fileID: 0} + m_RootGameObject: {fileID: 1502327695165466} + m_IsPrefabParent: 1 +--- !u!1 &1502327695165466 +GameObject: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + serializedVersion: 5 + m_Component: + - component: {fileID: 4906103838815550} + - component: {fileID: 33168895557203384} + - component: {fileID: 23726883161695556} + - component: {fileID: 65213150513755038} + - component: {fileID: 114253944624540912} + - component: {fileID: 114975380025643044} + m_Layer: 0 + m_Name: PlayerCallbacksOrderOnTheHost_PlayerPrefab + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &4906103838815550 +Transform: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1502327695165466} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!23 &23726883161695556 +MeshRenderer: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1502327695165466} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RenderingLayerMask: 4294967295 + m_Materials: + - {fileID: 10303, guid: 0000000000000000f000000000000000, type: 0} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 +--- !u!33 &33168895557203384 +MeshFilter: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1502327695165466} + m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0} +--- !u!65 &65213150513755038 +BoxCollider: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1502327695165466} + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_Enabled: 1 + serializedVersion: 2 + m_Size: {x: 1, y: 1, z: 1} + m_Center: {x: 0, y: 0, z: 0} +--- !u!114 &114253944624540912 +MonoBehaviour: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1502327695165466} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 372142912, guid: dc443db3e92b4983b9738c1131f555cb, type: 3} + m_Name: + m_EditorClassIdentifier: + m_SceneId: + m_Value: 0 + m_AssetId: + i0: 220 + i1: 151 + i2: 179 + i3: 118 + i4: 73 + i5: 177 + i6: 13 + i7: 164 + i8: 184 + i9: 216 + i10: 254 + i11: 199 + i12: 56 + i13: 103 + i14: 117 + i15: 82 + m_ServerOnly: 0 + m_LocalPlayerAuthority: 1 +--- !u!114 &114975380025643044 +MonoBehaviour: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1502327695165466} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 77a7432320518724092f03d1e2eee645, type: 3} + m_Name: + m_EditorClassIdentifier: + actualListOfCallbacks: [] + isDone: 0 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkClientActiveWorksWithManyClients/NetworkClientActiveWorksWithManyClients.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkClientActiveWorksWithManyClients/NetworkClientActiveWorksWithManyClients.cs new file mode 100644 index 00000000..8e0252d8 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkClientActiveWorksWithManyClients/NetworkClientActiveWorksWithManyClients.cs @@ -0,0 +1,67 @@ +using System.Collections; +using NUnit.Framework; +using UnityEngine.TestTools; +using UnityEngine; +using UnityEngine.Networking; + +#pragma warning disable 618 +public class NetworkClientActiveWorksWithManyClients +{ + int kListenPort = 7073; + bool isTestDone; + int m_ClientConnectionCount = 0; + + [UnityTest] + public IEnumerator NetworkClientActiveWorksWithManyClientsTest() + { + NetworkClient.ShutdownAll(); + NetworkServer.Reset(); + + ConnectionConfig config = new ConnectionConfig(); + config.AddChannel(QosType.ReliableSequenced); + config.AddChannel(QosType.Unreliable); + + for (int i = 0; i < 3; ++i) + { + NetworkClient myClient = new NetworkClient(); + if (!myClient.Configure(config, 10)) + { + Assert.Fail("Client configure failed"); + } + myClient.RegisterHandler(MsgType.Connect, OnClientConnected); + } + + int retries = 0; + while (!NetworkServer.Listen("127.0.0.1", ++kListenPort)) + { + Assert.IsTrue(retries++ < 10, "Couldn't Listen for more than 10 retries"); + } + + Assert.IsFalse(NetworkClient.active, "NetworkClient.active should be false as there is no clients yet"); + NetworkClient.allClients[0].Connect("127.0.0.1", kListenPort); + Assert.IsTrue(NetworkClient.active, "NetworkClient.active should be true as there is one client"); + NetworkClient.allClients[1].Connect("127.0.0.1", kListenPort); + NetworkClient.allClients[2].Connect("127.0.0.1", kListenPort); + + while (!isTestDone) + { + yield return null; + } + } + + public void OnClientConnected(NetworkMessage netMsg) + { + if (++m_ClientConnectionCount == 3) + { + NetworkClient.allClients[1].Shutdown(); + Assert.IsTrue(NetworkClient.active, "NetworkClient.active should be true as there are two clients"); + NetworkClient.allClients[0].Shutdown(); + Assert.IsTrue(NetworkClient.active, "NetworkClient.active should be true as there is one client"); + // The 2nd basic client instance is now 0, since they are removed from the list on shut down... + NetworkClient.allClients[0].Shutdown(); + Assert.IsFalse(NetworkClient.active, "NetworkClient.active should be false as all clients were shut down"); + isTestDone = true; + } + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkClientDisconnectWorks/NetworkClientDisconnectWorks.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkClientDisconnectWorks/NetworkClientDisconnectWorks.cs new file mode 100644 index 00000000..4414c92c --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkClientDisconnectWorks/NetworkClientDisconnectWorks.cs @@ -0,0 +1,82 @@ +using System.Collections; +using NUnit.Framework; +using UnityEngine.TestTools; +using UnityEngine; +using UnityEngine.Networking; + +#pragma warning disable 618 +public class NetworkClientDisconnectWorks +{ + int kListenPort = 7073; + private const int totalConnects = 2; + private int numConnects = 0; + bool isClientConnected = false; + bool isServerRecivedConnection = false; + ConnectionConfig config; + NetworkClient myClient; + + [UnityTest] + public IEnumerator NetworkClientDisconnectWorksTest() + { + NetworkClient.ShutdownAll(); + NetworkServer.Reset(); + + NetworkServer.RegisterHandler(MsgType.Connect, OnServerConnected); + NetworkServer.RegisterHandler(MsgType.Disconnect, OnClientDisconnected); + + config = new ConnectionConfig(); + config.AddChannel(QosType.ReliableSequenced); + config.AddChannel(QosType.Unreliable); + + myClient = new NetworkClient(); + if (!myClient.Configure(config, 20)) + { + Assert.Fail("Client configure failed"); + } + + myClient.RegisterHandler(MsgType.Connect, OnClientConnected); + + int retries = 0; + while (!NetworkServer.Listen("127.0.0.1", ++kListenPort)) + { + Assert.IsTrue(retries++ < 10, "Couldn't Listen for more than 10 retries"); + } + myClient.Connect("127.0.0.1", kListenPort); + + while (numConnects != totalConnects) + { + if (isServerRecivedConnection && isClientConnected) + { + myClient.Disconnect(); + isClientConnected = false; + } + yield return null; + } + } + + public void OnServerConnected(NetworkMessage netMsg) + { + isServerRecivedConnection = true; + } + + public void OnClientConnected(NetworkMessage netMsg) + { + isClientConnected = true; + } + + public void OnClientDisconnected(NetworkMessage netMsg) + { + numConnects++; + Assert.IsTrue(isServerRecivedConnection); + isServerRecivedConnection = false; + isClientConnected = false; + myClient = new NetworkClient(); + if (!myClient.Configure(config, 20)) + { + Assert.Fail("Client configure failed"); + } + myClient.RegisterHandler(MsgType.Connect, OnClientConnected); + myClient.Connect("127.0.0.1", kListenPort); + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkDiscoveryWorks/NetworkDiscoveryWorks.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkDiscoveryWorks/NetworkDiscoveryWorks.cs new file mode 100644 index 00000000..7c22fcc0 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkDiscoveryWorks/NetworkDiscoveryWorks.cs @@ -0,0 +1,61 @@ +using System.Collections; +using NUnit.Framework; +using UnityEngine.TestTools; +using UnityEngine; +using UnityEngine.Networking; + +#pragma warning disable 618 +public class NetworkDiscoveryWorks +{ + const string testData = "TESTING"; + GameObject clientObj; + GameObject serverObj; + + [UnityTest] + public IEnumerator NetworkDiscoveryWorksTest() + { + NetworkClient.ShutdownAll(); + NetworkServer.Reset(); + + bool result; + + serverObj = new GameObject(); + var serverDiscovery = serverObj.AddComponent(); + serverDiscovery.useNetworkManager = false; + serverDiscovery.broadcastData = testData; + result = serverDiscovery.Initialize(); + Assert.IsTrue(result, "serverDiscovery.Initialize() returned false"); + + result = serverDiscovery.StartAsServer(); + Assert.IsTrue(result, "serverDiscovery.StartAsServer() returned false"); + + clientObj = new GameObject(); + var clientDiscovery = clientObj.AddComponent(); + + result = clientDiscovery.Initialize(); + Assert.IsTrue(result, "clientDiscovery.Initialize() returned false"); + + result = clientDiscovery.StartAsClient(); + Assert.IsTrue(result, "clientDiscovery.StartAsClient() returned false"); + + + while (clientDiscovery.broadcastsReceived.Count <= 0) + { + yield return null; + } + + foreach (var dis in clientDiscovery.broadcastsReceived.Values) + { + char[] chars = new char[dis.broadcastData.Length / sizeof(char)]; + System.Buffer.BlockCopy(dis.broadcastData, 0, chars, 0, dis.broadcastData.Length); + var str = new string(chars); + + Assert.AreEqual(testData, str, "Sent and received data are different"); + } + serverDiscovery.StopBroadcast(); + clientDiscovery.StopBroadcast(); + Object.Destroy(serverDiscovery); + Object.Destroy(clientDiscovery); + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkManagerCallbacksOrderOnTheHost/CustomNetworkManagerWithCallbacks.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkManagerCallbacksOrderOnTheHost/CustomNetworkManagerWithCallbacks.cs new file mode 100644 index 00000000..d478be65 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkManagerCallbacksOrderOnTheHost/CustomNetworkManagerWithCallbacks.cs @@ -0,0 +1,70 @@ +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.Networking; + +#pragma warning disable 618 +public class CustomNetworkManagerWithCallbacks : NetworkManager +{ + public List actualListOfCallbacks = new List(); + public bool isStartHostPartDone; + public bool isStopHostPartDone; + + // ----- Start Host ----- + public override void OnStartHost() + { + actualListOfCallbacks.Add("OnStartHost"); + } + + public override void OnStartServer() + { + actualListOfCallbacks.Add("OnStartServer"); + } + + public override void OnServerConnect(NetworkConnection conn) + { + base.OnServerConnect(conn); + actualListOfCallbacks.Add("OnServerConnect"); + } + + public override void OnStartClient(NetworkClient client) + { + actualListOfCallbacks.Add("OnStartClient"); + } + + public override void OnClientConnect(NetworkConnection conn) + { + base.OnClientConnect(conn); + actualListOfCallbacks.Add("OnClientConnect"); + isStartHostPartDone = true; + } + + public override void OnServerReady(NetworkConnection conn) + { + actualListOfCallbacks.Add("OnServerReady"); + base.OnServerReady(conn); + } + + public override void OnServerAddPlayer(NetworkConnection conn, short playerControllerId) + { + base.OnServerAddPlayer(conn, playerControllerId); + actualListOfCallbacks.Add("OnServerAddPlayer"); + } + + // ----- Stop Host ----- + public override void OnStopHost() + { + actualListOfCallbacks.Add("OnStopHost"); + } + + public override void OnStopServer() + { + actualListOfCallbacks.Add("OnStopServer"); + } + + public override void OnStopClient() + { + actualListOfCallbacks.Add("OnStopClient"); + isStopHostPartDone = true; + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkManagerCallbacksOrderOnTheHost/NetworkManagerCallbacksOrderOnTheHost.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkManagerCallbacksOrderOnTheHost/NetworkManagerCallbacksOrderOnTheHost.cs new file mode 100644 index 00000000..ec4dcdd6 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkManagerCallbacksOrderOnTheHost/NetworkManagerCallbacksOrderOnTheHost.cs @@ -0,0 +1,60 @@ +using System.Collections; +using System.Collections.Generic; +using NUnit.Framework; +using UnityEngine.TestTools; +using UnityEngine; +using UnityEngine.Networking; + +#pragma warning disable 618 +public class NetworkManagerCallbacksOrderOnTheHost +{ + public static List resultListOfCallbacks = new List() + { + "OnStartHost", + "OnStartServer", + "OnServerConnect", + "OnStartClient", + "OnServerReady", + "OnServerAddPlayer", + "OnClientConnect", + "OnStopHost", + "OnStopServer", + "OnStopClient" + }; + + [UnityTest] + public IEnumerator CallbacksOrderInNetworkManagerOnTheHostIsCorrect() + { + NetworkServer.Reset(); + NetworkClient.ShutdownAll(); + + GameObject nmObject = new GameObject(); + CustomNetworkManagerWithCallbacks nmanager = nmObject.AddComponent(); + nmanager.playerPrefab = Resources.Load("CleanPlayerPrefab", typeof(GameObject)) as GameObject; + + yield return null; + Assert.IsNotNull(nmanager.playerPrefab, "Player prefab field is not set on NetworkManager"); + + nmanager.StartHost(); + yield return null; + + Assert.IsTrue(NetworkServer.active, "Server is not active after StartHost"); + Assert.IsTrue(NetworkClient.active, "Client is not active after StartHost"); + yield return null; + + while (!nmanager.isStartHostPartDone) + { + yield return null; + } + + nmanager.StopHost(); + while (!nmanager.isStopHostPartDone) + { + yield return null; + } + + CollectionAssert.AreEqual(resultListOfCallbacks, nmanager.actualListOfCallbacks, "Wrong order of callbacks or some callback is missing"); + Object.Destroy(nmObject); + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkManagerCallbacksOrderOnTheHost/Resources/CleanPlayerPrefab.prefab b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkManagerCallbacksOrderOnTheHost/Resources/CleanPlayerPrefab.prefab new file mode 100644 index 00000000..6ce373f4 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkManagerCallbacksOrderOnTheHost/Resources/CleanPlayerPrefab.prefab @@ -0,0 +1,131 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!1001 &100100000 +Prefab: + m_ObjectHideFlags: 1 + serializedVersion: 2 + m_Modification: + m_TransformParent: {fileID: 0} + m_Modifications: [] + m_RemovedComponents: [] + m_ParentPrefab: {fileID: 0} + m_RootGameObject: {fileID: 1257315088113390} + m_IsPrefabParent: 1 +--- !u!1 &1257315088113390 +GameObject: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + serializedVersion: 5 + m_Component: + - component: {fileID: 4088004896237320} + - component: {fileID: 33049133014149440} + - component: {fileID: 23902480328168034} + - component: {fileID: 65237091255332572} + - component: {fileID: 114457817983725144} + m_Layer: 0 + m_Name: CleanPlayerPrefab + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &4088004896237320 +Transform: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1257315088113390} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!23 &23902480328168034 +MeshRenderer: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1257315088113390} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RenderingLayerMask: 4294967295 + m_Materials: + - {fileID: 10303, guid: 0000000000000000f000000000000000, type: 0} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 +--- !u!33 &33049133014149440 +MeshFilter: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1257315088113390} + m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0} +--- !u!65 &65237091255332572 +BoxCollider: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1257315088113390} + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_Enabled: 1 + serializedVersion: 2 + m_Size: {x: 1, y: 1, z: 1} + m_Center: {x: 0, y: 0, z: 0} +--- !u!114 &114457817983725144 +MonoBehaviour: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1257315088113390} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 372142912, guid: dc443db3e92b4983b9738c1131f555cb, type: 3} + m_Name: + m_EditorClassIdentifier: + m_SceneId: + m_Value: 0 + m_AssetId: + i0: 33 + i1: 118 + i2: 84 + i3: 125 + i4: 76 + i5: 229 + i6: 172 + i7: 164 + i8: 24 + i9: 35 + i10: 11 + i11: 204 + i12: 175 + i13: 163 + i14: 232 + i15: 234 + m_ServerOnly: 0 + m_LocalPlayerAuthority: 1 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkManagerConfigWorks/NetworkManagerConfigWorksTest.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkManagerConfigWorks/NetworkManagerConfigWorksTest.cs new file mode 100644 index 00000000..486643f5 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkManagerConfigWorks/NetworkManagerConfigWorksTest.cs @@ -0,0 +1,87 @@ +using NUnit.Framework; +using System; +using System.Collections; +using UnityEngine; +using UnityEngine.TestTools; +using UnityEngine.Networking; + +#pragma warning disable 618 +public class NetworkManagerConfigWorksTest +{ + NetworkManager netManager; + + [UnityTest] + public IEnumerator NetworkManagerConfigCheck() + { + NetworkServer.Reset(); + + var netManagerObj = new GameObject(); + netManager = netManagerObj.AddComponent(); + + netManager.GetComponent().customConfig = true; + + foreach (QosType channel in Enum.GetValues(typeof(QosType))) + { + netManager.GetComponent(). + connectionConfig.AddChannel(channel); + } + + Assert.AreEqual(netManager.connectionConfig.ChannelCount, Enum.GetValues(typeof(QosType)).Length, "Not all channels are added"); + + netManager.connectionConfig.AckDelay = 33; + netManager.connectionConfig.AcksType = ConnectionAcksType.Acks32; + netManager.connectionConfig.AllCostTimeout = 20; + netManager.connectionConfig.FragmentSize = 500; + netManager.connectionConfig.ConnectTimeout = 500; + netManager.connectionConfig.DisconnectTimeout = 2000; + + NetworkHostCanBeStartedWithConfig(); + NetworkServerClientCanBeStartedWithConfig(); + + yield return null; + UnityEngine.Object.Destroy(netManager); + } + + //check that Host can be started + public IEnumerator NetworkHostCanBeStartedWithConfig() + { + NetworkClient netClient = new NetworkClient(); + + if (!netManager.isNetworkActive) + netClient = netManager.StartHost(); + + if (!netClient.isConnected) + yield return null; + + Assert.IsTrue(netClient.isConnected, + "Network is not active."); + + netManager.StopHost(); + } + + //check that Server/Client can be started + public IEnumerator NetworkServerClientCanBeStartedWithConfig() + { + string netAddress = "127.0.0.1"; + int netPort = 8887; + netManager.networkAddress = netAddress; + netManager.networkPort = netPort; + + netManager.StartServer(); + + NetworkClient netClient = netManager.StartClient(); + + netClient.Connect(netAddress, netPort); + + if (!netClient.isConnected) + { + yield return null; + } + + Assert.IsTrue(netClient.isConnected, + "Client did not connect to server"); + + netManager.StopServer(); + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkManagerGivesErrorWhenNoPlayerPrefabSet/NetworkManagerGivesErrorWhenNoPlayerPrefabSet.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkManagerGivesErrorWhenNoPlayerPrefabSet/NetworkManagerGivesErrorWhenNoPlayerPrefabSet.cs new file mode 100644 index 00000000..4b5aa5ff --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkManagerGivesErrorWhenNoPlayerPrefabSet/NetworkManagerGivesErrorWhenNoPlayerPrefabSet.cs @@ -0,0 +1,50 @@ +using System.Collections; +using NUnit.Framework; +using UnityEngine.TestTools; +using UnityEngine; +using UnityEngine.Networking; + +#pragma warning disable 618 +public class NetworkManagerGivesErrorWhenNoPlayerPrefabSet +{ + public class CustomNetworkManagerGivesErrorWhenNoPlayerPrefabSet : NetworkManager + { + public bool isDone = false; + public override void OnServerReady(NetworkConnection conn) + { + base.OnServerReady(conn); + isDone = true; + } + } + + [UnityTest] + public IEnumerator NetworkManagerGivesErrorWhenNoPlayerPrefabSetTest() + { + NetworkClient.ShutdownAll(); + NetworkServer.Reset(); + + GameObject nmObject = new GameObject(); + CustomNetworkManagerGivesErrorWhenNoPlayerPrefabSet nmanager = nmObject.AddComponent(); + nmanager.networkAddress = "localhost"; + + yield return null; + Assert.IsNull(nmanager.playerPrefab, "Player prefab field is set on NetworkManager, but shouldn't be"); + + nmanager.StartHost(); + yield return null; + + LogAssert.Expect(LogType.Error, "The PlayerPrefab is empty on the NetworkManager. Please setup a PlayerPrefab object."); + Assert.IsTrue(NetworkServer.active, "Server is not active after StartHost"); + Assert.IsTrue(NetworkClient.active, "Client is not active after StartHost"); + yield return null; + + while (!nmanager.isDone) + { + yield return null; + } + + nmanager.StopHost(); + Object.Destroy(nmObject); + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkManagerHandlesLargePacket/NetworkManagerHandlesLargePacket.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkManagerHandlesLargePacket/NetworkManagerHandlesLargePacket.cs new file mode 100644 index 00000000..e505dfba --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkManagerHandlesLargePacket/NetworkManagerHandlesLargePacket.cs @@ -0,0 +1,85 @@ +using System.Collections; +using NUnit.Framework; +using UnityEngine.TestTools; +using UnityEngine; +using UnityEngine.Networking; + +#pragma warning disable 618 +public class NetworkManagerHandlesLargePacket +{ + public bool isDone = false; + const short MsgIdBig = 99; + const int MsgSize = 10397;// increasing it to bigger number will cause failure + + class BigMessage : MessageBase + { + public byte[] data; + } + + [UnityTest] + public IEnumerator NetworkManagerHandlesLargePacketTest() + { + NetworkClient.ShutdownAll(); + NetworkServer.Reset(); + + GameObject nmObject = new GameObject(); + NetworkManagerWithLargePacket nmanager = nmObject.AddComponent(); + nmanager.networkAddress = "localhost"; + nmanager.autoCreatePlayer = false; + + nmanager.customConfig = true; + nmanager.connectionConfig.MinUpdateTimeout = 1; + nmanager.connectionConfig.MaxSentMessageQueueSize = 200; + nmanager.channels.Add(QosType.UnreliableFragmented); + + nmanager.StartServer(); + nmanager.StartClient(); + yield return null; + NetworkServer.RegisterHandler(MsgIdBig, OnBigMessage); + + yield return null; + + Assert.IsTrue(NetworkServer.active, "Server is not started"); + Assert.IsTrue(NetworkClient.active, "Client is not started"); + yield return null; + + while (!isDone) + { + yield return null; + } + + NetworkManager.singleton.StopServer(); + NetworkManager.singleton.StopClient(); + + Object.Destroy(nmObject); + } + + public void OnBigMessage(NetworkMessage netMsg) + { + Debug.Log("OnBigMessage"); + var bigMsg = netMsg.ReadMessage(); + Assert.AreEqual(MsgSize, bigMsg.data.Length); + isDone = true; + } + + public class NetworkManagerWithLargePacket : NetworkManager + { + public override void OnClientConnect(NetworkConnection conn) + { + Debug.Log("OnClient Connect"); + base.OnClientConnect(conn); + + var bigMsg = new BigMessage(); + bigMsg.data = new byte[MsgSize]; + + var writer = new NetworkWriter(); + writer.StartMessage(MsgIdBig); + bigMsg.Serialize(writer); + writer.FinishMessage(); + var data = writer.ToArray(); + + client.SendBytes(data, data.Length, 0); + } + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkManagerSpawnSpecialPrefab/NetworkManagerSpawnSpecialPrefab.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkManagerSpawnSpecialPrefab/NetworkManagerSpawnSpecialPrefab.cs new file mode 100644 index 00000000..aa9bcf0b --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkManagerSpawnSpecialPrefab/NetworkManagerSpawnSpecialPrefab.cs @@ -0,0 +1,87 @@ +using System; +using System.Collections; +using NUnit.Framework; +using UnityEditor; +using UnityEngine; +using UnityEngine.Networking; +using UnityEngine.TestTools; +using UnityEngine.Windows; + +#pragma warning disable 618 +class NetworkManagerSpawnSpecialPrefab : IPrebuildSetup +{ + public void Setup() + { +#if UNITY_EDITOR + GameObject obj = new GameObject("NetworkManagerSpawnSpecialPrefab_player"); + var netId = obj.AddComponent(); + // Certain conditions can lead to a prefab containing a set scene ID + // for example if you set up a scene object linked to a prefab, start playmode (which + // assigns a new scene ID) and then click apply changes to prefab on the scene object + netId.ForceSceneId(1); + obj.AddComponent(); + var netTransform = obj.AddComponent(); + netTransform.transformSyncMode = NetworkTransform.TransformSyncMode.SyncCharacterController; + obj.AddComponent(); + var prefab = PrefabUtility.CreatePrefab("Assets/UNetManagerSpawnSpecialPrefab.prefab", obj, ReplacePrefabOptions.ConnectToPrefab); + GameObject.DestroyImmediate(obj); + + obj = new GameObject("NetworkManagerSpawnerScript"); + var manager = obj.AddComponent(); + manager.playerPrefab = prefab; + GameObject.DestroyImmediate(obj); + //File.Delete("Assets/UNetManagerSpawnSpecialPrefab.prefab"); +#endif + } + + // TODO: Disabled for now as something went wrong in the transition from runtime to playmode tests (in test setup part) + //[UnityTest] + public IEnumerator NetworkManagerSpawnSpecialPrefabTest() + { + NetworkManager.singleton.StartHost(); + + DateTime timelimit = DateTime.Now; + while (!NetworkManagerSpawnerScript.serverReady) + { + if ((DateTime.Now - timelimit).TotalSeconds > 30) + { + Assert.Fail("Network manager didn't get to ready state"); + } + yield return null; + } + + // If invalid scene ID (forced to 1) has not been corrected in the prefab we have a problem (the bug this test covers only happened on standalone players) + if (!NetworkManagerSpawnSpecialPrefabObject.didSpawnWithValidSceneId) + { + Assert.Fail("Server ready but scene ID is invalid."); + } + + NetworkManager.singleton.StopServer(); + } + + public class NetworkManagerSpawnerScript : NetworkManager + { + public static bool serverReady; + + public override void OnServerReady(NetworkConnection conn) + { + base.OnServerReady(conn); + serverReady = true; + } + } + + public class NetworkManagerSpawnSpecialPrefabObject : NetworkBehaviour + { + public static bool didSpawnWithValidSceneId; + + public override void OnStartServer() + { + // The scene ID was forced to 1 on the prefab, it should have been corrected to 0 on this intantiated copy of that prafab + if (GetComponent().sceneId.Value == 0) + { + didSpawnWithValidSceneId = true; + } + } + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkManagerStillWorksWhenUserUseStartAndAwake/NetworkManagerStillWorksWhenUserUseStartAndAwake.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkManagerStillWorksWhenUserUseStartAndAwake/NetworkManagerStillWorksWhenUserUseStartAndAwake.cs new file mode 100644 index 00000000..73724844 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkManagerStillWorksWhenUserUseStartAndAwake/NetworkManagerStillWorksWhenUserUseStartAndAwake.cs @@ -0,0 +1,64 @@ +using System.Collections; +using NUnit.Framework; +using UnityEngine.TestTools; +using UnityEngine; +using UnityEngine.Networking; + +#pragma warning disable 618 +public class NetworkManagerStillWorksWhenUserUseStartAndAwake +{ + public class CustomNetworkManagerWithAwakeAndStart : NetworkManager + { + public bool isDone = false; + public int counter; + + public void Awake() + { + counter++; + } + + public void Start() + { + counter++; + } + + public override void OnClientConnect(NetworkConnection conn) + { + base.OnClientConnect(conn); + counter++; + isDone = true; + } + } + + [UnityTest] + public IEnumerator NetworkManagerStillWorksWhenUserUseStartAndAwakeTest() + { + NetworkClient.ShutdownAll(); + NetworkServer.Reset(); + + GameObject nmObject = new GameObject(); + CustomNetworkManagerWithAwakeAndStart nmanager = nmObject.AddComponent(); + nmanager.networkAddress = "localhost"; + + yield return null; + Assert.IsNull(nmanager.playerPrefab, "Player prefab field is set on NetworkManager, but shouldn't be"); + + nmanager.StartHost(); + yield return null; + + LogAssert.Expect(LogType.Error, "The PlayerPrefab is empty on the NetworkManager. Please setup a PlayerPrefab object."); + Assert.IsTrue(NetworkServer.active, "Server is not active after StartHost"); + Assert.IsTrue(NetworkClient.active, "Client is not active after StartHost"); + yield return null; + + while (!nmanager.isDone) + { + yield return null; + } + + nmanager.StopHost(); + Assert.AreEqual(3, nmanager.counter, "Start or Awake was not called on NetwotkManager"); + Object.Destroy(nmObject); + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkManagerStopServerAndClientWorks/NetworkManagerStopServerAndClientWorks.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkManagerStopServerAndClientWorks/NetworkManagerStopServerAndClientWorks.cs new file mode 100644 index 00000000..8c4d141f --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkManagerStopServerAndClientWorks/NetworkManagerStopServerAndClientWorks.cs @@ -0,0 +1,54 @@ +using System.Collections; +using NUnit.Framework; +using UnityEngine.TestTools; +using UnityEngine; +using UnityEngine.Networking; + +#pragma warning disable 618 +public class NetworkManagerStopServerAndClientWorks +{ + public class TestNetworkManagerStop : NetworkManager + { + public bool isDone; + + public override void OnClientConnect(NetworkConnection conn) + { + StopServer(); + StopClient(); + + Assert.IsFalse(NetworkServer.active, "Server should not be active at this point"); + Assert.IsFalse(NetworkClient.active, "Client should not be active at this point"); + isDone = true; + } + } + + [UnityTest] + public IEnumerator NetworkManagerStopServerAndClientWorksTest() + { + NetworkClient.ShutdownAll(); + NetworkServer.Reset(); + + GameObject nmObject = new GameObject(); + TestNetworkManagerStop nmanager = nmObject.AddComponent(); + + nmanager.networkAddress = "localhost"; + nmanager.StartServer(); + nmanager.StartClient(); + yield return null; + + Assert.IsTrue(NetworkServer.active, "Server is not started"); + Assert.IsTrue(NetworkClient.active, "Client is not started"); + yield return null; + + while (!nmanager.isDone) + { + yield return null; + } + + NetworkManager.singleton.StopServer(); + NetworkManager.singleton.StopClient(); + + Object.Destroy(nmObject); + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkManagerWorksWithNullScenes/NetworkManagerWorksWithNullScenesTest.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkManagerWorksWithNullScenes/NetworkManagerWorksWithNullScenesTest.cs new file mode 100644 index 00000000..f1a56b7c --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkManagerWorksWithNullScenes/NetworkManagerWorksWithNullScenesTest.cs @@ -0,0 +1,38 @@ +using UnityEngine; +using UnityEngine.TestTools; +using NUnit.Framework; +using System.Collections; +using UnityEngine.Networking; + +#pragma warning disable 618 +public class NetworkManagerWorksWithNullScenesTest +{ + [UnityTest] + public IEnumerator TestNetworkManageNullScenes() + { + NetworkClient.ShutdownAll(); + NetworkServer.Reset(); + + var networkManagerObj = new GameObject(); + NetworkManager nmanager = networkManagerObj.AddComponent(); + nmanager.playerPrefab = Resources.Load("CleanPlayerPrefab", typeof(GameObject)) as GameObject; + + nmanager.offlineScene = null; + nmanager.onlineScene = null; + + NetworkServer.Reset(); + + if (!nmanager.isNetworkActive) + { + nmanager.StartHost(); + yield return null; + } + + Assert.IsTrue(nmanager.isNetworkActive, + "Network is not active."); + + nmanager.StopHost(); + Object.Destroy(networkManagerObj); + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkMessagesWork/NetworkMessages.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkMessagesWork/NetworkMessages.cs new file mode 100644 index 00000000..4568ddbc --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkMessagesWork/NetworkMessages.cs @@ -0,0 +1,88 @@ +using System.Collections; +using NUnit.Framework; +using UnityEngine.TestTools; +using UnityEngine; +using UnityEngine.Networking; + +#pragma warning disable 618 +public class MessageTypes +{ + public const short CSHelloMsgType = MsgType.Highest + 1; + public const short CSUpdateMsgType = MsgType.Highest + 2; + public const short SCUpdateMsgType = MsgType.Highest + 3; +} + +public class CSHelloMessage : MessageBase +{ + public int connectionID; + + public CSHelloMessage() {} + public CSHelloMessage(int ID) { this.connectionID = ID; } + + public override void Deserialize(NetworkReader reader) + { + connectionID = reader.ReadInt32(); + } + + public override void Serialize(NetworkWriter writer) + { + writer.StartMessage(MessageTypes.CSHelloMsgType); + writer.Write(connectionID); + writer.FinishMessage(); + } +} + +public class CSUpdateMessage : MessageBase +{ + public byte ID; + public Vector3 position; + + public CSUpdateMessage() {} + public CSUpdateMessage(byte ID, Vector3 position) + { + this.ID = ID; + this.position = position; + } + + public override void Deserialize(NetworkReader reader) + { + ID = reader.ReadByte(); + position = reader.ReadVector3(); + } + + public override void Serialize(NetworkWriter writer) + { + writer.StartMessage(MessageTypes.CSUpdateMsgType); + writer.Write(ID); + writer.Write(position); + writer.FinishMessage(); + } +} + +public class SCUpdateMessage : MessageBase +{ + public byte ID; + public bool status; + + public SCUpdateMessage() {} + public SCUpdateMessage(byte ID, bool status) + { + this.ID = ID; + this.status = status; + } + + public override void Deserialize(NetworkReader reader) + { + ID = reader.ReadByte(); + status = reader.ReadBoolean(); + } + + public override void Serialize(NetworkWriter writer) + { + writer.StartMessage(MessageTypes.SCUpdateMsgType); + writer.Write(ID); + writer.Write(status); + writer.FinishMessage(); + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkMessagesWork/NetworkMessagesWorkTest.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkMessagesWork/NetworkMessagesWorkTest.cs new file mode 100644 index 00000000..07c9426f --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkMessagesWork/NetworkMessagesWorkTest.cs @@ -0,0 +1,95 @@ +using NUnit.Framework; +using System; +using System.Collections; +using UnityEngine; +using UnityEngine.TestTools; +using UnityEngine.Networking; + +#pragma warning disable 618 +public class NetworkMessagesWorkTest +{ + string m_ip = "127.0.0.1"; + int m_port0 = 8888; + + bool isDone = false; + NetworkClient client; + + [UnityTest] + public IEnumerator NetworkMessagesWorkCheck() + { + NetworkServer.Reset(); + + ConnectionConfig connectionConfig = new ConnectionConfig(); + connectionConfig.AddChannel(QosType.Reliable); + connectionConfig.AddChannel(QosType.AllCostDelivery); + connectionConfig.AcksType = ConnectionAcksType.Acks96; + NetworkServer.Configure(connectionConfig, 4); + + NetworkServer.RegisterHandler(MessageTypes.CSUpdateMsgType, OnClientUpdate); + NetworkServer.RegisterHandler(MsgType.Connect, OnClientConnect); + NetworkServer.RegisterHandler(MessageTypes.CSHelloMsgType, OnClientHello); + + bool isServerStarted = NetworkServer.Listen(m_ip, m_port0); + Assert.IsTrue(isServerStarted, "Server is not started."); + + client = new NetworkClient(); + client.Configure(connectionConfig, 4); + client.Connect(m_ip, m_port0); + while (!client.isConnected) + { + yield return null; + } + + client.RegisterHandler(MessageTypes.SCUpdateMsgType, OnServerUpdate); + + CSHelloMessage msg = new CSHelloMessage(client.connection.connectionId); + client.Send(MessageTypes.CSHelloMsgType, msg); + + while (!isDone) + { + yield return null; + } + } + + public void SendServerUpdateMessage() + { + NetworkServer.SendToAll(MessageTypes.SCUpdateMsgType, + new SCUpdateMessage((byte)NetworkServer.serverHostId, + NetworkServer.active)); + } + + public void SendClientUpdateMessage(NetworkClient client) + { + Vector3 vec = new Vector3(1, 1, 1); + client.Send(MessageTypes.CSUpdateMsgType, + new CSUpdateMessage((byte)client.connection.hostId, vec)); + } + + public void OnClientHello(NetworkMessage msg) + { + Assert.AreEqual(msg.msgType, MessageTypes.CSHelloMsgType); + SendServerUpdateMessage(); + } + + public void OnClientConnect(NetworkMessage msg) + { + Assert.AreEqual(msg.msgType, MsgType.Connect); + } + + public void OnServerUpdate(NetworkMessage msg) + { + Assert.AreEqual(msg.msgType, MessageTypes.SCUpdateMsgType); + SendClientUpdateMessage(client); + } + + public void OnClientUpdate(NetworkMessage msg) + { + Assert.AreEqual(msg.msgType, MessageTypes.CSUpdateMsgType); + msg.reader.SeekZero(); + Vector3 recVecor = msg.ReadMessage().position; + Vector3 vec = new Vector3(1, 1, 1); + Assert.AreEqual(vec, recVecor); + isDone = true; + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkMigrationWorks/NetworkMigrationWorksTest.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkMigrationWorks/NetworkMigrationWorksTest.cs new file mode 100644 index 00000000..0aae67d8 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkMigrationWorks/NetworkMigrationWorksTest.cs @@ -0,0 +1,69 @@ +using NUnit.Framework; +using System; +using System.Collections; +using UnityEngine; +using UnityEngine.TestTools; +using UnityEngine.Networking; +using UnityEngine.Networking.NetworkSystem; + +#pragma warning disable 618 +public class NetworkMigrationWorksTest +{ + private GameObject netManagerObj; + NetworkManager networkManager; + NetworkMigrationManager networkMigrManager; + private NetworkClient client; + int _port = 8888; + string _ip = "127.0.0.1"; + + [UnityTest] + public IEnumerator NetworkMigrationWorksCheck() + { + NetworkServer.Reset(); + + SetupNetwork(); + + yield return new WaitUntil(() => networkMigrManager.peers != null); + + networkManager.StopServer(); + + PeerInfoMessage newHostInfo; + bool youAreNewHost; + Assert.IsTrue( + networkMigrManager.FindNewHost(out newHostInfo, out youAreNewHost), + "New host was not found."); + + Assert.IsTrue( + client.ReconnectToNewHost(newHostInfo.address, newHostInfo.port), + "Old client did not reconnect to new host."); + + yield return null; + UnityEngine.Object.Destroy(netManagerObj); + } + + public void SetupNetwork() + { + netManagerObj = new GameObject(); + networkManager = netManagerObj.AddComponent(); + networkManager.playerPrefab = Resources.Load("PlayerGameObject", typeof(GameObject)) as GameObject; + + Assert.IsNotNull(networkManager.playerPrefab); + + networkManager.customConfig = true; + networkManager.networkAddress = _ip; + networkManager.networkPort = _port; + networkManager.autoCreatePlayer = false; + + networkMigrManager = netManagerObj.AddComponent(); + Assert.IsTrue(networkManager.StartServer(), "Server was not started!"); + networkManager.SetupMigrationManager(networkMigrManager); + + client = networkManager.StartClient(); + client.Connect(_ip, _port); + Assert.IsNull(client.connection, "Client is not connected"); + + networkMigrManager.Initialize(client, networkManager.matchInfo); + networkMigrManager.SendPeerInfo(); + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkMigrationWorks/Resources/PlayerGameObject.prefab b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkMigrationWorks/Resources/PlayerGameObject.prefab new file mode 100644 index 00000000..b5ef4ccc --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkMigrationWorks/Resources/PlayerGameObject.prefab @@ -0,0 +1,74 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!1001 &100100000 +Prefab: + m_ObjectHideFlags: 1 + serializedVersion: 2 + m_Modification: + m_TransformParent: {fileID: 0} + m_Modifications: [] + m_RemovedComponents: [] + m_ParentPrefab: {fileID: 0} + m_RootGameObject: {fileID: 1600669219956046} + m_IsPrefabParent: 1 +--- !u!1 &1600669219956046 +GameObject: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + serializedVersion: 5 + m_Component: + - component: {fileID: 4779181925345128} + - component: {fileID: 114606075425375630} + m_Layer: 0 + m_Name: PlayerGameObject + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &4779181925345128 +Transform: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1600669219956046} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!114 &114606075425375630 +MonoBehaviour: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1600669219956046} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 372142912, guid: dc443db3e92b4983b9738c1131f555cb, type: 3} + m_Name: + m_EditorClassIdentifier: + m_SceneId: + m_Value: 0 + m_AssetId: + i0: 234 + i1: 158 + i2: 182 + i3: 71 + i4: 221 + i5: 1 + i6: 4 + i7: 190 + i8: 232 + i9: 175 + i10: 63 + i11: 36 + i12: 58 + i13: 50 + i14: 5 + i15: 86 + m_ServerOnly: 0 + m_LocalPlayerAuthority: 1 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkObserversObjectsWork/NetworkObserversObjectsWork.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkObserversObjectsWork/NetworkObserversObjectsWork.cs new file mode 100644 index 00000000..98208742 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/NetworkObserversObjectsWork/NetworkObserversObjectsWork.cs @@ -0,0 +1,69 @@ +using NUnit.Framework; +using System.Collections; +using UnityEngine; +using UnityEngine.TestTools; +using UnityEngine.Networking; + +#pragma warning disable 618 +public class NetworkObserversObjectsWork : SpawningTestBase +{ + private GameObject observerFar, observerClose; + bool isDone = false; + + [UnityTest] + public IEnumerator NetworkObserversObjectsCheck() + { + NetworkClient.ShutdownAll(); + NetworkServer.Reset(); + + SetupPrefabs(); + StartServer(); + StartLocalClient(); + + observerClose = (GameObject)Instantiate(rockPrefab, Vector3.zero, Quaternion.identity); + observerClose.AddComponent(); + observerClose.gameObject.name = "RockClose"; + + observerFar = (GameObject)Instantiate(rockPrefab, new Vector3(100, 100, 100), Quaternion.identity); + observerFar.AddComponent(); + observerFar.gameObject.name = "RockFar"; + + NetworkServer.Spawn(observerClose); + NetworkServer.Spawn(observerFar); + + while (!isDone) + { + yield return null; + } + + ClientScene.DestroyAllClientObjects(); + yield return null; + NetworkServer.Destroy(observerClose); + NetworkServer.Destroy(observerFar); + } + + public override void OnServerReady(GameObject player) + { + // add physics collider to player so proximity check will find it + player.AddComponent(); + var box = player.AddComponent(); + box.bounds.SetMinMax(Vector3.zero, new Vector3(1, 1, 1)); + + // rebuild observer lists + observerClose.GetComponent().RebuildObservers(false); + observerFar.GetComponent().RebuildObservers(false); + } + + public override void OnClientReady(short playerId) + { + Assert.AreEqual(1, observerClose.GetComponent().observers.Count, "Player sees observerClose object as it is close"); + Assert.AreEqual(0, observerFar.GetComponent().observers.Count, "Player doesn't see observerFar object as it is far away"); + + observerFar.transform.position = Vector3.zero; + observerFar.GetComponent().RebuildObservers(false); + Assert.AreEqual(1, observerFar.GetComponent().observers.Count, "Player sees observerFar object as it is close now"); + + isDone = true; + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/PlayWithReadyState/PlayWithReadyState.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/PlayWithReadyState/PlayWithReadyState.cs new file mode 100644 index 00000000..bf3a5c84 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/PlayWithReadyState/PlayWithReadyState.cs @@ -0,0 +1,216 @@ +using System.Collections; +using System.Collections.Generic; +using System; +using NUnit.Framework; +using UnityEngine.TestTools; +using UnityEngine; +using UnityEngine.Networking; +using UnityEngine.Networking.NetworkSystem; + +#pragma warning disable 618 +public class PlayWithReadyState +{ + public bool isDone = false; + static NetworkHash128 playerHash = NetworkHash128.Parse("abcd1"); + NetworkClient client1; + NetworkClient client2; + + const short MsgId1 = 99; + const short MsgId2 = 98; + const short MsgId3 = 97; + const short FromClientMsg1 = 95; + const short FromClientMsg2 = 94; + const short FromClientMsg3 = 93; + + public int numClientsConnected = 0; + + public int msg1Count = 0; + public int msg3Count = 0; + + public List actualListOfCallbacks = new List(); + public List resultListOfCallbacks = new List() + { + "CheckClientsConnected:1", + "CheckClientsConnected:2", + "OnServerFromClientMsg1", + "Msg1", + "Msg1", + "OnServerFromClientMsg2", + "Msg3", + "Msg3", + "OnServerFromClientMsg3" + }; + + [UnityTest] + public IEnumerator PlayWithReadyStateTest() + { + NetworkClient.ShutdownAll(); + NetworkServer.Reset(); + + GameObject nmObject = new GameObject(); + PlayWithReadyStateNetworkManager nmanager = nmObject.AddComponent(); + nmanager.networkAddress = "localhost"; + + ClientScene.RegisterSpawnHandler(playerHash, PlayWithReadyStateNetworkManager.OnSpawnPlayer, PlayWithReadyStateNetworkManager.OnUnSpawnPlayer); + + NetworkServer.RegisterHandler(FromClientMsg1, OnServerFromClientMsg1); + NetworkServer.RegisterHandler(FromClientMsg2, OnServerFromClientMsg2); + NetworkServer.RegisterHandler(FromClientMsg3, OnServerFromClientMsg3); + + nmanager.StartServer(); + client1 = nmanager.StartClient(); + client1.RegisterHandler(MsgType.Connect, OnClient1Connect); + client1.RegisterHandler(MsgId1, OnMsg1); + client1.RegisterHandler(MsgId2, OnMsg2); + client1.RegisterHandler(MsgId3, OnMsg3); + + // client2 is never ready, so should not recieve msgs + client2 = new NetworkClient(); + client2.RegisterHandler(MsgType.Connect, OnClient2Connect); + client2.RegisterHandler(MsgId1, OnMsg1); + client2.RegisterHandler(MsgId2, OnMsg2); + client2.RegisterHandler(MsgId3, OnMsg3); + client2.RegisterHandler(MsgType.NotReady, OnNotReady); + + Assert.IsTrue(NetworkServer.active, "Server is not started"); + Assert.IsTrue(NetworkClient.active, "Client is not started"); + + client2.Connect(NetworkManager.singleton.networkAddress, NetworkManager.singleton.networkPort); + + yield return null; + + while (!isDone) + { + yield return null; + } + + CollectionAssert.AreEqual(resultListOfCallbacks, actualListOfCallbacks, "Wrong order of callbacks or some callback is missing"); + + nmanager.StopServer(); + nmanager.StopClient(); + NetworkClient.ShutdownAll(); + UnityEngine.Object.Destroy(nmObject); + } + + //need to handle this message as it is sent by NetworkManager, + //but it can appear with delay - so we can't guarantee order + void OnNotReady(NetworkMessage netMsg) + { + } + + // Server Flow + // This block results in Msg1 printed twice (sent to same client twice) + void OnServerFromClientMsg1(NetworkMessage netMsg) + { + // both clients are connected now + actualListOfCallbacks.Add("OnServerFromClientMsg1"); + NetworkServer.SetClientReady(netMsg.conn); + + // this will go to only 1 client + NetworkServer.SendToReady(null, MsgId1, new EmptyMessage()); + + // this will go to only 1 client + var tm = NetworkManager.singleton as PlayWithReadyStateNetworkManager; + NetworkServer.SendToReady(tm.thePlayer, MsgId1, new EmptyMessage()); + } + + // This block results in Msg2 printed twice (sent to both clients) + void OnServerFromClientMsg2(NetworkMessage netMsg) + { + actualListOfCallbacks.Add("OnServerFromClientMsg2"); + NetworkServer.SetAllClientsNotReady(); + + // clients should NOT receive this + NetworkServer.SendToReady(null, MsgId2, new EmptyMessage()); + + // both clients SHOULD receive this + NetworkServer.SendToAll(MsgId3, new EmptyMessage()); + } + + private void OnServerFromClientMsg3(NetworkMessage netMsg) + { + actualListOfCallbacks.Add("OnServerFromClientMsg3"); + isDone = true; + } + + // Client Flow + void OnClient1Connect(NetworkMessage netMsg) + { + numClientsConnected += 1; + CheckClientsConnected(netMsg.conn); + } + + void OnClient2Connect(NetworkMessage netMsg) + { + numClientsConnected += 1; + CheckClientsConnected(netMsg.conn); + } + + void CheckClientsConnected(NetworkConnection conn) + { + actualListOfCallbacks.Add("CheckClientsConnected:" + numClientsConnected); + if (numClientsConnected == 2) + { + conn.Send(FromClientMsg1, new EmptyMessage()); + } + } + + void OnMsg1(NetworkMessage netMsg) + { + actualListOfCallbacks.Add("Msg1"); + msg1Count += 1; + if (msg1Count == 2) + { + netMsg.conn.Send(FromClientMsg2, new EmptyMessage()); + } + } + + void OnMsg2(NetworkMessage netMsg) + { + // should not ever be received! + Assert.Fail("This message should not be received: Msg2 " + netMsg.conn.connectionId); + } + + void OnMsg3(NetworkMessage netMsg) + { + actualListOfCallbacks.Add("Msg3"); + msg3Count += 1; + if (msg3Count == 2) + { + netMsg.conn.Send(FromClientMsg3, new EmptyMessage()); + } + } + + public class PlayWithReadyStateNetworkManager : NetworkManager + { + public GameObject thePlayer; + + public override void OnServerAddPlayer(NetworkConnection conn, short playerControllerId) + { + thePlayer = (GameObject)OnSpawnPlayer(Vector3.zero, playerHash); + NetworkServer.AddPlayerForConnection(conn, thePlayer, playerControllerId, playerHash); + } + + public static GameObject OnSpawnPlayer(Vector3 pos, NetworkHash128 assetId) + { + try + { + GameObject thePlayer = new GameObject(); + thePlayer.name = "PlayWithReadyStatePrefab"; + thePlayer.AddComponent(); + return thePlayer; + } + catch (Exception e) + { + Assert.Fail("Spawn exception " + e); + return null; + } + } + + public static void OnUnSpawnPlayer(GameObject unspawned) + { + Destroy(unspawned); + } + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/ReadyStateBehavesCorrectly/ReadyStateBehavesCorrectly.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/ReadyStateBehavesCorrectly/ReadyStateBehavesCorrectly.cs new file mode 100644 index 00000000..b5e1d46c --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/ReadyStateBehavesCorrectly/ReadyStateBehavesCorrectly.cs @@ -0,0 +1,108 @@ +using System.Collections; +using NUnit.Framework; +using UnityEngine.TestTools; +using UnityEngine; +using UnityEngine.Networking.NetworkSystem; +using UnityEngine.Networking; + +#pragma warning disable 618 +public class ReadyStateBehavesCorrectly +{ + int kListenPort = 7073; + bool isDone = false; + ConnectionConfig config; + NetworkClient myClient; + NetworkClient localClient; + + private int numClientConnects = 0; + private bool doDisconnect = false; + + [UnityTest] + public IEnumerator ReadyStateBehavesCorrectlyTest() + { + NetworkServer.Reset(); + NetworkClient.ShutdownAll(); + + NetworkServer.RegisterHandler(MsgType.Ready, OnServerReady); + + config = new ConnectionConfig(); + config.AddChannel(QosType.ReliableSequenced); + config.AddChannel(QosType.Unreliable); + + int retries = 0; + while (!NetworkServer.Listen("127.0.0.1", ++kListenPort)) + { + Assert.IsTrue(retries++ < 10, "Couldn't Listen for more than 10 retries"); + } + + myClient = new NetworkClient(); + if (!myClient.Configure(config, 10)) + { + Assert.Fail("Client configure failed"); + } + + myClient.RegisterHandler(MsgType.Connect, OnClient1Connected); + myClient.RegisterHandler(MsgType.Disconnect, OnClient1Disconnected); + myClient.Connect("127.0.0.1", kListenPort); + + while (!isDone) + { + yield return null; + if (doDisconnect) + { + ClientDisconnect(); + doDisconnect = false; + } + } + } + + public void OnServerReady(NetworkMessage netMsg) + { + if (numClientConnects == 1) + { + // server disconnects client + netMsg.conn.Disconnect(); + } + else if (numClientConnects <= 3) + { + // client will disconnect from server + doDisconnect = true; + } + } + + public void OnClient1Connected(NetworkMessage netMsg) + { + numClientConnects += 1; + ClientScene.Ready(netMsg.conn); + } + + public void OnClient1Disconnected(NetworkMessage netMsg) + { + //is called only for clients 1 and 3 + if (numClientConnects == 1) + { + myClient.Connect("127.0.0.1", kListenPort); + } + + if (numClientConnects == 3) + { + isDone = true; + } + } + + private void ClientDisconnect() + { + if (numClientConnects == 2) + { + myClient.Disconnect(); + localClient = ClientScene.ConnectLocalServer(); + localClient.RegisterHandler(MsgType.Connect, OnClient1Connected); + localClient.RegisterHandler(MsgType.Disconnect, OnClient1Disconnected); + } + else //for numClientConnects == 3 + { + localClient.Disconnect(); + } + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/RecursionDetectionHandlesComplexScripts/RecursionDetectionHandlesComplexScripts.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/RecursionDetectionHandlesComplexScripts/RecursionDetectionHandlesComplexScripts.cs new file mode 100644 index 00000000..599f5a97 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/RecursionDetectionHandlesComplexScripts/RecursionDetectionHandlesComplexScripts.cs @@ -0,0 +1,415 @@ +using System.Collections; +using NUnit.Framework; +using UnityEngine.TestTools; +using UnityEngine; +using UnityEngine.Networking; + +#pragma warning disable 618 +public class RecursionDetectionHandlesComplexScripts +{ + [UnityTest] + public IEnumerator RecursionDetectionHandlesComplexScriptsTest() + { + NetworkServer.Reset(); + NetworkClient.ShutdownAll(); + + GameObject go = new GameObject(); + go.name = "objectWithComplexScript"; + go.AddComponent(); + yield return null; + Assert.IsNotNull(GameObject.Find("objectWithComplexScript")); + yield return null; + + Object.Destroy(go); + } + + // Script with MANY MANY network attributes. Checks that the recursion detection in UNetWeaver wont generate a false positive on complex scripts. + public partial class UNetRecursionBehaviour : NetworkBehaviour + { + // 31 syncvars + [SyncVar] + public int var000; + [SyncVar] + public int var001; + [SyncVar] + public int var002; + [SyncVar] + public int var003; + [SyncVar] + public int var004; + [SyncVar] + public int var005; + [SyncVar] + public int var006; + [SyncVar] + public int var007; + [SyncVar] + public int var008; + [SyncVar] + public int var009; + + [SyncVar] + public int var010; + [SyncVar] + public int var011; + [SyncVar] + public int var012; + [SyncVar] + public int var013; + [SyncVar] + public int var014; + [SyncVar] + public int var015; + [SyncVar] + public int var016; + [SyncVar] + public int var017; + [SyncVar] + public int var018; + [SyncVar] + public int var019; + + [SyncVar] + public int var020; + [SyncVar] + public int var021; + [SyncVar] + public int var022; + [SyncVar] + public int var023; + [SyncVar] + public int var024; + [SyncVar] + public int var025; + [SyncVar] + public int var026; + [SyncVar] + public int var027; + [SyncVar] + public int var028; + [SyncVar] + public int var029; + + [SyncVar] + public int var030; + + // 50 Commands + [Command] + void CmdTest000(int p1, string p2) {} + [Command] + void CmdTest001(int p1, string p2) {} + [Command] + void CmdTest002(int p1, string p2) {} + [Command] + void CmdTest003(int p1, string p2) {} + [Command] + void CmdTest004(int p1, string p2) {} + [Command] + void CmdTest005(int p1, string p2) {} + [Command] + void CmdTest006(int p1, string p2) {} + [Command] + void CmdTest007(int p1, string p2) {} + [Command] + void CmdTest008(int p1, string p2) {} + [Command] + void CmdTest009(int p1, string p2) {} + + [Command] + void CmdTest010(int p1, string p2) {} + [Command] + void CmdTest011(int p1, string p2) {} + [Command] + void CmdTest012(int p1, string p2) {} + [Command] + void CmdTest013(int p1, string p2) {} + [Command] + void CmdTest014(int p1, string p2) {} + [Command] + void CmdTest015(int p1, string p2) {} + [Command] + void CmdTest016(int p1, string p2) {} + [Command] + void CmdTest017(int p1, string p2) {} + [Command] + void CmdTest018(int p1, string p2) {} + [Command] + void CmdTest019(int p1, string p2) {} + + [Command] + void CmdTest020(int p1, string p2) {} + [Command] + void CmdTest021(int p1, string p2) {} + [Command] + void CmdTest022(int p1, string p2) {} + [Command] + void CmdTest023(int p1, string p2) {} + [Command] + void CmdTest024(int p1, string p2) {} + [Command] + void CmdTest025(int p1, string p2) {} + [Command] + void CmdTest026(int p1, string p2) {} + [Command] + void CmdTest027(int p1, string p2) {} + [Command] + void CmdTest028(int p1, string p2) {} + [Command] + void CmdTest029(int p1, string p2) {} + + [Command] + void CmdTest030(int p1, string p2) {} + [Command] + void CmdTest031(int p1, string p2) {} + [Command] + void CmdTest032(int p1, string p2) {} + [Command] + void CmdTest033(int p1, string p2) {} + [Command] + void CmdTest034(int p1, string p2) {} + [Command] + void CmdTest035(int p1, string p2) {} + [Command] + void CmdTest036(int p1, string p2) {} + [Command] + void CmdTest037(int p1, string p2) {} + [Command] + void CmdTest038(int p1, string p2) {} + [Command] + void CmdTest039(int p1, string p2) {} + + [Command] + void CmdTest040(int p1, string p2) {} + [Command] + void CmdTest041(int p1, string p2) {} + [Command] + void CmdTest042(int p1, string p2) {} + [Command] + void CmdTest043(int p1, string p2) {} + [Command] + void CmdTest044(int p1, string p2) {} + [Command] + void CmdTest045(int p1, string p2) {} + [Command] + void CmdTest046(int p1, string p2) {} + [Command] + void CmdTest047(int p1, string p2) {} + [Command] + void CmdTest048(int p1, string p2) {} + [Command] + void CmdTest049(int p1, string p2) {} + + // 100 ClientRpcs + + [ClientRpc] + void RpcTest000(int p1, string p2) {} + [ClientRpc] + void RpcTest001(int p1, string p2) {} + [ClientRpc] + void RpcTest002(int p1, string p2) {} + [ClientRpc] + void RpcTest003(int p1, string p2) {} + [ClientRpc] + void RpcTest004(int p1, string p2) {} + [ClientRpc] + void RpcTest005(int p1, string p2) {} + [ClientRpc] + void RpcTest006(int p1, string p2) {} + [ClientRpc] + void RpcTest007(int p1, string p2) {} + [ClientRpc] + void RpcTest008(int p1, string p2) {} + [ClientRpc] + void RpcTest009(int p1, string p2) {} + + [ClientRpc] + void RpcTest010(int p1, string p2) {} + [ClientRpc] + void RpcTest011(int p1, string p2) {} + [ClientRpc] + void RpcTest012(int p1, string p2) {} + [ClientRpc] + void RpcTest013(int p1, string p2) {} + [ClientRpc] + void RpcTest014(int p1, string p2) {} + [ClientRpc] + void RpcTest015(int p1, string p2) {} + [ClientRpc] + void RpcTest016(int p1, string p2) {} + [ClientRpc] + void RpcTest017(int p1, string p2) {} + [ClientRpc] + void RpcTest018(int p1, string p2) {} + [ClientRpc] + void RpcTest019(int p1, string p2) {} + + [ClientRpc] + void RpcTest020(int p1, string p2) {} + [ClientRpc] + void RpcTest021(int p1, string p2) {} + [ClientRpc] + void RpcTest022(int p1, string p2) {} + [ClientRpc] + void RpcTest023(int p1, string p2) {} + [ClientRpc] + void RpcTest024(int p1, string p2) {} + [ClientRpc] + void RpcTest025(int p1, string p2) {} + [ClientRpc] + void RpcTest026(int p1, string p2) {} + [ClientRpc] + void RpcTest027(int p1, string p2) {} + [ClientRpc] + void RpcTest028(int p1, string p2) {} + [ClientRpc] + void RpcTest029(int p1, string p2) {} + + [ClientRpc] + void RpcTest030(int p1, string p2) {} + [ClientRpc] + void RpcTest031(int p1, string p2) {} + [ClientRpc] + void RpcTest032(int p1, string p2) {} + [ClientRpc] + void RpcTest033(int p1, string p2) {} + [ClientRpc] + void RpcTest034(int p1, string p2) {} + [ClientRpc] + void RpcTest035(int p1, string p2) {} + [ClientRpc] + void RpcTest036(int p1, string p2) {} + [ClientRpc] + void RpcTest037(int p1, string p2) {} + [ClientRpc] + void RpcTest038(int p1, string p2) {} + [ClientRpc] + void RpcTest039(int p1, string p2) {} + + [ClientRpc] + void RpcTest040(int p1, string p2) {} + [ClientRpc] + void RpcTest041(int p1, string p2) {} + [ClientRpc] + void RpcTest042(int p1, string p2) {} + [ClientRpc] + void RpcTest043(int p1, string p2) {} + [ClientRpc] + void RpcTest044(int p1, string p2) {} + [ClientRpc] + void RpcTest045(int p1, string p2) {} + [ClientRpc] + void RpcTest046(int p1, string p2) {} + [ClientRpc] + void RpcTest047(int p1, string p2) {} + [ClientRpc] + void RpcTest048(int p1, string p2) {} + [ClientRpc] + void RpcTest049(int p1, string p2) {} + + [ClientRpc] + void RpcTest100(int p1, string p2) {} + [ClientRpc] + void RpcTest101(int p1, string p2) {} + [ClientRpc] + void RpcTest102(int p1, string p2) {} + [ClientRpc] + void RpcTest103(int p1, string p2) {} + [ClientRpc] + void RpcTest104(int p1, string p2) {} + [ClientRpc] + void RpcTest105(int p1, string p2) {} + [ClientRpc] + void RpcTest106(int p1, string p2) {} + [ClientRpc] + void RpcTest107(int p1, string p2) {} + [ClientRpc] + void RpcTest108(int p1, string p2) {} + [ClientRpc] + void RpcTest109(int p1, string p2) {} + + [ClientRpc] + void RpcTest110(int p1, string p2) {} + [ClientRpc] + void RpcTest111(int p1, string p2) {} + [ClientRpc] + void RpcTest112(int p1, string p2) {} + [ClientRpc] + void RpcTest113(int p1, string p2) {} + [ClientRpc] + void RpcTest114(int p1, string p2) {} + [ClientRpc] + void RpcTest115(int p1, string p2) {} + [ClientRpc] + void RpcTest116(int p1, string p2) {} + [ClientRpc] + void RpcTest117(int p1, string p2) {} + [ClientRpc] + void RpcTest118(int p1, string p2) {} + [ClientRpc] + void RpcTest119(int p1, string p2) {} + + [ClientRpc] + void RpcTest120(int p1, string p2) {} + [ClientRpc] + void RpcTest121(int p1, string p2) {} + [ClientRpc] + void RpcTest122(int p1, string p2) {} + [ClientRpc] + void RpcTest123(int p1, string p2) {} + [ClientRpc] + void RpcTest124(int p1, string p2) {} + [ClientRpc] + void RpcTest125(int p1, string p2) {} + [ClientRpc] + void RpcTest126(int p1, string p2) {} + [ClientRpc] + void RpcTest127(int p1, string p2) {} + [ClientRpc] + void RpcTest128(int p1, string p2) {} + [ClientRpc] + void RpcTest129(int p1, string p2) {} + + [ClientRpc] + void RpcTest130(int p1, string p2) {} + [ClientRpc] + void RpcTest131(int p1, string p2) {} + [ClientRpc] + void RpcTest132(int p1, string p2) {} + [ClientRpc] + void RpcTest133(int p1, string p2) {} + [ClientRpc] + void RpcTest134(int p1, string p2) {} + [ClientRpc] + void RpcTest135(int p1, string p2) {} + [ClientRpc] + void RpcTest136(int p1, string p2) {} + [ClientRpc] + void RpcTest137(int p1, string p2) {} + [ClientRpc] + void RpcTest138(int p1, string p2) {} + [ClientRpc] + void RpcTest139(int p1, string p2) {} + + [ClientRpc] + void RpcTest140(int p1, string p2) {} + [ClientRpc] + void RpcTest141(int p1, string p2) {} + [ClientRpc] + void RpcTest142(int p1, string p2) {} + [ClientRpc] + void RpcTest143(int p1, string p2) {} + [ClientRpc] + void RpcTest144(int p1, string p2) {} + [ClientRpc] + void RpcTest145(int p1, string p2) {} + [ClientRpc] + void RpcTest146(int p1, string p2) {} + [ClientRpc] + void RpcTest147(int p1, string p2) {} + [ClientRpc] + void RpcTest148(int p1, string p2) {} + [ClientRpc] + void RpcTest149(int p1, string p2) {} + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/SettingNetworkStartPositionWorks/SettingNetworkStartPositionWorks.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/SettingNetworkStartPositionWorks/SettingNetworkStartPositionWorks.cs new file mode 100644 index 00000000..e23f832a --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/SettingNetworkStartPositionWorks/SettingNetworkStartPositionWorks.cs @@ -0,0 +1,58 @@ +using System.Collections; +using NUnit.Framework; +using UnityEngine.TestTools; +using UnityEngine; +using UnityEngine.Networking; + +#pragma warning disable 618 +public class SettingNetworkStartPositionWorks +{ + public static Vector3 startpos = new Vector3(1.4f, 6.3f, 6.23f); + + public class TestNetworkManagerStartPos : NetworkManager + { + public bool isDone = false; + + public override void OnServerAddPlayer(NetworkConnection conn, short playerControllerId) + { + base.OnServerAddPlayer(conn, playerControllerId); + StringAssert.IsMatch(conn.playerControllers[0].gameObject.transform.position.ToString(), startpos.ToString()); + isDone = true; + } + } + + [UnityTest] + public IEnumerator SettingNetworkStartPositionWorksTest() + { + NetworkServer.Reset(); + NetworkClient.ShutdownAll(); + + GameObject nmObject = new GameObject(); + TestNetworkManagerStartPos nmanager = nmObject.AddComponent(); + nmanager.playerPrefab = Resources.Load("CleanPlayerPrefab", typeof(GameObject)) as GameObject; + nmanager.networkAddress = "localhost"; + + var start = new GameObject(); + start.transform.position = startpos; + start.AddComponent(); + + nmanager.StartServer(); + nmanager.StartClient(); + yield return null; + + Assert.IsTrue(NetworkServer.active, "Server is not started"); + Assert.IsTrue(NetworkClient.active, "Client is not started"); + yield return null; + + while (!nmanager.isDone) + { + yield return null; + } + + NetworkManager.singleton.StopServer(); + NetworkManager.singleton.StopClient(); + + Object.Destroy(nmObject); + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/SpawningTests/BaseClass/SpawningTestBase.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/SpawningTests/BaseClass/SpawningTestBase.cs new file mode 100644 index 00000000..df71b658 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/SpawningTests/BaseClass/SpawningTestBase.cs @@ -0,0 +1,153 @@ +using NUnit.Framework; +using UnityEngine; +using UnityEngine.Networking; + +#pragma warning disable 618 +public class SpawningTestBase : MonoBehaviour +{ + // CreateNamedPrefab - simply use prefabs in Resources folder + + int listenPort = 7073; + private const short kReadyMsgId = 55; + public const short kStringMsgId = 56; + + // One player per client by default + int m_PlayerCount = 1; + protected NetworkClient myClient; + public GameObject playerObj; + + protected static GameObject playerPrefab; + protected static GameObject rockPrefab; + public static int numStartServer = 0; + public static int numStartClient = 0; + public static int numDestroyClient = 0; + + public static void IncrementStartServer() + { + numStartServer += 1; + } + + public static void IncrementStartClient() + { + numStartClient += 1; + } + + public static void IncrementDestroyClient() + { + numDestroyClient += 1; + } + + public void SetupPrefabs() + { + playerPrefab = Resources.Load("SpawningBase_PlayerPrefab", typeof(GameObject)) as GameObject; + rockPrefab = Resources.Load("SpawningBase_SpawnableObjectPrefab", typeof(GameObject)) as GameObject; + + numStartServer = 0; + numStartClient = 0; + numDestroyClient = 0; + } + + public void StartServer() + { + NetworkServer.Reset(); + NetworkServer.RegisterHandler(MsgType.Disconnect, OnServerDisconnected); + NetworkServer.RegisterHandler(MsgType.AddPlayer, OnAddPlayer); + NetworkServer.RegisterHandler(kStringMsgId, OnServerStringMessage); + + int retries = 0; + while (!NetworkServer.Listen("127.0.0.1", ++listenPort)) + { + Assert.IsTrue(retries++ < 10, "Couldn't Listen for more than 10 retries"); + } + } + + internal void RegisterClientData() + { + // Just use default handler + myClient.RegisterHandler(MsgType.Connect, OnClientConnected); + myClient.RegisterHandler(kReadyMsgId, OnClientReadyInternal); + myClient.RegisterHandler(kStringMsgId, OnClientStringMessage); + + ClientScene.RegisterPrefab(playerPrefab); + ClientScene.RegisterPrefab(rockPrefab); + } + + public void StartClientAndConnect() + { + myClient = new NetworkClient(); + // not sure if we need custom config + // if (!myClient.Configure(config, maxConnections)) + // { + // Assert.Fail("Client configure failed"); + // } + + RegisterClientData(); + myClient.Connect("127.0.0.1", listenPort); + } + + public void StartLocalClient() + { + StartLocalClient(1); + } + + public void StartLocalClient(int playerCount) + { + m_PlayerCount = playerCount; + myClient = ClientScene.ConnectLocalServer(); + RegisterClientData(); + } + + public void OnServerDisconnected(NetworkMessage netMsg) + { + NetworkServer.DestroyPlayersForConnection(netMsg.conn); + } + + public void OnAddPlayer(NetworkMessage netMsg) + { + var msg = netMsg.ReadMessage(); + playerObj = (GameObject)Instantiate(playerPrefab, Vector3.zero, Quaternion.identity); + + SpawningBase_PlayerScript script = playerObj.GetComponent(); // need to add this script ot prefab in Resources + script.intValue = 999; + script.floatValue = 55.5f; + + NetworkServer.AddPlayerForConnection(netMsg.conn, playerObj, msg.playerControllerId); + + OnServerReady(playerObj); + + NetworkServer.SendToClientOfPlayer(playerObj, kReadyMsgId, msg); + } + + public void OnClientConnected(NetworkMessage netMsg) + { + ClientScene.AddPlayer(netMsg.conn, 0); + + for (int i = 1; i < m_PlayerCount; i++) + { + ClientScene.AddPlayer((short)(i + 1)); + } + } + + public void OnClientReadyInternal(NetworkMessage netMsg) + { + var msg = netMsg.ReadMessage(); + OnClientReady(msg.playerControllerId); + } + + public virtual void OnServerReady(GameObject player) + { + } + + public virtual void OnClientReady(short playerId) + { + } + + public virtual void OnClientStringMessage(NetworkMessage netMsg) + { + } + + public virtual void OnServerStringMessage(NetworkMessage netMsg) + { + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/SpawningTests/LocalClientSpawnsMultiplePlayers.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/SpawningTests/LocalClientSpawnsMultiplePlayers.cs new file mode 100644 index 00000000..fe4b8fba --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/SpawningTests/LocalClientSpawnsMultiplePlayers.cs @@ -0,0 +1,62 @@ +using System.Collections; +using System.Collections.Generic; +using NUnit.Framework; +using UnityEngine.TestTools; +using UnityEngine; +using UnityEngine.Networking; + +#pragma warning disable 618 +public class LocalClientSpawnsMultiplePlayers : SpawningTestBase +{ + const int kPlayerCount = 2; + List m_ReadyPlayers = new List(); + private int numPlayers = 0; + GameObject obj; + + [UnityTest] + public IEnumerator LocalClientSpawnsMultiplePlayersTest() + { + NetworkClient.ShutdownAll(); + NetworkServer.Reset(); + + SetupPrefabs(); + StartServer(); + StartLocalClient(kPlayerCount); + + while (m_ReadyPlayers.Count != kPlayerCount) + { + yield return null; + } + + ClientScene.DestroyAllClientObjects(); + yield return null; + NetworkServer.Destroy(obj); + NetworkServer.Destroy(playerObj); + } + + public override void OnServerReady(GameObject player) + { + obj = (GameObject)Instantiate(rockPrefab, Vector3.zero, Quaternion.identity); + NetworkServer.Spawn(obj); + + // rock + this player + Assert.AreEqual(numPlayers + 2, numStartServer); + Assert.AreEqual(numPlayers + 2, numStartClient); + + numPlayers += 2; + } + + public override void OnClientReady(short playerId) + { + // Sanity check. Make sure these are unique player IDs each time + if (!m_ReadyPlayers.Contains(playerId)) + { + m_ReadyPlayers.Add(playerId); + } + else + { + Assert.Fail("Player with such Id already exist"); + } + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/SpawningTests/LocalClientSpawnsObjectAfterConnect.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/SpawningTests/LocalClientSpawnsObjectAfterConnect.cs new file mode 100644 index 00000000..1d58fc06 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/SpawningTests/LocalClientSpawnsObjectAfterConnect.cs @@ -0,0 +1,45 @@ +using System.Collections; +using NUnit.Framework; +using UnityEngine.TestTools; +using UnityEngine; +using UnityEngine.Networking; + +#pragma warning disable 618 +public class LocalClientSpawnsObjectAfterConnect : SpawningTestBase +{ + bool isDone; + GameObject obj; + + [UnityTest] + public IEnumerator LocalClientSpawnsObjectAfterConnectTest() + { + NetworkClient.ShutdownAll(); + NetworkServer.Reset(); + + SetupPrefabs(); + StartServer(); + StartLocalClient(); + + while (!isDone) + { + yield return null; + } + + // 2 is player and rock + Assert.AreEqual(2, numStartServer); + Assert.AreEqual(2, numStartClient); + + ClientScene.DestroyAllClientObjects(); + yield return null; + NetworkServer.Destroy(obj); + NetworkServer.Destroy(playerObj); + } + + public override void OnServerReady(GameObject player) + { + obj = (GameObject)Instantiate(rockPrefab, Vector3.zero, Quaternion.identity); + NetworkServer.Spawn(obj); + isDone = true; + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/SpawningTests/LocalClientSpawnsObjectBeforeConnect.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/SpawningTests/LocalClientSpawnsObjectBeforeConnect.cs new file mode 100644 index 00000000..38253230 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/SpawningTests/LocalClientSpawnsObjectBeforeConnect.cs @@ -0,0 +1,46 @@ +using System.Collections; +using NUnit.Framework; +using UnityEngine.TestTools; +using UnityEngine; +using UnityEngine.Networking; + +#pragma warning disable 618 +public class LocalClientSpawnsObjectBeforeConnect : SpawningTestBase +{ + bool isDone; + GameObject obj; + + [UnityTest] + public IEnumerator LocalClientSpawnsObjectBeforeConnectTest() + { + NetworkClient.ShutdownAll(); + NetworkServer.Reset(); + + SetupPrefabs(); + StartServer(); + + obj = (GameObject)Instantiate(rockPrefab, Vector3.zero, Quaternion.identity); + NetworkServer.Spawn(obj); + + StartLocalClient(); + + while (!isDone) + { + yield return null; + } + + ClientScene.DestroyAllClientObjects(); + yield return null; + NetworkServer.Destroy(obj); + NetworkServer.Destroy(playerObj); + } + + public override void OnServerReady(GameObject player) + { + // 2 is player and rock + Assert.AreEqual(2, numStartServer); + Assert.AreEqual(2, numStartClient); + isDone = true; + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/SpawningTests/Resources/SpawningBase_PlayerPrefab.prefab b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/SpawningTests/Resources/SpawningBase_PlayerPrefab.prefab new file mode 100644 index 00000000..2f909720 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/SpawningTests/Resources/SpawningBase_PlayerPrefab.prefab @@ -0,0 +1,145 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!1001 &100100000 +Prefab: + m_ObjectHideFlags: 1 + serializedVersion: 2 + m_Modification: + m_TransformParent: {fileID: 0} + m_Modifications: [] + m_RemovedComponents: [] + m_ParentPrefab: {fileID: 0} + m_RootGameObject: {fileID: 1873923016790054} + m_IsPrefabParent: 1 +--- !u!1 &1873923016790054 +GameObject: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + serializedVersion: 5 + m_Component: + - component: {fileID: 4724899533531532} + - component: {fileID: 33138031125937212} + - component: {fileID: 23215592827078678} + - component: {fileID: 65412238776160816} + - component: {fileID: 114224568570801332} + - component: {fileID: 114515388448827666} + m_Layer: 0 + m_Name: SpawningBase_PlayerPrefab + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &4724899533531532 +Transform: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1873923016790054} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!23 &23215592827078678 +MeshRenderer: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1873923016790054} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RenderingLayerMask: 4294967295 + m_Materials: + - {fileID: 10303, guid: 0000000000000000f000000000000000, type: 0} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 +--- !u!33 &33138031125937212 +MeshFilter: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1873923016790054} + m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0} +--- !u!65 &65412238776160816 +BoxCollider: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1873923016790054} + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_Enabled: 1 + serializedVersion: 2 + m_Size: {x: 1, y: 1, z: 1} + m_Center: {x: 0, y: 0, z: 0} +--- !u!114 &114224568570801332 +MonoBehaviour: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1873923016790054} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 372142912, guid: dc443db3e92b4983b9738c1131f555cb, type: 3} + m_Name: + m_EditorClassIdentifier: + m_SceneId: + m_Value: 0 + m_AssetId: + i0: 28 + i1: 204 + i2: 14 + i3: 67 + i4: 65 + i5: 209 + i6: 128 + i7: 244 + i8: 40 + i9: 252 + i10: 81 + i11: 221 + i12: 202 + i13: 181 + i14: 94 + i15: 234 + m_ServerOnly: 0 + m_LocalPlayerAuthority: 1 +--- !u!114 &114515388448827666 +MonoBehaviour: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1873923016790054} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: ec2008c107e8a1b4b8222ddb5f7ffbf0, type: 3} + m_Name: + m_EditorClassIdentifier: + intValue: 0 + floatValue: 0 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/SpawningTests/Resources/SpawningBase_PlayerScript.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/SpawningTests/Resources/SpawningBase_PlayerScript.cs new file mode 100644 index 00000000..7b4893cf --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/SpawningTests/Resources/SpawningBase_PlayerScript.cs @@ -0,0 +1,27 @@ +using NUnit.Framework; +using UnityEngine.Networking; + +#pragma warning disable 618 +public class SpawningBase_PlayerScript : NetworkBehaviour +{ + [SyncVar] + public int intValue; + + [SyncVar] + public float floatValue; + + public override void OnStartServer() + { + Assert.AreEqual(intValue, 999); + Assert.AreEqual(floatValue, 55.5f); + SpawningTestBase.IncrementStartServer(); + } + + public override void OnStartClient() + { + Assert.AreEqual(intValue, 999); + Assert.AreEqual(floatValue, 55.5f); + SpawningTestBase.IncrementStartClient(); + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/SpawningTests/Resources/SpawningBase_SpawnableObjectPrefab.prefab b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/SpawningTests/Resources/SpawningBase_SpawnableObjectPrefab.prefab new file mode 100644 index 00000000..fa43bab9 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/SpawningTests/Resources/SpawningBase_SpawnableObjectPrefab.prefab @@ -0,0 +1,143 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!1001 &100100000 +Prefab: + m_ObjectHideFlags: 1 + serializedVersion: 2 + m_Modification: + m_TransformParent: {fileID: 0} + m_Modifications: [] + m_RemovedComponents: [] + m_ParentPrefab: {fileID: 0} + m_RootGameObject: {fileID: 1825730589472640} + m_IsPrefabParent: 1 +--- !u!1 &1825730589472640 +GameObject: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + serializedVersion: 5 + m_Component: + - component: {fileID: 4350670242350864} + - component: {fileID: 33483871696536668} + - component: {fileID: 23883713217033572} + - component: {fileID: 135279845048574246} + - component: {fileID: 114236485685277416} + - component: {fileID: 114143015368681524} + m_Layer: 0 + m_Name: SpawningBase_SpawnableObjectPrefab + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &4350670242350864 +Transform: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1825730589472640} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!23 &23883713217033572 +MeshRenderer: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1825730589472640} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RenderingLayerMask: 4294967295 + m_Materials: + - {fileID: 10303, guid: 0000000000000000f000000000000000, type: 0} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 +--- !u!33 &33483871696536668 +MeshFilter: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1825730589472640} + m_Mesh: {fileID: 10207, guid: 0000000000000000e000000000000000, type: 0} +--- !u!114 &114143015368681524 +MonoBehaviour: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1825730589472640} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 0f2edb38790e9884ea9580b5060a9f5e, type: 3} + m_Name: + m_EditorClassIdentifier: +--- !u!114 &114236485685277416 +MonoBehaviour: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1825730589472640} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 372142912, guid: dc443db3e92b4983b9738c1131f555cb, type: 3} + m_Name: + m_EditorClassIdentifier: + m_SceneId: + m_Value: 0 + m_AssetId: + i0: 172 + i1: 232 + i2: 70 + i3: 72 + i4: 218 + i5: 76 + i6: 126 + i7: 84 + i8: 202 + i9: 2 + i10: 212 + i11: 172 + i12: 217 + i13: 78 + i14: 202 + i15: 94 + m_ServerOnly: 0 + m_LocalPlayerAuthority: 0 +--- !u!135 &135279845048574246 +SphereCollider: + m_ObjectHideFlags: 1 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1825730589472640} + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_Enabled: 1 + serializedVersion: 2 + m_Radius: 0.5 + m_Center: {x: 0, y: 0, z: 0} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/SpawningTests/Resources/SpawningBase_SpawnableObjectScript.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/SpawningTests/Resources/SpawningBase_SpawnableObjectScript.cs new file mode 100644 index 00000000..cf43a36c --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/SpawningTests/Resources/SpawningBase_SpawnableObjectScript.cs @@ -0,0 +1,21 @@ +using UnityEngine.Networking; + +#pragma warning disable 618 +public class SpawningBase_SpawnableObjectScript : NetworkBehaviour +{ + public override void OnStartServer() + { + SpawningTestBase.IncrementStartServer(); + } + + public override void OnStartClient() + { + SpawningTestBase.IncrementStartClient(); + } + + public override void OnNetworkDestroy() + { + SpawningTestBase.IncrementDestroyClient(); + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/SpawningTests/SpawnObjectAfterConnect.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/SpawningTests/SpawnObjectAfterConnect.cs new file mode 100644 index 00000000..f23328d2 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/SpawningTests/SpawnObjectAfterConnect.cs @@ -0,0 +1,48 @@ +using System.Collections; +using NUnit.Framework; +using UnityEngine.TestTools; +using UnityEngine; +using UnityEngine.Networking; + +#pragma warning disable 618 +public class SpawnObjectAfterConnect : SpawningTestBase +{ + bool isDone; + GameObject obj; + + [UnityTest] + public IEnumerator SpawnObjectAfterConnectTest() + { + NetworkClient.ShutdownAll(); + NetworkServer.Reset(); + + SetupPrefabs(); + StartServer(); + NetworkServer.SpawnObjects(); + StartClientAndConnect(); + + while (!isDone) + { + yield return null; + } + ClientScene.DestroyAllClientObjects(); + yield return null; + NetworkServer.Destroy(obj); + NetworkServer.Destroy(playerObj); + } + + public override void OnServerReady(GameObject player) + { + obj = (GameObject)Instantiate(rockPrefab, Vector3.zero, Quaternion.identity); + NetworkServer.Spawn(obj); + + Assert.AreEqual(2, numStartServer); + } + + public override void OnClientReady(short playerId) + { + Assert.AreEqual(2, numStartClient); + isDone = true; + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/SpawningTests/SpawnObjectBeforeConnect.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/SpawningTests/SpawnObjectBeforeConnect.cs new file mode 100644 index 00000000..4d105f2f --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/SpawningTests/SpawnObjectBeforeConnect.cs @@ -0,0 +1,47 @@ +using System.Collections; +using NUnit.Framework; +using UnityEngine.TestTools; +using UnityEngine; +using UnityEngine.Networking; + +#pragma warning disable 618 +public class SpawnObjectBeforeConnect : SpawningTestBase +{ + bool isDone; + + [UnityTest] + public IEnumerator SpawnObjectBeforeConnectTest() + { + NetworkClient.ShutdownAll(); + NetworkServer.Reset(); + + SetupPrefabs(); + StartServer(); + + GameObject obj = (GameObject)Instantiate(rockPrefab, Vector3.zero, Quaternion.identity); + NetworkServer.Spawn(obj); + StartClientAndConnect(); + + while (!isDone) + { + yield return null; + } + + ClientScene.DestroyAllClientObjects(); + yield return null; + NetworkServer.Destroy(obj); + NetworkServer.Destroy(playerObj); + } + + public override void OnServerReady(GameObject player) + { + Assert.AreEqual(2, numStartServer); + } + + public override void OnClientReady(short playerId) + { + Assert.AreEqual(2, numStartClient); + isDone = true; + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/SpawningTests/SpawnObjectOnServerOnly.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/SpawningTests/SpawnObjectOnServerOnly.cs new file mode 100644 index 00000000..440a53d8 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/SpawningTests/SpawnObjectOnServerOnly.cs @@ -0,0 +1,31 @@ +using System.Collections; +using NUnit.Framework; +using UnityEngine.TestTools; +using UnityEngine; +using UnityEngine.Networking; + +#pragma warning disable 618 +public class SpawnObjectOnServerOnly : SpawningTestBase +{ + GameObject obj; + + [UnityTest] + public IEnumerator SpawnObjectOnServerOnlyTest() + { + NetworkClient.ShutdownAll(); + NetworkServer.Reset(); + + SetupPrefabs(); + StartServer(); + + obj = (GameObject)Instantiate(rockPrefab, Vector3.zero, Quaternion.identity); + NetworkServer.Spawn(obj); + yield return null; + + // 1 is rock, there is no player + Assert.AreEqual(1, numStartServer); + + NetworkServer.Destroy(obj); + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/SpawningTests/SpawnObjectThenDeleteItAfterConnect.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/SpawningTests/SpawnObjectThenDeleteItAfterConnect.cs new file mode 100644 index 00000000..a1f4f327 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/SpawningTests/SpawnObjectThenDeleteItAfterConnect.cs @@ -0,0 +1,49 @@ +using System.Collections; +using NUnit.Framework; +using UnityEngine.TestTools; +using UnityEngine; +using UnityEngine.Networking; + +#pragma warning disable 618 +public class SpawnObjectThenDeleteItAfterConnect : SpawningTestBase +{ + private GameObject deleteMe; + bool isDone = false; + + [UnityTest] + public IEnumerator SpawnObjectThenDeleteItAfterConnectTest() + { + NetworkClient.ShutdownAll(); + NetworkServer.Reset(); + + SetupPrefabs(); + StartServer(); + + deleteMe = (GameObject)Instantiate(rockPrefab, Vector3.zero, Quaternion.identity); + NetworkServer.Spawn(deleteMe); + + StartClientAndConnect(); + + while (!isDone) + { + yield return null; + } + + ClientScene.DestroyAllClientObjects(); + yield return null; + NetworkServer.Destroy(playerObj); + } + + public override void OnServerReady(GameObject player) + { + NetworkServer.Destroy(deleteMe); + Assert.AreEqual(2, numStartServer, "StartServer should be called 2 times - for player and SpawnableObject"); + } + + public override void OnClientReady(short playerId) + { + Assert.AreEqual(2, numStartClient, "StartClient should be called 2 times - for player and SpawnableObject"); + isDone = true; + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/SpawningTests/SpawnObjectThenDeleteItBeforeConnect.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/SpawningTests/SpawnObjectThenDeleteItBeforeConnect.cs new file mode 100644 index 00000000..bf40b43b --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/SpawningTests/SpawnObjectThenDeleteItBeforeConnect.cs @@ -0,0 +1,47 @@ +using System.Collections; +using NUnit.Framework; +using UnityEngine.TestTools; +using UnityEngine; +using UnityEngine.Networking; + +#pragma warning disable 618 +public class SpawnObjectThenDeleteItBeforeConnect : SpawningTestBase +{ + bool isDone = false; + + [UnityTest] + public IEnumerator SpawnObjectThenDeleteItBeforeConnectTest() + { + NetworkClient.ShutdownAll(); + NetworkServer.Reset(); + + SetupPrefabs(); + StartServer(); + NetworkServer.SpawnObjects(); + + GameObject obj = (GameObject)Instantiate(rockPrefab, Vector3.zero, Quaternion.identity); + NetworkServer.Spawn(obj); + yield return new WaitForSeconds(2); + NetworkServer.Destroy(obj); + + StartClientAndConnect(); + + while (!isDone) + { + yield return null; + } + + ClientScene.DestroyAllClientObjects(); + yield return null; + NetworkServer.Destroy(playerObj); + } + + public override void OnClientReady(short playerId) + { + Assert.AreEqual(2, numStartServer, "StartServer should be called 2 times - for player and SpawnableObject"); + Assert.AreEqual(1, numStartClient, "StartClient should be called 1 time - for player only"); // 1 for player + Assert.AreEqual(0, numDestroyClient, "numDestroyClient should be 0, as there was no SpawnableObject on the Client"); //no rock on client + isDone = true; + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/TwoInstancesOfServerSimpleWorkInOneProcess/TwoInstancesOfServerSimpleWorkInOneProcess.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/TwoInstancesOfServerSimpleWorkInOneProcess/TwoInstancesOfServerSimpleWorkInOneProcess.cs new file mode 100644 index 00000000..271a4909 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/TwoInstancesOfServerSimpleWorkInOneProcess/TwoInstancesOfServerSimpleWorkInOneProcess.cs @@ -0,0 +1,99 @@ +using System.Collections; +using NUnit.Framework; +using UnityEngine.TestTools; +using UnityEngine; +using UnityEngine.Networking; +using UnityEngine.Networking.NetworkSystem; + +#pragma warning disable 618 +public class TwoInstancesOfServerSimpleWorkInOneProcess +{ + NetworkServerSimple server1; + NetworkServerSimple server2; + NetworkClient client1; + NetworkClient client2; + + const int port1 = 7003; + const int port2 = 7004; + + const short TestMsgId = 1000; + int actualMsgCount = 0; + int expectedMsgCount = 0; + + [UnityTest] + public IEnumerator TwoInstancesOfServerSimpleWorkInOneProcessTest() + { + NetworkClient.ShutdownAll(); + NetworkServer.Reset(); + + server1 = new NetworkServerSimple(); + server1.RegisterHandler(MsgType.Connect, OnServerConnect1); + server1.RegisterHandler(TestMsgId, OnServerMsg1); + + server2 = new NetworkServerSimple(); + server2.RegisterHandler(MsgType.Connect, OnServerConnect2); + server2.RegisterHandler(TestMsgId, OnServerMsg2); + + Assert.IsTrue(server1.Listen(port1), "Server1 Listen failed"); + Assert.IsTrue(server2.Listen(port2), "Server2 Listen failed"); + + client1 = new NetworkClient(); + client1.RegisterHandler(MsgType.Connect, OnClientConnect1); + client1.RegisterHandler(TestMsgId, OnClientMsg1); + + client2 = new NetworkClient(); + client2.RegisterHandler(MsgType.Connect, OnClientConnect2); + client2.RegisterHandler(TestMsgId, OnClientMsg2); + + client1.Connect("localhost", port1); + client2.Connect("localhost", port2); + + while (actualMsgCount != expectedMsgCount) + { + yield return null; + } + } + + void OnServerConnect1(NetworkMessage netMsg) + { + actualMsgCount += 1; + } + + void OnServerConnect2(NetworkMessage netMsg) + { + actualMsgCount += 1; + } + + void OnServerMsg1(NetworkMessage netMsg) + { + actualMsgCount += 1; + netMsg.conn.Send(TestMsgId, new EmptyMessage()); + } + + void OnServerMsg2(NetworkMessage netMsg) + { + actualMsgCount += 1; + netMsg.conn.Send(TestMsgId, new EmptyMessage()); + } + + void OnClientConnect1(NetworkMessage netMsg) + { + netMsg.conn.Send(TestMsgId, new EmptyMessage()); + } + + void OnClientConnect2(NetworkMessage netMsg) + { + netMsg.conn.Send(TestMsgId, new EmptyMessage()); + } + + void OnClientMsg1(NetworkMessage netMsg) + { + actualMsgCount += 1; + } + + void OnClientMsg2(NetworkMessage netMsg) + { + actualMsgCount += 1; + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/WeaverILGenerationTests_Classes/WeaverILGenerationTests_SyncLists.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/WeaverILGenerationTests_Classes/WeaverILGenerationTests_SyncLists.cs new file mode 100644 index 00000000..eb8576b1 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/WeaverILGenerationTests_Classes/WeaverILGenerationTests_SyncLists.cs @@ -0,0 +1,29 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.Networking; + +#pragma warning disable 618 +public class WeaverILGenerationTests_SyncLists_Base : NetworkBehaviour +{ + [SyncVar] public GameObject baseSyncObject; + void Awake() + { + Debug.Log("just here so compiler does not optimize away this"); + } +} + +public class WeaverILGenerationTests_SyncLists : WeaverILGenerationTests_SyncLists_Base +{ + public SyncListInt Inited = new SyncListInt(); + + // This can't be enabled by default as it will issue a warning from the weaver at compile time. This + // warning will appear in all projects including the package and can mess with CI or automation which checks for output + // in the editor log. + //[SyncVar] + //public SyncListInt NotInited; + + [SyncVar] + public GameObject syncObject; +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/WeaverILGenerationTests_Classes/WeaverILGenerationTests_TargetRPCServerClientChecks.cs b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/WeaverILGenerationTests_Classes/WeaverILGenerationTests_TargetRPCServerClientChecks.cs new file mode 100644 index 00000000..68a131c0 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/WeaverILGenerationTests_Classes/WeaverILGenerationTests_TargetRPCServerClientChecks.cs @@ -0,0 +1,19 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.Networking; + +#pragma warning disable 618 +public class WeaverILGenerationTests_TargetRPCServerClientChecks : NetworkBehaviour +{ + [TargetRpc] + public void TargetRpcTest(NetworkConnection connection) + { + } + + [ClientRpc] + public void RpcWithEnumArray(System.AttributeTargets[] array) + { + } +} +#pragma warning restore 618 diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/com.unity.multiplayer-hlapi.Tests.asmdef b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/com.unity.multiplayer-hlapi.Tests.asmdef new file mode 100644 index 00000000..dfb59bfc --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/Tests/Runtime/com.unity.multiplayer-hlapi.Tests.asmdef @@ -0,0 +1,11 @@ +{ + "name": "com.unity.multiplayer-hlapi.Tests", + "references": [ + "com.unity.multiplayer-hlapi.Runtime" + ], + "optionalUnityReferences": [ + "TestAssemblies" + ], + "includePlatforms": [], + "excludePlatforms": [] +} diff --git a/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/package.json b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/package.json new file mode 100644 index 00000000..cb08a104 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.multiplayer-hlapi@1.0.2/package.json @@ -0,0 +1,22 @@ +{ + "name": "com.unity.multiplayer-hlapi", + "displayName": "Multiplayer HLAPI", + "version": "1.0.2", + "unity": "2019.1", + "description": "The high level API component of the Unity Multiplayer system.", + "keywords": [ + "multiplayer", + "networking", + "hlapi", + "high-level", + "api" + ], + "dependencies": { + "nuget.mono-cecil": "0.1.5-preview" + }, + "repository": { + "type": "git", + "url": "https://gitlab.cds.internal.unity3d.com/upm-packages/multiplayer/com.unity.multiplayer-hlapi.git", + "revision": "a46e55980cbb98565c4634779a8f7b98cce67736" + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.purchasing@2.0.6/CHANGELOG.md b/KerbalVR/Library/PackageCache/com.unity.purchasing@2.0.6/CHANGELOG.md new file mode 100644 index 00000000..ea9106a8 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.purchasing@2.0.6/CHANGELOG.md @@ -0,0 +1,22 @@ +## [2.0.6] - 2019-02-18 +Remove embedded prebuilt assemblies. + +## [2.0.5] - 2019-02-08 +Fixed Unsupported platform error + +## [2.0.4] - 2019-01-20 +Added editor and playmode testing. + +## [2.0.3] - 2018-06-14 +Fixed issue related to 2.0.2 that caused new projects to not compile in the editor. +Engine dll is enabled for editor by default. +Removed meta data that disabled engine dll for windows store. + +## [2.0.2] - 2018-06-12 +Fixed issue where TypeLoadException occured while using "UnityEngine.Purchasing" because SimpleJson was not found. fogbugzId: 1035663. + +## [2.0.1] - 2018-02-14 +Fixed issue where importing the asset store package would fail due to importer settings. + +## [2.0.0] - 2018-02-07 +Fixed issue with IAP_PURCHASING flag not set on project load. diff --git a/KerbalVR/Library/PackageCache/com.unity.purchasing@2.0.6/Editor/UnityEditor.Purchasing.dll b/KerbalVR/Library/PackageCache/com.unity.purchasing@2.0.6/Editor/UnityEditor.Purchasing.dll new file mode 100644 index 00000000..de3e3b42 Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.purchasing@2.0.6/Editor/UnityEditor.Purchasing.dll differ diff --git a/KerbalVR/Library/PackageCache/com.unity.purchasing@2.0.6/License.md b/KerbalVR/Library/PackageCache/com.unity.purchasing@2.0.6/License.md new file mode 100644 index 00000000..27c17ac4 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.purchasing@2.0.6/License.md @@ -0,0 +1,32 @@ +**Unity Companion Package License v1.0 ("_License_")** + +Copyright © 2017 Unity Technologies ApS ("**_Unity_**") + +Unity hereby grants to you a worldwide, non-exclusive, no-charge, and royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, sublicense, and distribute the software that is made available with this License ("**_Software_**"), subject to the following terms and conditions: + +1. *Unity Companion Use Only*. Exercise of the license granted herein is limited to exercise for the creation, use, and/or distribution of applications, software, or other content pursuant to a valid Unity development engine software license ("**_Engine License_**"). That means while use of the Software is not limited to use in the software licensed under the Engine License, the Software may not be used for any purpose other than the creation, use, and/or distribution of Engine License-dependent applications, software, or other content. No other exercise of the license granted herein is permitted. + +1. *No Modification of Engine License*. Neither this License nor any exercise of the license granted herein modifies the Engine License in any way. + +1. *Ownership & Grant Back to You*. + + 3.1. You own your content. In this License, "derivative works" means derivatives of the Software itself--works derived only from the Software by you under this License (for example, modifying the code of the Software itself to improve its efficacy); “derivative works” of the Software do not include, for example, games, apps, or content that you create using the Software. You keep all right, title, and interest to your own content. + + 3.2. Unity owns its content. While you keep all right, title, and interest to your own content per the above, as between Unity and you, Unity will own all right, title, and interest to all intellectual property rights (including patent, trademark, and copyright) in the Software and derivative works of the Software, and you hereby assign and agree to assign all such rights in those derivative works to Unity. + + 3.3. You have a license to those derivative works. Subject to this License, Unity grants to you the same worldwide, non-exclusive, no-charge, and royalty-free copyright license to derivative works of the Software you create as is granted to you for the Software under this License. + +1. *Trademarks*. You are not granted any right or license under this License to use any trademarks, service marks, trade names, products names, or branding of Unity or its affiliates ("**_Trademarks_**"). Descriptive uses of Trademarks are permitted; see, for example, Unity’s Branding Usage Guidelines at [https://unity3d.com/public-relations/brand](https://unity3d.com/public-relations/brand). + +1. *Notices & Third-Party Rights*. This License, including the copyright notice above, must be provided in all substantial portions of the Software and derivative works thereof (or, if that is impracticable, in any other location where such notices are customarily placed). Further, if the Software is accompanied by a Unity "third-party notices" or similar file, you acknowledge and agree that software identified in that file is governed by those separate license terms. + +1. *DISCLAIMER, LIMITATION OF LIABILITY*. THE SOFTWARE AND ANY DERIVATIVE WORKS THEREOF IS PROVIDED ON AN "AS IS" BASIS, AND IS PROVIDED WITHOUT WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND/OR NONINFRINGEMENT. IN NO EVENT SHALL ANY COPYRIGHT HOLDER OR AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES (WHETHER DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL, INCLUDING PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, LOSS OF USE, DATA, OR PROFITS, AND BUSINESS INTERRUPTION), OR OTHER LIABILITY WHATSOEVER, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE, ARISING FROM OR OUT OF, OR IN CONNECTION WITH, THE SOFTWARE OR ANY DERIVATIVE WORKS THEREOF OR THE USE OF OR OTHER DEALINGS IN SAME, EVEN WHERE ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +1. *USE IS ACCEPTANCE and License Versions*. Your receipt and use of the Software constitutes your acceptance of this License and its terms and conditions. Software released by Unity under this License may be modified or updated and the License with it; upon any such modification or update, you will comply with the terms of the updated License for any use of any of the Software under the updated License. + +1. *Use in Compliance with Law and Termination*. Your exercise of the license granted herein will at all times be in compliance with applicable law and will not infringe any proprietary rights (including intellectual property rights); this License will terminate immediately on any breach by you of this License. + +1. *Severability*. If any provision of this License is held to be unenforceable or invalid, that provision will be enforced to the maximum extent possible and the other provisions will remain in full force and effect. + +1. *Governing Law and Venue*. This License is governed by and construed in accordance with the laws of Denmark, except for its conflict of laws rules; the United Nations Convention on Contracts for the International Sale of Goods will not apply. If you reside (or your principal place of business is) within the United States, you and Unity agree to submit to the personal and exclusive jurisdiction of and venue in the state and federal courts located in San Francisco County, California concerning any dispute arising out of this License ("**_Dispute_**"). If you reside (or your principal place of business is) outside the United States, you and Unity agree to submit to the personal and exclusive jurisdiction of and venue in the courts located in Copenhagen, Denmark concerning any Dispute. + diff --git a/KerbalVR/Library/PackageCache/com.unity.purchasing@2.0.6/README.md b/KerbalVR/Library/PackageCache/com.unity.purchasing@2.0.6/README.md new file mode 100644 index 00000000..bfc2ab8d --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.purchasing@2.0.6/README.md @@ -0,0 +1,9 @@ +# Unity In App Purchasing + +Implementation of the Unity In App Purchasing API. + +## Release Notes + +- Adding Readme file +- Adding local plugin importer callbacks. +- Removing Bintray references in package.json \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.purchasing@2.0.6/Tests/.tests.json b/KerbalVR/Library/PackageCache/com.unity.purchasing@2.0.6/Tests/.tests.json new file mode 100644 index 00000000..52ddbc79 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.purchasing@2.0.6/Tests/.tests.json @@ -0,0 +1,3 @@ +{ + "createSeparatePackage": false +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.purchasing@2.0.6/Tests/Editor/PurchasingEditorTest.cs b/KerbalVR/Library/PackageCache/com.unity.purchasing@2.0.6/Tests/Editor/PurchasingEditorTest.cs new file mode 100644 index 00000000..a4fdf48b --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.purchasing@2.0.6/Tests/Editor/PurchasingEditorTest.cs @@ -0,0 +1,16 @@ +using UnityEngine; +using UnityEditor; +using UnityEngine.TestTools; +using NUnit.Framework; +using System.Collections; + + + +public class PurchasingEditorTest { + + [Test] + public void PassingTest() + { + Assert.IsTrue(true); + } +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.purchasing@2.0.6/Tests/Editor/Unity.IAP.purchasing.EditorTests.asmdef b/KerbalVR/Library/PackageCache/com.unity.purchasing@2.0.6/Tests/Editor/Unity.IAP.purchasing.EditorTests.asmdef new file mode 100644 index 00000000..dca5f898 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.purchasing@2.0.6/Tests/Editor/Unity.IAP.purchasing.EditorTests.asmdef @@ -0,0 +1,11 @@ +{ + "name": "Unity.IAP.Purchasing.EditorTests", + "references": [], + "optionalUnityReferences": [ + "TestAssemblies" + ], + "includePlatforms": [ + "Editor" + ], + "excludePlatforms": [] +} diff --git a/KerbalVR/Library/PackageCache/com.unity.purchasing@2.0.6/Tests/Runtime/PurchasingRuntimeTest.cs b/KerbalVR/Library/PackageCache/com.unity.purchasing@2.0.6/Tests/Runtime/PurchasingRuntimeTest.cs new file mode 100644 index 00000000..752e2ae5 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.purchasing@2.0.6/Tests/Runtime/PurchasingRuntimeTest.cs @@ -0,0 +1,241 @@ +#if UNITY_PURCHASING +using System; +using System.IO; +using System.Linq; +using UnityEngine; +using UnityEditor; +using UnityEngine.Purchasing; +using UnityEditor.Purchasing; +using UnityEngine.Purchasing.Extension; +using UnityEngine.TestTools; +using NUnit.Framework; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; + +namespace Test +{ + public class PurchasingRuntimeTest + { + private IList products; + private int transactionID; + private TransactionLog transactionLog; + private List GetProductDescriptions(IEnumerable products) { + return (from product in products + let receipt = "fakeReceipt" + let tranID = (transactionID++).ToString() + let metadata = new ProductMetadata ("Fake", "Fake", "Fake", "GBP", 1.23m) + select new ProductDescription (product.storeSpecificId, metadata, receipt, tranID)).ToList(); + } + + private ProductMetadata metadata; + private bool _isPurchasingEnabled; + + [OneTimeSetUpAttribute] + public void BeforeAll() + { + _isPurchasingEnabled = PurchasingSettings.enabled; + if (!_isPurchasingEnabled) + { + Debug.Log("Temporarily Enabling Purchasing for tests"); + } + PurchasingSettings.enabled = true; + } + + [OneTimeSetUpAttribute] + public void AfterAll() + { + if (!_isPurchasingEnabled) + { + Debug.Log("Purchasing tests complete. Purchasing will now be disabled"); + } + PurchasingSettings.enabled = _isPurchasingEnabled; + } + + [SetUp] + public void Init() + { + metadata = new ProductMetadata("£1.23", "Fake title", "Fake desc", "GBP", 1.23m); + + products = new List (); + products.Add (new ProductDefinition ("ammo", "ammo.ios", ProductType.Consumable)); + products.Add (new ProductDefinition ("bomb", "bomb.ios", ProductType.Consumable)); + products.Add (new ProductDefinition ("sword", "sword.ios", ProductType.NonConsumable)); + products.Add (new ProductDefinition ("nanogenes", "nanogenes.ios", ProductType.Subscription)); + + } + + [Test] + public void TestProductMetaData() + { + Assert.AreEqual(metadata.localizedPriceString, "£1.23"); + Assert.AreEqual(metadata.localizedTitle, "Fake title"); + Assert.AreEqual(metadata.localizedDescription, "Fake desc"); + Assert.AreEqual(metadata.isoCurrencyCode, "GBP"); + Assert.AreEqual(metadata.localizedPrice, 1.23m); + } + + [Test] + public void TestProductDescription() + { + var prod1 = new ProductDescription("testID", metadata); + Assert.AreEqual(prod1.storeSpecificId, "testID"); + Assert.AreEqual(prod1.type, ProductType.Consumable); + Assert.AreEqual(prod1.metadata, metadata); + Assert.That(prod1.receipt, Is.Null); + Assert.That(prod1.transactionId, Is.Null); + } + + [Test] + public void TestProductConsumables() + { + Assert.IsNotEmpty(products); + Assert.AreEqual(products.Count, 4); + var product = products[0]; + Assert.AreEqual(product.id, "ammo"); + Assert.AreEqual(product.storeSpecificId, "ammo.ios"); + Assert.AreEqual(product.type, ProductType.Consumable); + } + + private static string GetTempFolder() { + var path = Path.Combine (Directory.GetCurrentDirectory (), "Test/tmp"); + if (Directory.Exists (path)) { + Directory.Delete (path, true); + } + Directory.CreateDirectory(path); + return path; + } + + class DummyProducts + { + + public static ProductDefinition Consumable = + new ProductDefinition ("coins", "com.brainDeadDesign.DepletedUraniumBullets", ProductType.Consumable, true, new List { new PayoutDefinition (PayoutType.Currency, "gold", 123), new PayoutDefinition (PayoutType.Resource, "health", 100) }); + + public static ProductDefinition NonConsumable = + new ProductDefinition("Rotary Cannon", "com.brainDeadDesign.GAU-12Equalizer", ProductType.NonConsumable, true, new PayoutDefinition(PayoutType.Item, "Cannon", 1, "anti-materiel cannon")); + + public static ProductDefinition Subscription = + new ProductDefinition("subscription", "com.brainDeadDesign.subscription", ProductType.Subscription); + + public static HashSet Products = new HashSet + { + Consumable, + NonConsumable, + Subscription + }; + + public static ReadOnlyCollection ProductCollection = + new ReadOnlyCollection (Products.ToList()); + + public static ProductMetadata DummyMetadata = + new ProductMetadata("£1.99", "Dummy product title", "Dummy product description", "GBP", 1.99m); + } + + class MockLogger : ILogger + { + + public bool IsLogTypeAllowed (LogType logType) + { + return true; + } + + public void Log (LogType logType, object message) + { + Console.WriteLine (message); + } + + public void Log (LogType logType, object message, UnityEngine.Object context) + { + Console.WriteLine (message); + } + + public void Log (LogType logType, string tag, object message) + { + Console.WriteLine (message); + } + + public void Log (LogType logType, string tag, object message, UnityEngine.Object context) + { + Console.WriteLine (message); + } + + public void Log (object message) + { + Console.WriteLine (message); + } + + public void Log (string tag, object message) + { + Console.WriteLine (message); + } + + public void Log (string tag, object message, UnityEngine.Object context) + { + Console.WriteLine (message); + } + + public void LogWarning (string tag, object message) + { + Console.WriteLine (message); + } + + public void LogWarning (string tag, object message, UnityEngine.Object context) + { + Console.WriteLine (message); + } + + public void LogError (string tag, object message) + { + Console.WriteLine (message); + } + + public void LogError (string tag, object message, UnityEngine.Object context) + { + Console.WriteLine (message); + } + + public void LogFormat (LogType logType, string format, params object[] args) + { + Console.WriteLine (format); + } + + public void LogException (Exception exception) + { + Console.WriteLine (exception); + } + + public ILogHandler logHandler { + get { + throw new NotImplementedException (); + } + set { + throw new NotImplementedException (); + } + } + + public bool logEnabled { get; set; } + + public LogType filterLogType { + get { + throw new NotImplementedException (); + } + set { + throw new NotImplementedException (); + } + } + + public void LogFormat (LogType logType, UnityEngine.Object context, string format, params object[] args) + { + Console.WriteLine (format); + } + + public void LogException (Exception exception, UnityEngine.Object context) + { + Console.WriteLine (exception); + } + } + } +} +#endif \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.purchasing@2.0.6/Tests/Runtime/Unity.IAP.purchasing.RunTimeTests.asmdef b/KerbalVR/Library/PackageCache/com.unity.purchasing@2.0.6/Tests/Runtime/Unity.IAP.purchasing.RunTimeTests.asmdef new file mode 100644 index 00000000..9ebabc4b --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.purchasing@2.0.6/Tests/Runtime/Unity.IAP.purchasing.RunTimeTests.asmdef @@ -0,0 +1,26 @@ +{ + "name": "Unity.IAP.Purchasing.RunTimeTests", + "references": [ + ], + "optionalUnityReferences": [ + "TestAssemblies" + ], + "includePlatforms": [], + "excludePlatforms": [ + "Android", + "iOS", + "LinuxStandalone64", + "macOSStandalone", + "Nintendo3DS", + "PS4", + "PSVita", + "Switch", + "tvOS", + "WSA", + "WebGL", + "WindowsStandalone32", + "WindowsStandalone64", + "XboxOne" + ], + "allowUnsafeCode": false +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.purchasing@2.0.6/UnityEngine.Purchasing.dll b/KerbalVR/Library/PackageCache/com.unity.purchasing@2.0.6/UnityEngine.Purchasing.dll new file mode 100644 index 00000000..b27be094 Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.purchasing@2.0.6/UnityEngine.Purchasing.dll differ diff --git a/KerbalVR/Library/PackageCache/com.unity.purchasing@2.0.6/package.json b/KerbalVR/Library/PackageCache/com.unity.purchasing@2.0.6/package.json new file mode 100644 index 00000000..d4b315c7 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.purchasing@2.0.6/package.json @@ -0,0 +1,18 @@ +{ + "name": "com.unity.purchasing", + "displayName": "In App Purchasing", + "version": "2.0.6", + "unity": "2018.1", + "description": "Unity IAP supports the iOS, Mac, tvOS, Google Play, Facebook Gameroom, Windows, Amazon, Samsung Galaxy, Tizen, Cloud Moolah MOO, Xiaomi Mi Game Pay App Stores.\n\nWith Unity IAP, setting up in-app purchases for your game across multiple app stores has never been easier.\n\nUse one common API to access all stores for free. With just a few lines of code, you can fully understand and optimize your in-game economy.\n\nUnity IAP automatically couples with Unity Analytics enabling you to monitor and act on trends in your revenue and purchase data across multiple platforms.\n\nIncludes client-side receipt validation for Apple, Google Play, and Xiaomi Mi Game Pay.", + "keywords": [ + "purchasing", + "iap", + "unity" + ], + "repository": { + "url": "https://gitlab.cds.internal.unity3d.com/upm-packages/purchasing/com.unity.purchasing", + "revision": "37674e38ef7548642e33bc97797a71b5eadbecac", + "type": "git" + }, + "license" : "Unity Companion Package License v1.0" +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/CHANGELOG.md b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/CHANGELOG.md new file mode 100644 index 00000000..cac5b9d9 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/CHANGELOG.md @@ -0,0 +1,31 @@ +# Changelog +## [1.0.13] - 2019-05-07 +- Fixed a regression where results from the player would no longer update correctly in the UI (case 1151147). + +## [1.0.12] - 2019-04-16 +- Added specific unity release to the package information. + +## [1.0.11] - 2019-04-10 +- Fixed a regression from 1.0.10 where test-started events were triggered multiple times after a domain reload. + +## [1.0.10] - 2019-04-08 +- Fixed an issue where test-started events would not be fired correctly after a test performing a domain reload (case 1141530). +- The UI should correctly run tests inside a nested class, when that class is selected. +- All actions should now correctly display a prefix when reporting test result. E.g. "TearDown :". +- Errors logged with Debug.LogError in TearDowns now append the error, rather than overwriting the existing result (case 1114306). +- Incorrect implementations of IWrapTestMethod and IWrapSetUpTearDown now gives a meaningful error. +- Fixed a regression where the Test Framework would run TearDown in a base class before the inheriting class (case 1142553). +- Fixed a regression introduced in 1.0.9 where tests with the Explicit attribute could no longer be executed. + +## [1.0.9] - 2019-03-27 +- Fixed an issue where a corrupt instance of the test runner window would block for a new being opened. +- Added the required modules to the list of package requirements. +- Fixed an issue where errors would happen if the test filter ui was clicked before the ui is done loading. +- Fix selecting items with duplicate names in test hierarchy of Test Runner window (case 987587). +- Fixed RecompileScripts instruction which we use in tests (case 1128994). +- Fixed an issue where using multiple filters on tests would sometimes give an incorrect result. + +## [1.0.7] - 2019-03-12 +### This is the first release of *Unity Package com.unity.test-framework*. + +- Migrated the test-framework from the current extension in unity. diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/CONTRIBUTING.md b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/CONTRIBUTING.md new file mode 100644 index 00000000..9f299b10 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/CONTRIBUTING.md @@ -0,0 +1,9 @@ +# Contributing + +## If you are interested in contributing, here are some ground rules: +* ... Define guidelines & rules for what contributors need to know to successfully make Pull requests against your repo ... + +## All contributions are subject to the [Unity Contribution Agreement(UCA)](https://unity3d.com/legal/licenses/Unity_Contribution_Agreement) +By making a pull request, you are confirming agreement to the terms and conditions of the UCA, including that your Contributions are your original creation and that you have complete right and authority to make your Contributions. + +## Once you have a change ready following these ground rules. Simply make a pull request diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/LICENSE.md b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/LICENSE.md new file mode 100644 index 00000000..f2dc729c --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/LICENSE.md @@ -0,0 +1,5 @@ +Test Framework copyright © 2019 Unity Technologies ApS + +Licensed under the Unity Companion License for Unity-dependent projects--see [Unity Companion License](http://www.unity3d.com/legal/licenses/Unity_Companion_License). + +Unless expressly provided otherwise, the Software under this license is made available strictly on an “AS IS” BASIS WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED. Please review the license for details on these and other terms and conditions. diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/CallbacksDelegator.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/CallbacksDelegator.cs new file mode 100644 index 00000000..ca73e2dd --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/CallbacksDelegator.cs @@ -0,0 +1,116 @@ +using System; +using System.Linq; +using System.Text; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; +using UnityEngine; +using UnityEngine.TestRunner.TestLaunchers; + +namespace UnityEditor.TestTools.TestRunner.Api +{ + internal class CallbacksDelegator + { + private static CallbacksDelegator s_instance; + public static CallbacksDelegator instance + { + get + { + if (s_instance == null) + { + s_instance = new CallbacksDelegator(CallbacksHolder.instance.GetAll, new TestAdaptorFactory()); + } + return s_instance; + } + } + + private readonly Func m_CallbacksProvider; + private readonly ITestAdaptorFactory m_AdaptorFactory; + + public CallbacksDelegator(Func callbacksProvider, ITestAdaptorFactory adaptorFactory) + { + m_CallbacksProvider = callbacksProvider; + m_AdaptorFactory = adaptorFactory; + } + + public void RunStarted(ITest testsToRun) + { + var testRunnerTestsToRun = m_AdaptorFactory.Create(testsToRun); + TryInvokeAllCallbacks(callbacks => callbacks.RunStarted(testRunnerTestsToRun)); + } + + public void RunStartedRemotely(byte[] testsToRunData) + { + var testData = Deserialize(testsToRunData); + var testsToRun = m_AdaptorFactory.BuildTree(testData); + TryInvokeAllCallbacks(callbacks => callbacks.RunStarted(testsToRun)); + } + + public void RunFinished(ITestResult testResults) + { + var testResult = m_AdaptorFactory.Create(testResults); + TryInvokeAllCallbacks(callbacks => callbacks.RunFinished(testResult)); + } + + public void RunFinishedRemotely(byte[] testResultsData) + { + var remoteTestResult = Deserialize(testResultsData); + var testResult = m_AdaptorFactory.Create(remoteTestResult.results.First(), remoteTestResult); + TryInvokeAllCallbacks(callbacks => callbacks.RunFinished(testResult)); + } + + public void RunFailed(string failureMessage) + { + var nunitTestResult = new TestSuiteResult(new TestSuite("test")); + nunitTestResult.SetResult(ResultState.Error, failureMessage); + var testResult = m_AdaptorFactory.Create(nunitTestResult); + TryInvokeAllCallbacks(callbacks => callbacks.RunFinished(testResult)); + } + + public void TestStarted(ITest test) + { + var testRunnerTest = m_AdaptorFactory.Create(test); + TryInvokeAllCallbacks(callbacks => callbacks.TestStarted(testRunnerTest)); + } + + public void TestStartedRemotely(byte[] testStartedData) + { + var testData = Deserialize(testStartedData); + var testsToRun = m_AdaptorFactory.BuildTree(testData); + + TryInvokeAllCallbacks(callbacks => callbacks.TestStarted(testsToRun)); + } + + public void TestFinished(ITestResult result) + { + var testResult = m_AdaptorFactory.Create(result); + TryInvokeAllCallbacks(callbacks => callbacks.TestFinished(testResult)); + } + + public void TestFinishedRemotely(byte[] testResultsData) + { + var remoteTestResult = Deserialize(testResultsData); + var testResult = m_AdaptorFactory.Create(remoteTestResult.results.First(), remoteTestResult); + TryInvokeAllCallbacks(callbacks => callbacks.TestFinished(testResult)); + } + + private void TryInvokeAllCallbacks(Action callbackAction) + { + foreach (var testRunnerApiCallback in m_CallbacksProvider()) + { + try + { + callbackAction(testRunnerApiCallback); + } + catch (Exception ex) + { + Debug.LogException(ex); + } + } + } + + private static T Deserialize(byte[] data) + { + return JsonUtility.FromJson(Encoding.UTF8.GetString(data)); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/CallbacksDelegatorListener.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/CallbacksDelegatorListener.cs new file mode 100644 index 00000000..c19621d5 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/CallbacksDelegatorListener.cs @@ -0,0 +1,28 @@ +using UnityEngine; +using UnityEngine.TestTools.TestRunner; + +namespace UnityEditor.TestTools.TestRunner.Api +{ + internal class CallbacksDelegatorListener : ScriptableObject, ITestRunnerListener + { + public void RunStarted(NUnit.Framework.Interfaces.ITest testsToRun) + { + CallbacksDelegator.instance.RunStarted(testsToRun); + } + + public void RunFinished(NUnit.Framework.Interfaces.ITestResult testResults) + { + CallbacksDelegator.instance.RunFinished(testResults); + } + + public void TestStarted(NUnit.Framework.Interfaces.ITest test) + { + CallbacksDelegator.instance.TestStarted(test); + } + + public void TestFinished(NUnit.Framework.Interfaces.ITestResult result) + { + CallbacksDelegator.instance.TestFinished(result); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/CallbacksHolder.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/CallbacksHolder.cs new file mode 100644 index 00000000..07b8ecfe --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/CallbacksHolder.cs @@ -0,0 +1,40 @@ +using System.Collections.Generic; +using System.Linq; + +namespace UnityEditor.TestTools.TestRunner.Api +{ + internal class CallbacksHolder : ScriptableSingleton + { + private List m_Callbacks = new List(); + public void Add(ICallbacks callback, int priority) + { + m_Callbacks.Add(new CallbackWithPriority(callback, priority)); + } + + public void Remove(ICallbacks callback) + { + m_Callbacks.RemoveAll(callbackWithPriority => callbackWithPriority.Callback == callback); + } + + public ICallbacks[] GetAll() + { + return m_Callbacks.OrderByDescending(callback => callback.Priority).Select(callback => callback.Callback).ToArray(); + } + + public void Clear() + { + m_Callbacks.Clear(); + } + + private struct CallbackWithPriority + { + public ICallbacks Callback; + public int Priority; + public CallbackWithPriority(ICallbacks callback, int priority) + { + Callback = callback; + Priority = priority; + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/ExecutionSettings.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/ExecutionSettings.cs new file mode 100644 index 00000000..76a6bc8c --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/ExecutionSettings.cs @@ -0,0 +1,9 @@ +namespace UnityEditor.TestTools.TestRunner.Api +{ + internal class ExecutionSettings + { + public BuildTarget? targetPlatform; + public ITestRunSettings overloadTestRunSettings; + public Filter filter; + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/Filter.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/Filter.cs new file mode 100644 index 00000000..96b46578 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/Filter.cs @@ -0,0 +1,34 @@ +using System; +using UnityEngine; +using UnityEngine.TestTools.TestRunner.GUI; + +namespace UnityEditor.TestTools.TestRunner.Api +{ + [Serializable] + internal class Filter + { + [SerializeField] + public TestMode testMode; + [SerializeField] + public string[] testNames; + [SerializeField] + public string[] groupNames; + [SerializeField] + public string[] categoryNames; + [SerializeField] + public string[] assemblyNames; + + public static Filter empty = new Filter(); + + internal TestRunnerFilter ToTestRunnerFilter() + { + return new TestRunnerFilter() + { + testNames = testNames, + categoryNames = categoryNames, + groupNames = groupNames, + assemblyNames = assemblyNames + }; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/ICallbacks.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/ICallbacks.cs new file mode 100644 index 00000000..c6b3e472 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/ICallbacks.cs @@ -0,0 +1,10 @@ +namespace UnityEditor.TestTools.TestRunner.Api +{ + internal interface ICallbacks + { + void RunStarted(ITestAdaptor testsToRun); + void RunFinished(ITestResultAdaptor result); + void TestStarted(ITestAdaptor test); + void TestFinished(ITestResultAdaptor result); + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/ITestAdaptor.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/ITestAdaptor.cs new file mode 100644 index 00000000..5474a89e --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/ITestAdaptor.cs @@ -0,0 +1,27 @@ +using System.Collections.Generic; +using NUnit.Framework.Interfaces; + +namespace UnityEditor.TestTools.TestRunner.Api +{ + internal interface ITestAdaptor + { + string Id { get; } + string Name { get; } + string FullName { get; } + int TestCaseCount { get; } + bool HasChildren { get; } + bool IsSuite { get; } + IEnumerable Children { get; } + int TestCaseTimeout { get; } + ITypeInfo TypeInfo { get; } + IMethodInfo Method { get; } + string[] Categories { get; } + bool IsTestAssembly { get; } + RunState RunState { get; } + string Description { get; } + string SkipReason { get; } + string ParentId { get; } + string UniqueName { get; } + string ParentUniqueName { get; } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/ITestAdaptorFactory.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/ITestAdaptorFactory.cs new file mode 100644 index 00000000..bf599029 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/ITestAdaptorFactory.cs @@ -0,0 +1,16 @@ +using System.Collections.Generic; +using NUnit.Framework.Interfaces; +using UnityEngine.TestRunner.TestLaunchers; + +namespace UnityEditor.TestTools.TestRunner.Api +{ + internal interface ITestAdaptorFactory + { + ITestAdaptor Create(ITest test); + ITestAdaptor Create(RemoteTestData testData); + ITestResultAdaptor Create(ITestResult testResult); + ITestResultAdaptor Create(RemoteTestResultData testResult, RemoteTestResultDataWithTestData allData); + ITestAdaptor BuildTree(RemoteTestResultDataWithTestData data); + IEnumerator BuildTreeAsync(RemoteTestResultDataWithTestData data); + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/ITestResultAdaptor.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/ITestResultAdaptor.cs new file mode 100644 index 00000000..703b5d6d --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/ITestResultAdaptor.cs @@ -0,0 +1,86 @@ +using System; +using System.Collections.Generic; +using NUnit.Framework.Interfaces; + +namespace UnityEditor.TestTools.TestRunner.Api +{ + internal interface ITestResultAdaptor + { + ITestAdaptor Test { get; } + string Name { get; } + + /// Gets the full name of the test result + string FullName { get; } + + string ResultState { get; } + + TestStatus TestStatus { get; } + + /// Gets the elapsed time for running the test in seconds + double Duration { get; } + + /// Gets or sets the time the test started running. + DateTime StartTime { get; } + + /// Gets or sets the time the test finished running. + DateTime EndTime { get; } + + /// + /// Gets the message associated with a test + /// failure or with not running the test + /// + string Message { get; } + + /// + /// Gets any stacktrace associated with an + /// error or failure. Not available in + /// the Compact Framework 1.0. + /// + string StackTrace { get; } + + /// + /// Gets the number of asserts executed + /// when running the test and all its children. + /// + int AssertCount { get; } + + /// + /// Gets the number of test cases that failed + /// when running the test and all its children. + /// + int FailCount { get; } + + /// + /// Gets the number of test cases that passed + /// when running the test and all its children. + /// + int PassCount { get; } + + /// + /// Gets the number of test cases that were skipped + /// when running the test and all its children. + /// + int SkipCount { get; } + + /// + /// Gets the number of test cases that were inconclusive + /// when running the test and all its children. + /// + int InconclusiveCount { get; } + + /// + /// Indicates whether this result has any child results. + /// Accessing HasChildren should not force creation of the + /// Children collection in classes implementing this interface. + /// + bool HasChildren { get; } + + /// Gets the the collection of child results. + IEnumerable Children { get; } + + /// Gets any text output written to this result. + string Output { get; } + + TNode ToXml(); + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/ITestRunSettings.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/ITestRunSettings.cs new file mode 100644 index 00000000..aa4515c6 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/ITestRunSettings.cs @@ -0,0 +1,9 @@ +using System; + +namespace UnityEditor.TestTools.TestRunner.Api +{ + internal interface ITestRunSettings : IDisposable + { + void Apply(); + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/ITestRunnerApi.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/ITestRunnerApi.cs new file mode 100644 index 00000000..f2dff859 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/ITestRunnerApi.cs @@ -0,0 +1,12 @@ +using System; + +namespace UnityEditor.TestTools.TestRunner.Api +{ + interface ITestRunnerApi + { + void Execute(ExecutionSettings executionSettings); + void RegisterCallbacks(T testCallbacks, int priority = 0) where T : ICallbacks; + void UnregisterCallbacks(T testCallbacks) where T : ICallbacks; + void RetrieveTestList(ExecutionSettings executionSettings, Action callback); + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/RunState.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/RunState.cs new file mode 100644 index 00000000..eb2c8ab8 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/RunState.cs @@ -0,0 +1,11 @@ +namespace UnityEditor.TestTools.TestRunner.Api +{ + internal enum RunState + { + NotRunnable, + Runnable, + Explicit, + Skipped, + Ignored, + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/TestAdaptor.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/TestAdaptor.cs new file mode 100644 index 00000000..0b6dc645 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/TestAdaptor.cs @@ -0,0 +1,123 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; +using UnityEngine.TestRunner.NUnitExtensions; +using UnityEngine.TestRunner.NUnitExtensions.Runner; +using UnityEngine.TestRunner.TestLaunchers; +using UnityEngine.TestTools.Utils; + +namespace UnityEditor.TestTools.TestRunner.Api +{ + internal class TestAdaptor : ITestAdaptor + { + internal TestAdaptor(ITest test) : this(test, new ITest[0]) + { + } + + internal TestAdaptor(ITest test, ITest[] additionalChildren) + { + Id = test.Id; + Name = test.Name; + var childIndex = -1; + if (test.Properties["childIndex"].Count > 0) + { + childIndex = (int)test.Properties["childIndex"][0]; + } + FullName = childIndex != -1 ? GetIndexedTestCaseName(test.FullName, childIndex) : test.FullName; + TestCaseCount = test.TestCaseCount; + HasChildren = test.HasChildren; + IsSuite = test.IsSuite; + Children = new[] {test.Tests, additionalChildren}.SelectMany(t => t).Select(t => new TestAdaptor(t)).ToArray(); + if (UnityTestExecutionContext.CurrentContext != null) + { + TestCaseTimeout = UnityTestExecutionContext.CurrentContext.TestCaseTimeout; + } + else + { + TestCaseTimeout = CoroutineRunner.k_DefaultTimeout; + } + + TypeInfo = test.TypeInfo; + Method = test.Method; + FullPath = GetFullPath(test); + Categories = test.GetAllCategoriesFromTest().Distinct().ToArray(); + IsTestAssembly = test is TestAssembly; + RunState = (RunState)Enum.Parse(typeof(RunState), test.RunState.ToString()); + Description = (string)test.Properties.Get(PropertyNames.Description); + SkipReason = test.GetSkipReason(); + ParentId = test.GetParentId(); + UniqueName = test.GetUniqueName(); + ParentUniqueName = test.GetParentUniqueName(); + } + + internal TestAdaptor(RemoteTestData test) + { + Id = test.id; + Name = test.name; + FullName = test.ChildIndex != -1 ? GetIndexedTestCaseName(test.fullName, test.ChildIndex) : test.fullName; + TestCaseCount = test.testCaseCount; + HasChildren = test.hasChildren; + IsSuite = test.isSuite; + m_ChildrenIds = test.childrenIds; + TestCaseTimeout = test.testCaseTimeout; + Categories = test.Categories; + IsTestAssembly = test.IsTestAssembly; + RunState = (RunState)Enum.Parse(typeof(RunState), test.RunState.ToString()); + Description = test.Description; + SkipReason = test.SkipReason; + ParentId = test.ParentId; + UniqueName = test.UniqueName; + ParentUniqueName = test.ParentUniqueName; + } + + internal void ApplyChildren(IEnumerable allTests) + { + Children = m_ChildrenIds.Select(id => allTests.First(t => t.Id == id)).ToArray(); + } + + public string Id { get; private set; } + public string Name { get; private set; } + public string FullName { get; private set; } + public int TestCaseCount { get; private set; } + public bool HasChildren { get; private set; } + public bool IsSuite { get; private set; } + public IEnumerable Children { get; private set; } + public int TestCaseTimeout { get; private set; } + public ITypeInfo TypeInfo { get; private set; } + public IMethodInfo Method { get; private set; } + public string FullPath { get; private set; } + private string[] m_ChildrenIds; + public string[] Categories { get; private set; } + public bool IsTestAssembly { get; private set; } + public RunState RunState { get; } + public string Description { get; } + public string SkipReason { get; } + public string ParentId { get; } + public string UniqueName { get; } + public string ParentUniqueName { get; } + + private static string GetFullPath(ITest test) + { + if (test.Parent != null && test.Parent.Parent != null) + return GetFullPath(test.Parent) + "/" + test.Name; + return test.Name; + } + + private static string GetIndexedTestCaseName(string fullName, int index) + { + var generatedTestSuffix = " GeneratedTestCase" + index; + if (fullName.EndsWith(")")) + { + // Test names from generated TestCaseSource look like Test(TestCaseSourceType) + // This inserts a unique test case index in the name, so that it becomes Test(TestCaseSourceType GeneratedTestCase0) + return fullName.Substring(0, fullName.Length - 1) + generatedTestSuffix + fullName[fullName.Length - 1]; + } + + // In some cases there can be tests with duplicate names generated in other ways and they won't have () in their name + // We just append a suffix at the end of the name in that case + return fullName + generatedTestSuffix; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/TestAdaptorFactory.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/TestAdaptorFactory.cs new file mode 100644 index 00000000..5fb8ab66 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/TestAdaptorFactory.cs @@ -0,0 +1,59 @@ +using System.Collections.Generic; +using System.Linq; +using NUnit.Framework.Interfaces; +using UnityEngine.TestRunner.TestLaunchers; + +namespace UnityEditor.TestTools.TestRunner.Api +{ + internal class TestAdaptorFactory : ITestAdaptorFactory + { + public ITestAdaptor Create(ITest test) + { + return new TestAdaptor(test); + } + + public ITestAdaptor Create(RemoteTestData testData) + { + return new TestAdaptor(testData); + } + + public ITestResultAdaptor Create(ITestResult testResult) + { + return new TestResultAdaptor(testResult); + } + + public ITestResultAdaptor Create(RemoteTestResultData testResult, RemoteTestResultDataWithTestData allData) + { + return new TestResultAdaptor(testResult, allData); + } + + public ITestAdaptor BuildTree(RemoteTestResultDataWithTestData data) + { + var tests = data.tests.Select(remoteTestData => new TestAdaptor(remoteTestData)).ToList(); + + foreach (var test in tests) + { + test.ApplyChildren(tests); + } + + return tests.First(); + } + + public IEnumerator BuildTreeAsync(RemoteTestResultDataWithTestData data) + { + var tests = data.tests.Select(remoteTestData => new TestAdaptor(remoteTestData)).ToList(); + + for (var index = 0; index < tests.Count; index++) + { + var test = tests[index]; + test.ApplyChildren(tests); + if (index % 100 == 0) + { + yield return null; + } + } + + yield return tests.First(); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/TestLauncherFactory.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/TestLauncherFactory.cs new file mode 100644 index 00000000..d63110b8 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/TestLauncherFactory.cs @@ -0,0 +1,57 @@ +using System; +using UnityEngine.TestTools; +using UnityEngine.TestTools.TestRunner; + +namespace UnityEditor.TestTools.TestRunner.Api +{ + internal class TestLauncherFactory + { + internal TestLauncherBase GetLauncher(ExecutionSettings executionSettings) + { + if (executionSettings.filter.testMode == TestMode.EditMode) + { + return GetEditModeLauncher(executionSettings.filter); + } + else + { + var settings = PlaymodeTestsControllerSettings.CreateRunnerSettings(executionSettings.filter.ToTestRunnerFilter()); + return GetPlayModeLauncher(settings, executionSettings); + } + } + + static TestLauncherBase GetEditModeLauncher(Filter filter) + { + return GetEditModeLauncherForProvidedAssemblies(filter); + } + + static TestLauncherBase GetPlayModeLauncher(PlaymodeTestsControllerSettings settings, ExecutionSettings executionSettings) + { + if (executionSettings.targetPlatform != null) + { + return GetPlayerLauncher(settings, executionSettings.targetPlatform.Value, executionSettings.overloadTestRunSettings); + } + + if (PlayerSettings.runPlayModeTestAsEditModeTest) + { + return GetEditModeLauncherForProvidedAssemblies(executionSettings.filter, TestPlatform.PlayMode); + } + + return GetPlayModeLauncher(settings); + } + + static TestLauncherBase GetEditModeLauncherForProvidedAssemblies(Filter filter, TestPlatform testPlatform = TestPlatform.EditMode) + { + return new EditModeLauncher(filter.ToTestRunnerFilter(), testPlatform); + } + + static TestLauncherBase GetPlayModeLauncher(PlaymodeTestsControllerSettings settings) + { + return new PlaymodeLauncher(settings); + } + + static TestLauncherBase GetPlayerLauncher(PlaymodeTestsControllerSettings settings, BuildTarget targetPlatform, ITestRunSettings overloadTestRunSettings) + { + return new PlayerLauncher(settings, targetPlatform, overloadTestRunSettings); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/TestMode.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/TestMode.cs new file mode 100644 index 00000000..c330457a --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/TestMode.cs @@ -0,0 +1,11 @@ +using System; + +namespace UnityEditor.TestTools.TestRunner.Api +{ + [Flags] + internal enum TestMode + { + EditMode = 1 << 0, + PlayMode = 1 << 1 + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/TestResultAdaptor.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/TestResultAdaptor.cs new file mode 100644 index 00000000..06e70f12 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/TestResultAdaptor.cs @@ -0,0 +1,87 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using NUnit.Framework.Interfaces; +using UnityEngine.TestRunner.TestLaunchers; + +namespace UnityEditor.TestTools.TestRunner.Api +{ + internal class TestResultAdaptor : ITestResultAdaptor + { + private TNode m_Node; + + internal TestResultAdaptor(ITestResult result) + { + Test = new TestAdaptor(result.Test); + Name = result.Name; + FullName = result.FullName; + ResultState = result.ResultState.ToString(); + TestStatus = ParseTestStatus(result.ResultState.Status); + Duration = result.Duration; + StartTime = result.StartTime; + EndTime = result.EndTime; + Message = result.Message; + StackTrace = result.StackTrace; + AssertCount = result.AssertCount; + FailCount = result.FailCount; + PassCount = result.PassCount; + SkipCount = result.SkipCount; + InconclusiveCount = result.InconclusiveCount; + HasChildren = result.HasChildren; + Output = result.Output; + Children = result.Children.Select(child => new TestResultAdaptor(child)).ToArray(); + m_Node = result.ToXml(true); + } + + internal TestResultAdaptor(RemoteTestResultData result, RemoteTestResultDataWithTestData allData) + { + Test = new TestAdaptor(allData.tests.First(t => t.id == result.testId)); + Name = result.name; + FullName = result.fullName; + ResultState = result.resultState; + TestStatus = ParseTestStatus(result.testStatus); + Duration = result.duration; + StartTime = result.startTime; + EndTime = result.endTime; + Message = result.message; + StackTrace = result.stackTrace; + AssertCount = result.assertCount; + FailCount = result.failCount; + PassCount = result.passCount; + SkipCount = result.skipCount; + InconclusiveCount = result.inconclusiveCount; + HasChildren = result.hasChildren; + Output = result.output; + Children = result.childrenIds.Select(childId => new TestResultAdaptor(allData.results.First(r => r.testId == childId), allData)).ToArray(); + m_Node = TNode.FromXml(result.xml); + } + + public ITestAdaptor Test { get; private set; } + public string Name { get; private set; } + public string FullName { get; private set; } + public string ResultState { get; private set; } + public TestStatus TestStatus { get; private set; } + public double Duration { get; private set; } + public DateTime StartTime { get; private set; } + public DateTime EndTime { get; private set; } + public string Message { get; private set; } + public string StackTrace { get; private set; } + public int AssertCount { get; private set; } + public int FailCount { get; private set; } + public int PassCount { get; private set; } + public int SkipCount { get; private set; } + public int InconclusiveCount { get; private set; } + public bool HasChildren { get; private set; } + public IEnumerable Children { get; private set; } + public string Output { get; private set; } + public TNode ToXml() + { + return m_Node; + } + + private static TestStatus ParseTestStatus(NUnit.Framework.Interfaces.TestStatus testStatus) + { + return (TestStatus)Enum.Parse(typeof(TestStatus), testStatus.ToString()); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/TestRunData.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/TestRunData.cs new file mode 100644 index 00000000..decdf289 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/TestRunData.cs @@ -0,0 +1,12 @@ +using System; +using UnityEngine; + +namespace UnityEditor.TestTools.TestRunner.Api +{ + [Serializable] + internal class TestRunData : ScriptableSingleton + { + [SerializeField] + public ExecutionSettings executionSettings; + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/TestRunnerApi.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/TestRunnerApi.cs new file mode 100644 index 00000000..655f97d3 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/TestRunnerApi.cs @@ -0,0 +1,81 @@ +using System; +using System.Linq; +using System.Threading; +using UnityEngine; +using UnityEngine.TestRunner.TestLaunchers; +using UnityEngine.TestTools; +using UnityEngine.TestTools.NUnitExtensions; + +namespace UnityEditor.TestTools.TestRunner.Api +{ + internal class TestRunnerApi : ScriptableObject, ITestRunnerApi + { + public void Execute(ExecutionSettings executionSettings) + { + if (executionSettings == null) + { + throw new ArgumentException("Filter for execution is undefined."); + } + + var launcherFactory = new TestLauncherFactory(); + var data = TestRunData.instance; + data.executionSettings = executionSettings; + + var testLauncher = launcherFactory.GetLauncher(executionSettings); + testLauncher.Run(); + } + + public void RegisterCallbacks(T testCallbacks, int priority = 0) where T : ICallbacks + { + if (testCallbacks == null) + { + throw new ArgumentException("TestCallbacks for execution is undefined."); + } + + CallbacksHolder.instance.Add(testCallbacks, priority); + } + + public void UnregisterCallbacks(T testCallbacks) where T : ICallbacks + { + if (testCallbacks == null) + { + throw new ArgumentException("TestCallbacks for execution is undefined."); + } + + CallbacksHolder.instance.Remove(testCallbacks); + } + + public void RetrieveTestList(ExecutionSettings executionSettings, Action callback) + { + if (executionSettings == null) + { + throw new ArgumentException("Filter for execution is undefined."); + } + + if (callback == null) + { + throw new ArgumentException("Callback is undefined."); + } + + var platform = ParseTestMode(executionSettings.filter.testMode); + var testAssemblyProvider = new EditorLoadedTestAssemblyProvider(new EditorCompilationInterfaceProxy(), new EditorAssembliesProxy()); + var testAdaptorFactory = new TestAdaptorFactory(); + var testListCache = new TestListCache(testAdaptorFactory, new RemoteTestResultDataFactory(), TestListCacheData.instance); + var testListProvider = new TestListProvider(testAssemblyProvider, new UnityTestAssemblyBuilder()); + var cachedTestListProvider = new CachingTestListProvider(testListProvider, testListCache, testAdaptorFactory); + + var job = new TestListJob(cachedTestListProvider, platform, callback); + job.Start(); + } + + private static TestPlatform ParseTestMode(TestMode testmode) + { + if (testmode == TestMode.EditMode) + { + return TestPlatform.EditMode; + } + + return TestPlatform.PlayMode; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/TestStatus.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/TestStatus.cs new file mode 100644 index 00000000..c72973e8 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/Api/TestStatus.cs @@ -0,0 +1,10 @@ +namespace UnityEditor.TestTools.TestRunner.Api +{ + internal enum TestStatus + { + Skipped, + Passed, + Failed, + Inconclusive + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/AssemblyInfo.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/AssemblyInfo.cs new file mode 100644 index 00000000..1c4e19ba --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/AssemblyInfo.cs @@ -0,0 +1,14 @@ +using System.Reflection; +using System.Runtime.CompilerServices; + +[assembly: AssemblyTitle("UnityEditor.TestRunner")] +[assembly: InternalsVisibleTo("Assembly-CSharp-Editor-testable")] +[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] +[assembly: InternalsVisibleTo("Unity.PerformanceTesting.Editor")] +[assembly: InternalsVisibleTo("Unity.IntegrationTests")] +[assembly: InternalsVisibleTo("UnityEditor.TestRunner.Tests")] +[assembly: InternalsVisibleTo("Unity.TestTools.CodeCoverage.Editor")] +[assembly: InternalsVisibleTo("Unity.PackageManagerUI.Develop.Editor")] +[assembly: InternalsVisibleTo("Unity.PackageManagerUI.Develop.EditorTests")] + +[assembly: AssemblyVersion("1.0.0")] diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineParser/CommandLineOption.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineParser/CommandLineOption.cs new file mode 100644 index 00000000..1a2d98a4 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineParser/CommandLineOption.cs @@ -0,0 +1,45 @@ +using System; +using System.Linq; + +namespace UnityEditor.TestRunner.CommandLineParser +{ + internal class CommandLineOption : ICommandLineOption + { + Action m_ArgAction; + + public CommandLineOption(string argName, Action action) + { + ArgName = argName; + m_ArgAction = s => action(); + } + + public CommandLineOption(string argName, Action action) + { + ArgName = argName; + m_ArgAction = action; + } + + public CommandLineOption(string argName, Action action) + { + ArgName = argName; + m_ArgAction = s => action(SplitStringToArray(s)); + } + + public string ArgName { get; private set; } + + public void ApplyValue(string value) + { + m_ArgAction(value); + } + + static string[] SplitStringToArray(string value) + { + if (string.IsNullOrEmpty(value)) + { + return null; + } + + return value.Split(';').ToArray(); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineParser/CommandLineOptionSet.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineParser/CommandLineOptionSet.cs new file mode 100644 index 00000000..d08c233d --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineParser/CommandLineOptionSet.cs @@ -0,0 +1,49 @@ +using System; + +namespace UnityEditor.TestRunner.CommandLineParser +{ + internal class CommandLineOptionSet + { + ICommandLineOption[] m_Options; + + public CommandLineOptionSet(params ICommandLineOption[] options) + { + m_Options = options; + } + + public void Parse(string[] args) + { + var i = 0; + while (i < args.Length) + { + var arg = args[i]; + if (!arg.StartsWith("-")) + { + i++; + continue; + } + + string value = null; + if (i + 1 < args.Length && !args[i + 1].StartsWith("-")) + { + value = args[i + 1]; + i++; + } + + ApplyValueToMatchingOptions(arg, value); + i++; + } + } + + private void ApplyValueToMatchingOptions(string argName, string value) + { + foreach (var option in m_Options) + { + if ("-" + option.ArgName == argName) + { + option.ApplyValue(value); + } + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineParser/ICommandLineOption.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineParser/ICommandLineOption.cs new file mode 100644 index 00000000..7f699adc --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineParser/ICommandLineOption.cs @@ -0,0 +1,8 @@ +namespace UnityEditor.TestRunner.CommandLineParser +{ + interface ICommandLineOption + { + string ArgName { get; } + void ApplyValue(string value); + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineTest/Executer.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineTest/Executer.cs new file mode 100644 index 00000000..c0ad491c --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineTest/Executer.cs @@ -0,0 +1,137 @@ +using System; +using System.Linq; +using UnityEditor.TestRunner.TestLaunchers; +using UnityEditor.TestTools.TestRunner.Api; +using UnityEngine; + +namespace UnityEditor.TestTools.TestRunner.CommandLineTest +{ + internal class Executer + { + private ITestRunnerApi m_TestRunnerApi; + private ISettingsBuilder m_SettingsBuilder; + private Action m_LogErrorFormat; + private Action m_LogException; + private Action m_ExitEditorApplication; + private Func m_ScriptCompilationFailedCheck; + + public Executer(ITestRunnerApi testRunnerApi, ISettingsBuilder settingsBuilder, Action logErrorFormat, Action logException, Action exitEditorApplication, Func scriptCompilationFailedCheck) + { + m_TestRunnerApi = testRunnerApi; + m_SettingsBuilder = settingsBuilder; + m_LogErrorFormat = logErrorFormat; + m_LogException = logException; + m_ExitEditorApplication = exitEditorApplication; + m_ScriptCompilationFailedCheck = scriptCompilationFailedCheck; + } + + internal void InitializeAndExecuteRun(string[] commandLineArgs) + { + Api.ExecutionSettings executionSettings; + try + { + executionSettings = m_SettingsBuilder.BuildApiExecutionSettings(commandLineArgs); + if (executionSettings.targetPlatform.HasValue) + RemotePlayerLogController.instance.SetBuildTarget(executionSettings.targetPlatform.Value); + } + catch (SetupException exception) + { + HandleSetupException(exception); + return; + } + + try + { + Debug.Log("Executing tests with settings: " + ExecutionSettingsToString(executionSettings)); + m_TestRunnerApi.Execute(executionSettings); + } + catch (Exception exception) + { + m_LogException(exception); + m_ExitEditorApplication((int)ReturnCodes.RunError); + } + } + + internal ExecutionSettings BuildExecutionSettings(string[] commandLineArgs) + { + return m_SettingsBuilder.BuildExecutionSettings(commandLineArgs); + } + + internal enum ReturnCodes + { + Ok = 0, + Failed = 2, + RunError = 3, + PlatformNotFoundReturnCode = 4 + } + + internal void SetUpCallbacks(ExecutionSettings executionSettings) + { + RemotePlayerLogController.instance.SetLogsDirectory(executionSettings.DeviceLogsDirectory); + + var resultSavingCallback = ScriptableObject.CreateInstance(); + resultSavingCallback.m_ResultFilePath = executionSettings.TestResultsFile; + + var logSavingCallback = ScriptableObject.CreateInstance(); + + m_TestRunnerApi.RegisterCallbacks(resultSavingCallback); + m_TestRunnerApi.RegisterCallbacks(logSavingCallback); + m_TestRunnerApi.RegisterCallbacks(ScriptableObject.CreateInstance(), -10); + var timeoutCallbacks = ScriptableObject.CreateInstance(); + timeoutCallbacks.Init((action, time) => new DelayedCallback(action, time), m_LogErrorFormat, m_ExitEditorApplication); + m_TestRunnerApi.RegisterCallbacks(timeoutCallbacks); + } + + internal void ExitOnCompileErrors() + { + if (m_ScriptCompilationFailedCheck()) + { + var handling = s_ExceptionHandlingMapping.First(h => h.m_ExceptionType == SetupException.ExceptionType.ScriptCompilationFailed); + m_LogErrorFormat(handling.m_Message, new object[0]); + m_ExitEditorApplication(handling.m_ReturnCode); + } + } + + void HandleSetupException(SetupException exception) + { + ExceptionHandling handling = s_ExceptionHandlingMapping.FirstOrDefault(h => h.m_ExceptionType == exception.Type) ?? new ExceptionHandling(exception.Type, "Unknown command line test run error. " + exception.Type, ReturnCodes.RunError); + m_LogErrorFormat(handling.m_Message, exception.Details); + m_ExitEditorApplication(handling.m_ReturnCode); + } + + private class ExceptionHandling + { + internal SetupException.ExceptionType m_ExceptionType; + internal string m_Message; + internal int m_ReturnCode; + public ExceptionHandling(SetupException.ExceptionType exceptionType, string message, ReturnCodes returnCode) + { + m_ExceptionType = exceptionType; + m_Message = message; + m_ReturnCode = (int)returnCode; + } + } + + static ExceptionHandling[] s_ExceptionHandlingMapping = new[] + { + new ExceptionHandling(SetupException.ExceptionType.ScriptCompilationFailed, "Scripts had compilation errors.", ReturnCodes.RunError), + new ExceptionHandling(SetupException.ExceptionType.PlatformNotFound, "Test platform not found ({0}).", ReturnCodes.PlatformNotFoundReturnCode), + new ExceptionHandling(SetupException.ExceptionType.TestSettingsFileNotFound, "Test settings file not found at {0}.", ReturnCodes.RunError) + }; + + private static string ExecutionSettingsToString(Api.ExecutionSettings executionSettings) + { + if (executionSettings == null) + { + return "none"; + } + + if (executionSettings.filter == null) + { + return "no filter"; + } + + return "test mode = " + executionSettings.filter.testMode; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineTest/ExecutionSettings.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineTest/ExecutionSettings.cs new file mode 100644 index 00000000..3ff23563 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineTest/ExecutionSettings.cs @@ -0,0 +1,11 @@ +using System; + +namespace UnityEditor.TestTools.TestRunner.CommandLineTest +{ + [Serializable] + internal class ExecutionSettings + { + public string TestResultsFile; + public string DeviceLogsDirectory; + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineTest/ExitCallbacks.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineTest/ExitCallbacks.cs new file mode 100644 index 00000000..d781d86a --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineTest/ExitCallbacks.cs @@ -0,0 +1,48 @@ +using System; +using UnityEditor.TestTools.TestRunner.Api; +using UnityEngine; + +namespace UnityEditor.TestTools.TestRunner.CommandLineTest +{ + [Serializable] + internal class ExitCallbacks : ScriptableObject, ICallbacks + { + private bool m_AnyTestsExecuted; + private bool m_RunFailed; + internal static bool preventExit; + + public void RunFinished(ITestResultAdaptor testResults) + { + if (preventExit) + { + return; + } + + if (!m_AnyTestsExecuted) + { + Debug.LogFormat(LogType.Warning, LogOption.NoStacktrace, null, "No tests were executed"); + } + EditorApplication.Exit(m_RunFailed ? (int)Executer.ReturnCodes.Failed : (int)Executer.ReturnCodes.Ok); + } + + public void TestStarted(ITestAdaptor test) + { + if (!test.IsSuite) + { + m_AnyTestsExecuted = true; + } + } + + public void TestFinished(ITestResultAdaptor result) + { + if (!result.Test.IsSuite && (result.TestStatus == TestStatus.Failed)) + { + m_RunFailed = true; + } + } + + public void RunStarted(ITestAdaptor testsToRun) + { + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineTest/ISettingsBuilder.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineTest/ISettingsBuilder.cs new file mode 100644 index 00000000..557195d0 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineTest/ISettingsBuilder.cs @@ -0,0 +1,10 @@ +using UnityEditor.TestTools.TestRunner.Api; + +namespace UnityEditor.TestTools.TestRunner.CommandLineTest +{ + interface ISettingsBuilder + { + Api.ExecutionSettings BuildApiExecutionSettings(string[] commandLineArgs); + ExecutionSettings BuildExecutionSettings(string[] commandLineArgs); + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineTest/LogSavingCallbacks.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineTest/LogSavingCallbacks.cs new file mode 100644 index 00000000..40a185f5 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineTest/LogSavingCallbacks.cs @@ -0,0 +1,29 @@ +using System; +using UnityEditor.TestRunner.TestLaunchers; +using UnityEditor.TestTools.TestRunner.Api; +using UnityEngine; + +namespace UnityEditor.TestTools.TestRunner.CommandLineTest +{ + [Serializable] + internal class LogSavingCallbacks : ScriptableObject, ICallbacks + { + public void RunStarted(ITestAdaptor testsToRun) + { + RemotePlayerLogController.instance.StartLogWriters(); + } + + public virtual void RunFinished(ITestResultAdaptor testResults) + { + RemotePlayerLogController.instance.StopLogWriters(); + } + + public void TestStarted(ITestAdaptor test) + { + } + + public void TestFinished(ITestResultAdaptor result) + { + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineTest/LogWriter.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineTest/LogWriter.cs new file mode 100644 index 00000000..5470fd7e --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineTest/LogWriter.cs @@ -0,0 +1,92 @@ +using System; +using System.Collections.Generic; +using System.IO; +using UnityEditor.DeploymentTargets; +using UnityEditor.Utils; +using UnityEngine; + +namespace UnityEditor.TestTools.TestRunner.CommandLineTest +{ + internal class LogWriter : IDisposable + { + private string m_LogsDirectory; + private string m_DeviceID; + private Dictionary m_LogStreams; + private DeploymentTargetLogger m_Logger; + + internal LogWriter(string logsDirectory, string deviceID, DeploymentTargetLogger logger) + { + m_LogStreams = new Dictionary(); + m_Logger = logger; + m_LogsDirectory = logsDirectory; + m_DeviceID = deviceID; + + logger.logMessage += WriteLogToFile; + } + + private void WriteLogToFile(string id, string logLine) + { + StreamWriter logStream; + var streamExists = m_LogStreams.TryGetValue(id, out logStream); + if (!streamExists) + { + var filePath = GetLogFilePath(m_LogsDirectory, m_DeviceID, id); + logStream = CreateLogFile(filePath); + + m_LogStreams.Add(id, logStream); + } + + try + { + if (logLine != null) + logStream.WriteLine(logLine); + } + catch (Exception ex) + { + Debug.LogError($"Writing {id} log failed."); + Debug.LogException(ex); + } + } + + public void Stop() + { + m_Logger.Stop(); + foreach (var logStream in m_LogStreams) + { + logStream.Value.Close(); + } + } + + public void Dispose() + { + Stop(); + } + + private StreamWriter CreateLogFile(string path) + { + Debug.LogFormat(LogType.Log, LogOption.NoStacktrace, null, "Creating {0} device log: {1}", m_DeviceID, path); + StreamWriter streamWriter = null; + try + { + if (!Directory.Exists(path)) + Directory.CreateDirectory(Path.GetDirectoryName(path)); + + streamWriter = File.CreateText(path); + } + catch (Exception ex) + { + Debug.LogError($"Creating device log {path} file failed."); + Debug.LogException(ex); + } + + return streamWriter; + } + + private string GetLogFilePath(string lgosDirectory, string deviceID, string logID) + { + var fileName = "Device-" + deviceID + "-" + logID + ".txt"; + fileName = string.Join("_", fileName.Split(Path.GetInvalidFileNameChars())); + return Paths.Combine(lgosDirectory, fileName); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineTest/ResultsSavingCallbacks.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineTest/ResultsSavingCallbacks.cs new file mode 100644 index 00000000..a3837bf9 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineTest/ResultsSavingCallbacks.cs @@ -0,0 +1,50 @@ +using System; +using System.IO; +using UnityEditor.TestTools.TestRunner.Api; +using UnityEditor.Utils; +using UnityEngine; + +namespace UnityEditor.TestTools.TestRunner.CommandLineTest +{ + [Serializable] + internal class ResultsSavingCallbacks : ScriptableObject, ICallbacks + { + [SerializeField] + public string m_ResultFilePath; + + public ResultsSavingCallbacks() + { + this.m_ResultFilePath = GetDefaultResultFilePath(); + } + + public void RunStarted(ITestAdaptor testsToRun) + { + } + + public virtual void RunFinished(ITestResultAdaptor testResults) + { + if (string.IsNullOrEmpty(m_ResultFilePath)) + { + m_ResultFilePath = GetDefaultResultFilePath(); + } + + var resultWriter = new ResultsWriter(); + resultWriter.WriteResultToFile(testResults, m_ResultFilePath); + } + + public void TestStarted(ITestAdaptor test) + { + } + + public void TestFinished(ITestResultAdaptor result) + { + } + + private static string GetDefaultResultFilePath() + { + var fileName = "TestResults-" + DateTime.Now.Ticks + ".xml"; + var projectPath = Directory.GetCurrentDirectory(); + return Paths.Combine(projectPath, fileName); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineTest/ResultsWriter.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineTest/ResultsWriter.cs new file mode 100644 index 00000000..073d2ecd --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineTest/ResultsWriter.cs @@ -0,0 +1,99 @@ +using System; +using System.IO; +using System.Xml; +using NUnit.Framework.Interfaces; +using UnityEditor.TestTools.TestRunner.Api; +using UnityEngine; + +namespace UnityEditor.TestTools.TestRunner.CommandLineTest +{ + internal class ResultsWriter + { + private const string k_nUnitVersion = "3.5.0.0"; + + private const string k_TestRunNode = "test-run"; + private const string k_Id = "id"; + private const string k_Testcasecount = "testcasecount"; + private const string k_Result = "result"; + private const string k_Total = "total"; + private const string k_Passed = "passed"; + private const string k_Failed = "failed"; + private const string k_Inconclusive = "inconclusive"; + private const string k_Skipped = "skipped"; + private const string k_Asserts = "asserts"; + private const string k_EngineVersion = "engine-version"; + private const string k_ClrVersion = "clr-version"; + private const string k_StartTime = "start-time"; + private const string k_EndTime = "end-time"; + private const string k_Duration = "duration"; + + private const string k_TimeFormat = "u"; + + public void WriteResultToFile(ITestResultAdaptor result, string filePath) + { + Debug.LogFormat(LogType.Log, LogOption.NoStacktrace, null, "Saving results to: {0}", filePath); + + try + { + if (!Directory.Exists(filePath)) + { + CreateDirectory(filePath); + } + + using (var fileStream = File.CreateText(filePath)) + { + WriteResultToStream(result, fileStream); + } + } + catch (Exception ex) + { + Debug.LogError("Saving result file failed."); + Debug.LogException(ex); + } + } + + void CreateDirectory(string filePath) + { + Directory.CreateDirectory(Path.GetDirectoryName(filePath)); + } + + public void WriteResultToStream(ITestResultAdaptor result, StreamWriter streamWriter, XmlWriterSettings settings = null) + { + settings = settings ?? new XmlWriterSettings(); + settings.Indent = true; + settings.NewLineOnAttributes = false; + + using (var xmlWriter = XmlWriter.Create(streamWriter, settings)) + { + WriteResultsToXml(result, xmlWriter); + } + } + + void WriteResultsToXml(ITestResultAdaptor result, XmlWriter xmlWriter) + { + // XML format as specified at https://github.com/nunit/docs/wiki/Test-Result-XML-Format + + var testRunNode = new TNode(k_TestRunNode); + + testRunNode.AddAttribute(k_Id, "2"); + testRunNode.AddAttribute(k_Testcasecount, (result.PassCount + result.FailCount + result.SkipCount + result.InconclusiveCount).ToString()); + testRunNode.AddAttribute(k_Result, result.ResultState.ToString()); + testRunNode.AddAttribute(k_Total, (result.PassCount + result.FailCount + result.SkipCount + result.InconclusiveCount).ToString()); + testRunNode.AddAttribute(k_Passed, result.PassCount.ToString()); + testRunNode.AddAttribute(k_Failed, result.FailCount.ToString()); + testRunNode.AddAttribute(k_Inconclusive, result.InconclusiveCount.ToString()); + testRunNode.AddAttribute(k_Skipped, result.SkipCount.ToString()); + testRunNode.AddAttribute(k_Asserts, result.AssertCount.ToString()); + testRunNode.AddAttribute(k_EngineVersion, k_nUnitVersion); + testRunNode.AddAttribute(k_ClrVersion, Environment.Version.ToString()); + testRunNode.AddAttribute(k_StartTime, result.StartTime.ToString(k_TimeFormat)); + testRunNode.AddAttribute(k_EndTime, result.EndTime.ToString(k_TimeFormat)); + testRunNode.AddAttribute(k_Duration, result.Duration.ToString()); + + var resultNode = result.ToXml(); + testRunNode.ChildNodes.Add(resultNode); + + testRunNode.WriteTo(xmlWriter); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineTest/RunData.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineTest/RunData.cs new file mode 100644 index 00000000..6a469a7b --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineTest/RunData.cs @@ -0,0 +1,8 @@ +namespace UnityEditor.TestTools.TestRunner.CommandLineTest +{ + internal class RunData : ScriptableSingleton + { + public bool isRunning; + public ExecutionSettings executionSettings; + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineTest/RunSettings.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineTest/RunSettings.cs new file mode 100644 index 00000000..9b914c75 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineTest/RunSettings.cs @@ -0,0 +1,29 @@ +using UnityEditor.TestTools.TestRunner.Api; + +namespace UnityEditor.TestTools.TestRunner.CommandLineTest +{ + internal class RunSettings : ITestRunSettings + { + private ITestSettings m_TestSettings; + public RunSettings(ITestSettings testSettings) + { + this.m_TestSettings = testSettings; + } + + public void Apply() + { + if (m_TestSettings != null) + { + m_TestSettings.SetupProjectParameters(); + } + } + + public void Dispose() + { + if (m_TestSettings != null) + { + m_TestSettings.Dispose(); + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineTest/SettingsBuilder.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineTest/SettingsBuilder.cs new file mode 100644 index 00000000..ef7500c6 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineTest/SettingsBuilder.cs @@ -0,0 +1,173 @@ +using System; +using System.IO; +using UnityEditor.TestRunner.CommandLineParser; +using UnityEditor.TestTools.TestRunner.Api; +using UnityEngine.TestTools.TestRunner.GUI; + +namespace UnityEditor.TestTools.TestRunner.CommandLineTest +{ + internal class SettingsBuilder : ISettingsBuilder + { + private ITestSettingsDeserializer m_TestSettingsDeserializer; + private Action m_LogAction; + private Action m_LogWarningAction; + private Func m_FileExistsCheck; + private Func m_ScriptCompilationFailedCheck; + public SettingsBuilder(ITestSettingsDeserializer testSettingsDeserializer, Action logAction, Action logWarningAction, Func fileExistsCheck, Func scriptCompilationFailedCheck) + { + m_LogAction = logAction; + m_LogWarningAction = logWarningAction; + m_FileExistsCheck = fileExistsCheck; + m_ScriptCompilationFailedCheck = scriptCompilationFailedCheck; + m_TestSettingsDeserializer = testSettingsDeserializer; + } + + public Api.ExecutionSettings BuildApiExecutionSettings(string[] commandLineArgs) + { + var quit = false; + string testPlatform = TestMode.EditMode.ToString(); + string[] testFilters = null; + string[] testCategories = null; + string testSettingsFilePath = null; + int testRepetitions = 1; + + var optionSet = new CommandLineOptionSet( + new CommandLineOption("quit", () => { quit = true; }), + new CommandLineOption("testPlatform", platform => { testPlatform = platform; }), + new CommandLineOption("editorTestsFilter", filters => { testFilters = filters; }), + new CommandLineOption("testFilter", filters => { testFilters = filters; }), + new CommandLineOption("editorTestsCategories", catagories => { testCategories = catagories; }), + new CommandLineOption("testCategory", catagories => { testCategories = catagories; }), + new CommandLineOption("testSettingsFile", settingsFilePath => { testSettingsFilePath = settingsFilePath; }), + new CommandLineOption("testRepetitions", reps => { testRepetitions = int.Parse(reps); }) + ); + optionSet.Parse(commandLineArgs); + + DisplayQuitWarningIfQuitIsGiven(quit); + + CheckForScriptCompilationErrors(); + + LogParametersForRun(testPlatform, testFilters, testCategories, testSettingsFilePath); + + var testSettings = GetTestSettings(testSettingsFilePath); + + var filter = new Filter() + { + groupNames = testFilters, + categoryNames = testCategories + }; + + var buildTarget = SetFilterAndGetBuildTarget(testPlatform, filter); + + RerunCallbackData.instance.runFilter = new TestRunnerFilter() + { + categoryNames = filter.categoryNames, + groupNames = filter.groupNames, + testRepetitions = testRepetitions + }; + + RerunCallbackData.instance.testMode = filter.testMode; + + return new Api.ExecutionSettings() + { + filter = filter, + overloadTestRunSettings = new RunSettings(testSettings), + targetPlatform = buildTarget + }; + } + + public ExecutionSettings BuildExecutionSettings(string[] commandLineArgs) + { + string resultFilePath = null; + string deviceLogsDirectory = null; + + var optionSet = new CommandLineOptionSet( + new CommandLineOption("editorTestsResultFile", filePath => { resultFilePath = filePath; }), + new CommandLineOption("testResults", filePath => { resultFilePath = filePath; }), + new CommandLineOption("deviceLogs", dirPath => { deviceLogsDirectory = dirPath; }) + ); + optionSet.Parse(commandLineArgs); + + return new ExecutionSettings() + { + TestResultsFile = resultFilePath, + DeviceLogsDirectory = deviceLogsDirectory + }; + } + + void DisplayQuitWarningIfQuitIsGiven(bool quitIsGiven) + { + if (quitIsGiven) + { + m_LogWarningAction("Running tests from command line arguments will not work when \"quit\" is specified."); + } + } + + void CheckForScriptCompilationErrors() + { + if (m_ScriptCompilationFailedCheck()) + { + throw new SetupException(SetupException.ExceptionType.ScriptCompilationFailed); + } + } + + void LogParametersForRun(string testPlatform, string[] testFilters, string[] testCategories, string testSettingsFilePath) + { + m_LogAction("Running tests for " + testPlatform); + if (testFilters != null && testFilters.Length > 0) + { + m_LogAction("With test filter: " + string.Join(", ", testFilters)); + } + if (testCategories != null && testCategories.Length > 0) + { + m_LogAction("With test categories: " + string.Join(", ", testCategories)); + } + if (!string.IsNullOrEmpty(testSettingsFilePath)) + { + m_LogAction("With test settings file: " + testSettingsFilePath); + } + } + + ITestSettings GetTestSettings(string testSettingsFilePath) + { + ITestSettings testSettings = null; + if (!string.IsNullOrEmpty(testSettingsFilePath)) + { + if (!m_FileExistsCheck(testSettingsFilePath)) + { + throw new SetupException(SetupException.ExceptionType.TestSettingsFileNotFound, testSettingsFilePath); + } + + testSettings = m_TestSettingsDeserializer.GetSettingsFromJsonFile(testSettingsFilePath); + } + return testSettings; + } + + static BuildTarget? SetFilterAndGetBuildTarget(string testPlatform, Filter filter) + { + BuildTarget? buildTarget = null; + if (testPlatform.ToLower() == "editmode") + { + filter.testMode = TestMode.EditMode; + } + else if (testPlatform.ToLower() == "playmode") + { + filter.testMode = TestMode.PlayMode; + } + else + { + try + { + buildTarget = (BuildTarget)Enum.Parse(typeof(BuildTarget), testPlatform, true); + + filter.testMode = TestMode.PlayMode; + } + catch (ArgumentException) + { + throw new SetupException(SetupException.ExceptionType.PlatformNotFound, testPlatform); + } + } + return buildTarget; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineTest/SetupException.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineTest/SetupException.cs new file mode 100644 index 00000000..33377134 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineTest/SetupException.cs @@ -0,0 +1,23 @@ +using System; + +namespace UnityEditor.TestTools.TestRunner.CommandLineTest +{ + internal class SetupException : Exception + { + public ExceptionType Type { get; } + public object[] Details { get; } + + public SetupException(ExceptionType type, params object[] details) + { + Type = type; + Details = details; + } + + public enum ExceptionType + { + ScriptCompilationFailed, + PlatformNotFound, + TestSettingsFileNotFound, + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineTest/TestStarter.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineTest/TestStarter.cs new file mode 100644 index 00000000..bced7274 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineTest/TestStarter.cs @@ -0,0 +1,80 @@ +using System; +using System.IO; +using UnityEditor.TestRunner.CommandLineParser; +using UnityEditor.TestTools.TestRunner.Api; +using UnityEngine; + +namespace UnityEditor.TestTools.TestRunner.CommandLineTest +{ + [InitializeOnLoad] + static class TestStarter + { + static TestStarter() + { + if (!ShouldRunTests()) + { + return; + } + + if (EditorApplication.isCompiling) + { + return; + } + + executer.ExitOnCompileErrors(); + + if (RunData.instance.isRunning) + { + executer.SetUpCallbacks(RunData.instance.executionSettings); + return; + } + + EditorApplication.update += UpdateWatch; + } + + static void UpdateWatch() + { + EditorApplication.update -= UpdateWatch; + + if (RunData.instance.isRunning) + { + return; + } + + RunData.instance.isRunning = true; + var commandLineArgs = Environment.GetCommandLineArgs(); + RunData.instance.executionSettings = executer.BuildExecutionSettings(commandLineArgs); + executer.SetUpCallbacks(RunData.instance.executionSettings); + executer.InitializeAndExecuteRun(commandLineArgs); + } + + static bool ShouldRunTests() + { + var shouldRunTests = false; + var optionSet = new CommandLineOptionSet( + new CommandLineOption("runTests", () => { shouldRunTests = true; }), + new CommandLineOption("runEditorTests", () => { shouldRunTests = true; }) + ); + optionSet.Parse(Environment.GetCommandLineArgs()); + return shouldRunTests; + } + + static Executer s_Executer; + + static Executer executer + { + get + { + if (s_Executer == null) + { + Func compilationCheck = () => EditorUtility.scriptCompilationFailed; + Action actionLogger = (string msg) => { Debug.LogFormat(LogType.Log, LogOption.NoStacktrace, null, msg); }; + var apiSettingsBuilder = new SettingsBuilder(new TestSettingsDeserializer(() => new TestSettings()), actionLogger, Debug.LogWarning, File.Exists, compilationCheck); + s_Executer = new Executer(ScriptableObject.CreateInstance(), apiSettingsBuilder, Debug.LogErrorFormat, Debug.LogException, EditorApplication.Exit, compilationCheck); + } + + return s_Executer; + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineTest/TimeoutCallbacks.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineTest/TimeoutCallbacks.cs new file mode 100644 index 00000000..8e509934 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/CommandLineTest/TimeoutCallbacks.cs @@ -0,0 +1,74 @@ +using System; +using UnityEditor.TestRunner.TestLaunchers; +using UnityEditor.TestTools.TestRunner.Api; +using UnityEngine; + +namespace UnityEditor.TestTools.TestRunner.CommandLineTest +{ + internal class TimeoutCallbacks : ScriptableObject, ICallbacks + { + internal const int k_DefaultTimeout = 600; + + private Func m_DelayedCallbackFactory; + private Action m_LogErrorFormat; + private Action m_ExitApplication; + + private double m_CurrentTimeout; + private IDelayedCallback m_TimeoutCallback; + + public void Init(Func delayedCallbackFactory, Action logErrorFormat, Action exitApplication) + { + m_DelayedCallbackFactory = delayedCallbackFactory; + m_LogErrorFormat = logErrorFormat; + m_ExitApplication = exitApplication; + } + + public void RunFinished(ITestResultAdaptor result) + { + if (m_TimeoutCallback != null) + { + m_TimeoutCallback.Clear(); + } + } + + public void RunStarted(ITestAdaptor testsToRun) + { + ResetToTimeout(k_DefaultTimeout); + } + + public void TestFinished(ITestResultAdaptor result) + { + ResetToTimeout(k_DefaultTimeout); + } + + public void TestStarted(ITestAdaptor test) + { + ResetToTimeout(k_DefaultTimeout + test.TestCaseTimeout / 1000); + } + + private void ResetToTimeout(double timeoutValue) + { + if (m_TimeoutCallback != null && Math.Abs(m_CurrentTimeout - timeoutValue) < 0.1f) + { + m_TimeoutCallback.Reset(); + } + else + { + if (m_TimeoutCallback != null) + { + m_TimeoutCallback.Clear(); + } + + m_TimeoutCallback = m_DelayedCallbackFactory(TimeoutReached, timeoutValue); + m_CurrentTimeout = timeoutValue; + } + } + + private void TimeoutReached() + { + RemotePlayerLogController.instance.StopLogWriters(); + m_LogErrorFormat("Test execution timed out.", new object[0]); + m_ExitApplication((int)Executer.ReturnCodes.RunError); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/AssetsDatabaseHelper.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/AssetsDatabaseHelper.cs new file mode 100644 index 00000000..0016142e --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/AssetsDatabaseHelper.cs @@ -0,0 +1,11 @@ +namespace UnityEditor.TestTools.TestRunner.GUI +{ + internal class AssetsDatabaseHelper : IAssetsDatabaseHelper + { + public void OpenAssetInItsDefaultExternalEditor(string assetPath, int line) + { + var asset = AssetDatabase.LoadMainAssetAtPath(assetPath); + AssetDatabase.OpenAsset(asset, line); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/GuiHelper.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/GuiHelper.cs new file mode 100644 index 00000000..26aba74e --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/GuiHelper.cs @@ -0,0 +1,101 @@ +using System; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text.RegularExpressions; +using UnityEditor.Utils; +using UnityEngine; + +namespace UnityEditor.TestTools.TestRunner.GUI +{ + internal class GuiHelper : IGuiHelper + { + public GuiHelper(IMonoCecilHelper monoCecilHelper, IAssetsDatabaseHelper assetsDatabaseHelper) + { + MonoCecilHelper = monoCecilHelper; + AssetsDatabaseHelper = assetsDatabaseHelper; + } + + protected IMonoCecilHelper MonoCecilHelper { get; private set; } + public IAssetsDatabaseHelper AssetsDatabaseHelper { get; private set; } + + public void OpenScriptInExternalEditor(Type type, MethodInfo method) + { + var fileOpenInfo = GetFileOpenInfo(type, method); + + if (string.IsNullOrEmpty(fileOpenInfo.FilePath)) + { + Debug.LogWarning("Failed to open test method source code in external editor. Inconsistent filename and yield return operator in target method."); + + return; + } + + if (fileOpenInfo.LineNumber == 1) + { + Debug.LogWarning("Failed to get a line number for unity test method. So please find it in opened file in external editor."); + } + + AssetsDatabaseHelper.OpenAssetInItsDefaultExternalEditor(fileOpenInfo.FilePath, fileOpenInfo.LineNumber); + } + + public IFileOpenInfo GetFileOpenInfo(Type type, MethodInfo method) + { + const string fileExtension = ".cs"; + + var fileOpenInfo = MonoCecilHelper.TryGetCecilFileOpenInfo(type, method); + if (string.IsNullOrEmpty(fileOpenInfo.FilePath)) + { + var dirPath = Paths.UnifyDirectorySeparator(Application.dataPath); + var allCsFiles = Directory.GetFiles(dirPath, string.Format("*{0}", fileExtension), SearchOption.AllDirectories) + .Select(Paths.UnifyDirectorySeparator); + + var fileName = allCsFiles.FirstOrDefault(x => + x.Split(Path.DirectorySeparatorChar).Last().Equals(string.Concat(type.Name, fileExtension))); + + fileOpenInfo.FilePath = fileName ?? string.Empty; + } + + fileOpenInfo.FilePath = FilePathToAssetsRelativeAndUnified(fileOpenInfo.FilePath); + + return fileOpenInfo; + } + + public string FilePathToAssetsRelativeAndUnified(string filePath) + { + if (string.IsNullOrEmpty(filePath)) + return string.Empty; + + filePath = Paths.UnifyDirectorySeparator(filePath); + var length = Paths.UnifyDirectorySeparator(Application.dataPath).Length - "Assets".Length; + + return filePath.Substring(length); + } + + public bool OpenScriptInExternalEditor(string stacktrace) + { + if (string.IsNullOrEmpty(stacktrace)) + return false; + + var regex = new Regex("in (?.*):{1}(?[0-9]+)"); + + var matchingLines = stacktrace.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).Where(x => regex.IsMatch(x)).ToList(); + if (!matchingLines.Any()) + return false; + + var fileOpenInfo = matchingLines + .Select(x => regex.Match(x)) + .Select(x => + new FileOpenInfo + { + FilePath = x.Groups["path"].Value, + LineNumber = int.Parse(x.Groups["line"].Value) + }) + .First(openInfo => !string.IsNullOrEmpty(openInfo.FilePath) && File.Exists(openInfo.FilePath)); + + var filePath = FilePathToAssetsRelativeAndUnified(fileOpenInfo.FilePath); + AssetsDatabaseHelper.OpenAssetInItsDefaultExternalEditor(filePath, fileOpenInfo.LineNumber); + + return true; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/IAssetsDatabaseHelper.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/IAssetsDatabaseHelper.cs new file mode 100644 index 00000000..3e26c53a --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/IAssetsDatabaseHelper.cs @@ -0,0 +1,7 @@ +namespace UnityEditor.TestTools.TestRunner.GUI +{ + internal interface IAssetsDatabaseHelper + { + void OpenAssetInItsDefaultExternalEditor(string assetPath, int line); + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/IGuiHelper.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/IGuiHelper.cs new file mode 100644 index 00000000..a87fb8df --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/IGuiHelper.cs @@ -0,0 +1,13 @@ +using System; +using System.Reflection; + +namespace UnityEditor.TestTools.TestRunner.GUI +{ + internal interface IGuiHelper + { + bool OpenScriptInExternalEditor(string stacktrace); + void OpenScriptInExternalEditor(Type type, MethodInfo method); + IFileOpenInfo GetFileOpenInfo(Type type, MethodInfo method); + string FilePathToAssetsRelativeAndUnified(string filePath); + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/TestListBuilder/RenderingOptions.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/TestListBuilder/RenderingOptions.cs new file mode 100644 index 00000000..34118d65 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/TestListBuilder/RenderingOptions.cs @@ -0,0 +1,12 @@ +namespace UnityEditor.TestTools.TestRunner.GUI +{ + internal class RenderingOptions + { + public string nameFilter; + public bool showSucceeded; + public bool showFailed; + public bool showIgnored; + public bool showNotRunned; + public string[] categories; + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/TestListBuilder/ResultSummarizer.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/TestListBuilder/ResultSummarizer.cs new file mode 100644 index 00000000..cee81dab --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/TestListBuilder/ResultSummarizer.cs @@ -0,0 +1,175 @@ +// **************************************************************** +// Based on nUnit 2.6.2 (http://www.nunit.org/) +// **************************************************************** + +using System; +using System.Collections.Generic; +using UnityEngine.TestTools.TestRunner.GUI; + +namespace UnityEditor.TestTools.TestRunner.GUI +{ + /// + /// Summary description for ResultSummarizer. + /// + internal class ResultSummarizer + { + private int m_ErrorCount = -1; + private int m_FailureCount; + private int m_IgnoreCount = -1; + private int m_InconclusiveCount = -1; + private int m_NotRunnable = -1; + private int m_ResultCount; + private int m_SkipCount; + private int m_SuccessCount; + private int m_TestsRun; + + private TimeSpan m_Duration = TimeSpan.FromSeconds(0); + + public ResultSummarizer(IEnumerable results) + { + foreach (var result in results) + Summarize(result); + } + + public bool success + { + get { return m_FailureCount == 0; } + } + + /// + /// Returns the number of test cases for which results + /// have been summarized. Any tests excluded by use of + /// Category or Explicit attributes are not counted. + /// + public int ResultCount + { + get { return m_ResultCount; } + } + + /// + /// Returns the number of test cases actually run, which + /// is the same as ResultCount, less any Skipped, Ignored + /// or NonRunnable tests. + /// + public int TestsRun + { + get { return m_TestsRun; } + } + + /// + /// Returns the number of tests that passed + /// + public int Passed + { + get { return m_SuccessCount; } + } + + /// + /// Returns the number of test cases that had an error. + /// + public int errors + { + get { return m_ErrorCount; } + } + + /// + /// Returns the number of test cases that failed. + /// + public int failures + { + get { return m_FailureCount; } + } + + /// + /// Returns the number of test cases that failed. + /// + public int inconclusive + { + get { return m_InconclusiveCount; } + } + + /// + /// Returns the number of test cases that were not runnable + /// due to errors in the signature of the class or method. + /// Such tests are also counted as Errors. + /// + public int notRunnable + { + get { return m_NotRunnable; } + } + + /// + /// Returns the number of test cases that were skipped. + /// + public int Skipped + { + get { return m_SkipCount; } + } + + public int ignored + { + get { return m_IgnoreCount; } + } + + public double duration + { + get { return m_Duration.TotalSeconds; } + } + + public int testsNotRun + { + get { return m_SkipCount + m_IgnoreCount + m_NotRunnable; } + } + + public void Summarize(TestRunnerResult result) + { + m_Duration += TimeSpan.FromSeconds(result.duration); + m_ResultCount++; + + if (result.resultStatus != TestRunnerResult.ResultStatus.NotRun) + { + //TODO implement missing features + // if(result.IsIgnored) + // { + // m_IgnoreCount++; + // return; + // } + + m_SkipCount++; + return; + } + + switch (result.resultStatus) + { + case TestRunnerResult.ResultStatus.Passed: + m_SuccessCount++; + m_TestsRun++; + break; + case TestRunnerResult.ResultStatus.Failed: + m_FailureCount++; + m_TestsRun++; + break; + //TODO implement missing features + // case TestResultState.Error: + // case TestResultState.Cancelled: + // m_ErrorCount++; + // m_TestsRun++; + // break; + // case TestResultState.Inconclusive: + // m_InconclusiveCount++; + // m_TestsRun++; + // break; + // case TestResultState.NotRunnable: + // m_NotRunnable++; + // // errorCount++; + // break; + // case TestResultState.Ignored: + // m_IgnoreCount++; + // break; + default: + m_SkipCount++; + break; + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/TestListBuilder/TestFilterSettings.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/TestListBuilder/TestFilterSettings.cs new file mode 100644 index 00000000..576a685b --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/TestListBuilder/TestFilterSettings.cs @@ -0,0 +1,105 @@ +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +using UnityEngine.TestTools.TestRunner.GUI; + +namespace UnityEditor.TestTools.TestRunner.GUI +{ + internal class TestFilterSettings + { + public bool showSucceeded; + public bool showFailed; + public bool showIgnored; + public bool showNotRun; + + public string filterByName; + public int filterByCategory; + + private GUIContent m_SucceededBtn; + private GUIContent m_FailedBtn; + private GUIContent m_IgnoredBtn; + private GUIContent m_NotRunBtn; + + public string[] availableCategories; + + private readonly string m_PrefsKey; + + public TestFilterSettings(string prefsKey) + { + availableCategories = null; + m_PrefsKey = prefsKey; + Load(); + UpdateCounters(Enumerable.Empty()); + } + + public void Load() + { + showSucceeded = EditorPrefs.GetBool(m_PrefsKey + ".ShowSucceeded", true); + showFailed = EditorPrefs.GetBool(m_PrefsKey + ".ShowFailed", true); + showIgnored = EditorPrefs.GetBool(m_PrefsKey + ".ShowIgnored", true); + showNotRun = EditorPrefs.GetBool(m_PrefsKey + ".ShowNotRun", true); + filterByName = EditorPrefs.GetString(m_PrefsKey + ".FilterByName", string.Empty); + filterByCategory = EditorPrefs.GetInt(m_PrefsKey + ".FilterByCategory", 0); + } + + public void Save() + { + EditorPrefs.SetBool(m_PrefsKey + ".ShowSucceeded", showSucceeded); + EditorPrefs.SetBool(m_PrefsKey + ".ShowFailed", showFailed); + EditorPrefs.SetBool(m_PrefsKey + ".ShowIgnored", showIgnored); + EditorPrefs.SetBool(m_PrefsKey + ".ShowNotRun", showNotRun); + EditorPrefs.SetString(m_PrefsKey + ".FilterByName", filterByName); + EditorPrefs.SetInt(m_PrefsKey + ".FilterByCategory", filterByCategory); + } + + public void UpdateCounters(IEnumerable results) + { + var summary = new ResultSummarizer(results); + + m_SucceededBtn = new GUIContent(summary.Passed.ToString(), Icons.s_SuccessImg, "Show tests that succeeded"); + m_FailedBtn = new GUIContent((summary.errors + summary.failures + summary.inconclusive).ToString(), Icons.s_FailImg, "Show tests that failed"); + m_IgnoredBtn = new GUIContent((summary.ignored + summary.notRunnable).ToString(), Icons.s_IgnoreImg, "Show tests that are ignored"); + m_NotRunBtn = new GUIContent((summary.testsNotRun - summary.ignored - summary.notRunnable).ToString(), Icons.s_UnknownImg, "Show tests that didn't run"); + } + + public string[] GetSelectedCategories() + { + if (availableCategories == null) + return new string[0]; + + return availableCategories.Where((c, i) => (filterByCategory & (1 << i)) != 0).ToArray(); + } + + public void OnGUI() + { + EditorGUI.BeginChangeCheck(); + + filterByName = GUILayout.TextField(filterByName, "ToolbarSeachTextField", GUILayout.MinWidth(100), GUILayout.MaxWidth(250), GUILayout.ExpandWidth(true)); + if (GUILayout.Button(GUIContent.none, string.IsNullOrEmpty(filterByName) ? "ToolbarSeachCancelButtonEmpty" : "ToolbarSeachCancelButton")) + filterByName = string.Empty; + + if (availableCategories != null && availableCategories.Length > 0) + filterByCategory = EditorGUILayout.MaskField(filterByCategory, availableCategories, EditorStyles.toolbarDropDown, GUILayout.MaxWidth(90)); + + showSucceeded = GUILayout.Toggle(showSucceeded, m_SucceededBtn, EditorStyles.toolbarButton); + showFailed = GUILayout.Toggle(showFailed, m_FailedBtn, EditorStyles.toolbarButton); + showIgnored = GUILayout.Toggle(showIgnored, m_IgnoredBtn, EditorStyles.toolbarButton); + showNotRun = GUILayout.Toggle(showNotRun, m_NotRunBtn, EditorStyles.toolbarButton); + + if (EditorGUI.EndChangeCheck()) + Save(); + } + + public RenderingOptions BuildRenderingOptions() + { + var options = new RenderingOptions(); + options.showSucceeded = showSucceeded; + options.showFailed = showFailed; + options.showIgnored = showIgnored; + options.showNotRunned = showNotRun; + options.nameFilter = filterByName; + options.categories = GetSelectedCategories(); + return options; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/TestListBuilder/TestTreeViewBuilder.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/TestListBuilder/TestTreeViewBuilder.cs new file mode 100644 index 00000000..86d42f3a --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/TestListBuilder/TestTreeViewBuilder.cs @@ -0,0 +1,111 @@ +using System.Collections.Generic; +using System.Linq; +using UnityEditor.IMGUI.Controls; +using UnityEditor.TestTools.TestRunner.Api; +using UnityEngine.TestRunner.NUnitExtensions; +using UnityEngine.TestTools.TestRunner.GUI; +using UnityEngine.TestRunner.NUnitExtensions.Filters; + +namespace UnityEditor.TestTools.TestRunner.GUI +{ + internal class TestTreeViewBuilder + { + public List results = new List(); + private readonly List m_OldTestResultList; + private readonly TestRunnerUIFilter m_UIFilter; + private readonly ITestAdaptor m_TestListRoot; + + private readonly List m_AvailableCategories = new List(); + + public string[] AvailableCategories + { + get { return m_AvailableCategories.Distinct().OrderBy(a => a).ToArray(); } + } + + public TestTreeViewBuilder(ITestAdaptor tests, List oldTestResultResults, TestRunnerUIFilter uiFilter) + { + m_AvailableCategories.Add(CategoryFilterExtended.k_DefaultCategory); + m_OldTestResultList = oldTestResultResults; + m_TestListRoot = tests; + m_UIFilter = uiFilter; + } + + public TreeViewItem BuildTreeView(TestFilterSettings settings, bool sceneBased, string sceneName) + { + var rootItem = new TreeViewItem(int.MaxValue, 0, null, "Invisible Root Item"); + ParseTestTree(0, rootItem, m_TestListRoot); + return rootItem; + } + + private bool IsFilteredOutByUIFilter(ITestAdaptor test, TestRunnerResult result) + { + if (m_UIFilter.PassedHidden && result.resultStatus == TestRunnerResult.ResultStatus.Passed) + return true; + if (m_UIFilter.FailedHidden && (result.resultStatus == TestRunnerResult.ResultStatus.Failed || result.resultStatus == TestRunnerResult.ResultStatus.Inconclusive)) + return true; + if (m_UIFilter.NotRunHidden && (result.resultStatus == TestRunnerResult.ResultStatus.NotRun || result.resultStatus == TestRunnerResult.ResultStatus.Skipped)) + return true; + if (m_UIFilter.CategoryFilter.Length > 0) + return !test.Categories.Any(category => m_UIFilter.CategoryFilter.Contains(category)); + return false; + } + + private void ParseTestTree(int depth, TreeViewItem rootItem, ITestAdaptor testElement) + { + m_AvailableCategories.AddRange(testElement.Categories); + + var testElementId = testElement.UniqueName; + if (!testElement.HasChildren) + { + var result = m_OldTestResultList.FirstOrDefault(a => a.uniqueId == testElementId); + + if (result != null && + (result.ignoredOrSkipped + || result.notRunnable + || testElement.RunState == RunState.NotRunnable + || testElement.RunState == RunState.Ignored + || testElement.RunState == RunState.Skipped + ) + ) + { + //if the test was or becomes ignored or not runnable, we recreate the result in case it has changed + result = null; + } + if (result == null) + { + result = new TestRunnerResult(testElement); + } + results.Add(result); + + var test = new TestTreeViewItem(testElement, depth, rootItem); + if (!IsFilteredOutByUIFilter(testElement, result)) + rootItem.AddChild(test); + test.SetResult(result); + return; + } + + var groupResult = m_OldTestResultList.FirstOrDefault(a => a.uniqueId == testElementId); + if (groupResult == null) + { + groupResult = new TestRunnerResult(testElement); + } + + results.Add(groupResult); + var group = new TestTreeViewItem(testElement, depth, rootItem); + group.SetResult(groupResult); + + depth++; + foreach (var child in testElement.Children) + { + ParseTestTree(depth, group, child); + } + + + if (testElement.IsTestAssembly && !testElement.HasChildren) + return; + + if (group.hasChildren) + rootItem.AddChild(group); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/TestListGuiHelper.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/TestListGuiHelper.cs new file mode 100644 index 00000000..05cadbac --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/TestListGuiHelper.cs @@ -0,0 +1,135 @@ +using System; +using System.IO; +using System.Linq; +using UnityEditor.ProjectWindowCallback; +using UnityEditor.Scripting.ScriptCompilation; +using UnityEngine; + +namespace UnityEditor.TestTools.TestRunner.GUI +{ + internal class TestListGUIHelper + { + private const string kResourcesTemplatePath = "Resources/ScriptTemplates"; + private const string kAssemblyDefinitionTestTemplate = "92-Assembly Definition-NewTestAssembly.asmdef.txt"; + + private const string kAssemblyDefinitionEditModeTestTemplate = + "92-Assembly Definition-NewEditModeTestAssembly.asmdef.txt"; + + private const string kTestScriptTemplate = "83-C# Script-NewTestScript.cs.txt"; + private const string kNewTestScriptName = "NewTestScript.cs"; + private const string kNunit = "nunit.framework.dll"; + + [MenuItem("Assets/Create/Testing/Tests Assembly Folder", false, 83)] + public static void MenuItemAddFolderAndAsmDefForTesting() + { + AddFolderAndAsmDefForTesting(); + } + + [MenuItem("Assets/Create/Testing/Tests Assembly Folder", true, 83)] + public static bool MenuItemAddFolderAndAsmDefForTestingWithValidation() + { + return !SelectedFolderContainsTestAssembly(); + } + + public static void AddFolderAndAsmDefForTesting(bool isEditorOnly = false) + { + ProjectWindowUtil.CreateFolderWithTemplates("Tests", + isEditorOnly ? kAssemblyDefinitionEditModeTestTemplate : kAssemblyDefinitionTestTemplate); + } + + public static bool SelectedFolderContainsTestAssembly() + { + var theNearestCustomScriptAssembly = GetTheNearestCustomScriptAssembly(); + if (theNearestCustomScriptAssembly != null) + { + return theNearestCustomScriptAssembly.PrecompiledReferences != null && theNearestCustomScriptAssembly.PrecompiledReferences.Any(x => Path.GetFileName(x) == kNunit); + } + + return false; + } + + [MenuItem("Assets/Create/Testing/C# Test Script", false, 83)] + public static void AddTest() + { + var basePath = Path.Combine(EditorApplication.applicationContentsPath, kResourcesTemplatePath); + var destPath = Path.Combine(GetActiveFolderPath(), kNewTestScriptName); + var templatePath = Path.Combine(basePath, kTestScriptTemplate); + var icon = EditorGUIUtility.IconContent("cs Script Icon").image as Texture2D; + ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, + ScriptableObject.CreateInstance(), destPath, icon, templatePath); + + AssetDatabase.Refresh(); + } + + [MenuItem("Assets/Create/Testing/C# Test Script", true, 83)] + public static bool CanAddScriptAndItWillCompile() + { + return CanAddEditModeTestScriptAndItWillCompile() || CanAddPlayModeTestScriptAndItWillCompile(); + } + + public static bool CanAddEditModeTestScriptAndItWillCompile() + { + var theNearestCustomScriptAssembly = GetTheNearestCustomScriptAssembly(); + if (theNearestCustomScriptAssembly != null) + { + return (theNearestCustomScriptAssembly.AssemblyFlags & AssemblyFlags.EditorOnly) == + AssemblyFlags.EditorOnly; + } + + var activeFolderPath = GetActiveFolderPath(); + return activeFolderPath.ToLower().Contains("/editor"); + } + + public static bool CanAddPlayModeTestScriptAndItWillCompile() + { + if (PlayerSettings.playModeTestRunnerEnabled) + { + return true; + } + + var theNearestCustomScriptAssembly = GetTheNearestCustomScriptAssembly(); + + if (theNearestCustomScriptAssembly == null) + { + return false; + } + + var hasTestAssemblyFlag = theNearestCustomScriptAssembly.PrecompiledReferences != null && theNearestCustomScriptAssembly.PrecompiledReferences.Any(x => Path.GetFileName(x) == kNunit);; + var editorOnlyAssembly = (theNearestCustomScriptAssembly.AssemblyFlags & AssemblyFlags.EditorOnly) != 0; + + return hasTestAssemblyFlag && !editorOnlyAssembly; + } + + public static string GetActiveFolderPath() + { + var path = "Assets"; + + foreach (var obj in Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.Assets)) + { + path = AssetDatabase.GetAssetPath(obj); + if (!string.IsNullOrEmpty(path) && File.Exists(path)) + { + path = Path.GetDirectoryName(path); + break; + } + } + return path; + } + + private static CustomScriptAssembly GetTheNearestCustomScriptAssembly() + { + CustomScriptAssembly findCustomScriptAssemblyFromScriptPath; + try + { + findCustomScriptAssemblyFromScriptPath = + EditorCompilationInterface.Instance.FindCustomScriptAssemblyFromScriptPath( + Path.Combine(GetActiveFolderPath(), "Foo.cs")); + } + catch (Exception) + { + return null; + } + return findCustomScriptAssemblyFromScriptPath; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/TestListTreeView/Icons.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/TestListTreeView/Icons.cs new file mode 100644 index 00000000..52c94a51 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/TestListTreeView/Icons.cs @@ -0,0 +1,24 @@ +using UnityEngine; + +namespace UnityEditor.TestTools.TestRunner.GUI +{ + internal static class Icons + { + public static readonly Texture2D s_FailImg; + public static readonly Texture2D s_IgnoreImg; + public static readonly Texture2D s_SuccessImg; + public static readonly Texture2D s_UnknownImg; + public static readonly Texture2D s_InconclusiveImg; + public static readonly Texture2D s_StopwatchImg; + + static Icons() + { + s_FailImg = EditorGUIUtility.IconContent("TestFailed").image as Texture2D; + s_IgnoreImg = EditorGUIUtility.IconContent("TestIgnored").image as Texture2D; + s_SuccessImg = EditorGUIUtility.IconContent("TestPassed").image as Texture2D; + s_UnknownImg = EditorGUIUtility.IconContent("TestNormal").image as Texture2D; + s_InconclusiveImg = EditorGUIUtility.IconContent("TestInconclusive").image as Texture2D; + s_StopwatchImg = EditorGUIUtility.IconContent("TestStopwatch").image as Texture2D; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/TestListTreeView/TestListTreeViewDataSource.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/TestListTreeView/TestListTreeViewDataSource.cs new file mode 100644 index 00000000..04a5e6b7 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/TestListTreeView/TestListTreeViewDataSource.cs @@ -0,0 +1,93 @@ +using System.Collections.Generic; +using UnityEditor.IMGUI.Controls; +using UnityEditor.TestTools.TestRunner.Api; +using UnityEngine.SceneManagement; +using UnityEngine.TestTools.TestRunner; +using UnityEngine.TestTools.TestRunner.GUI; + +namespace UnityEditor.TestTools.TestRunner.GUI +{ + internal class TestListTreeViewDataSource : TreeViewDataSource + { + private bool m_ExpandTreeOnCreation; + private readonly TestListGUI m_TestListGUI; + private ITestAdaptor m_RootTest; + + public TestListTreeViewDataSource(TreeViewController testListTree, TestListGUI testListGUI, ITestAdaptor rootTest) : base(testListTree) + { + showRootItem = false; + rootIsCollapsable = false; + m_TestListGUI = testListGUI; + m_RootTest = rootTest; + } + + public override void FetchData() + { + var sceneName = SceneManager.GetActiveScene().name; + if (sceneName.StartsWith("InitTestScene")) + sceneName = PlaymodeTestsController.GetController().settings.originalScene; + + var testListBuilder = new TestTreeViewBuilder(m_RootTest, m_TestListGUI.newResultList, m_TestListGUI.m_TestRunnerUIFilter); + + m_RootItem = testListBuilder.BuildTreeView(null, false, sceneName); + SetExpanded(m_RootItem, true); + if (m_RootItem.hasChildren && m_RootItem.children.Count == 1) + SetExpanded(m_RootItem.children[0], true); + + if (m_ExpandTreeOnCreation) + SetExpandedWithChildren(m_RootItem, true); + + m_TestListGUI.newResultList = new List(testListBuilder.results); + m_TestListGUI.m_TestRunnerUIFilter.availableCategories = testListBuilder.AvailableCategories; + m_NeedRefreshRows = true; + } + + public override bool IsRenamingItemAllowed(TreeViewItem item) + { + return false; + } + + public void ExpandTreeOnCreation() + { + m_ExpandTreeOnCreation = true; + } + + public override bool IsExpandable(TreeViewItem item) + { + if (item is TestTreeViewItem) + return ((TestTreeViewItem)item).IsGroupNode; + return base.IsExpandable(item); + } + + protected override List Search(TreeViewItem rootItem, string search) + { + var result = new List(); + + if (rootItem.hasChildren) + { + foreach (var child in rootItem.children) + { + SearchTestTree(child, search, result); + } + } + return result; + } + + protected void SearchTestTree(TreeViewItem item, string search, IList searchResult) + { + var testItem = item as TestTreeViewItem; + if (!testItem.IsGroupNode) + { + if (testItem.FullName.ToLower().Contains(search)) + { + searchResult.Add(item); + } + } + else if (item.children != null) + { + foreach (var child in item.children) + SearchTestTree(child, search, searchResult); + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/TestListTreeView/TestListTreeViewGUI.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/TestListTreeView/TestListTreeViewGUI.cs new file mode 100644 index 00000000..66578130 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/TestListTreeView/TestListTreeViewGUI.cs @@ -0,0 +1,11 @@ +using UnityEditor.IMGUI.Controls; + +namespace UnityEditor.TestTools.TestRunner.GUI +{ + internal class TestListTreeViewGUI : TreeViewGUI + { + public TestListTreeViewGUI(TreeViewController testListTree) : base(testListTree) + { + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/TestListTreeView/TestTreeViewItem.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/TestListTreeView/TestTreeViewItem.cs new file mode 100644 index 00000000..8d99de95 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/TestListTreeView/TestTreeViewItem.cs @@ -0,0 +1,118 @@ +using System; +using System.Reflection; +using System.Text; +using UnityEditor.IMGUI.Controls; +using UnityEditor.TestTools.TestRunner.Api; +using UnityEngine.TestTools.TestRunner.GUI; + +namespace UnityEditor.TestTools.TestRunner.GUI +{ + internal sealed class TestTreeViewItem : TreeViewItem + { + public TestRunnerResult result; + internal ITestAdaptor m_Test; + + public Type type; + public MethodInfo method; + + private const int k_ResultTestMaxLength = 15000; + + public bool IsGroupNode { get { return m_Test.IsSuite; } } + + public string FullName { get { return m_Test.FullName; } } + + public TestTreeViewItem(ITestAdaptor test, int depth, TreeViewItem parent) + : base(GetId(test), depth, parent, test.Name) + { + m_Test = test; + + if (test.TypeInfo != null) + { + type = test.TypeInfo.Type; + } + if (test.Method != null) + { + method = test.Method.MethodInfo; + } + + displayName = test.Name.Replace("\n", ""); + icon = Icons.s_UnknownImg; + } + + private static int GetId(ITestAdaptor test) + { + return test.UniqueName.GetHashCode(); + } + + public void SetResult(TestRunnerResult testResult) + { + result = testResult; + result.SetResultChangedCallback(ResultUpdated); + ResultUpdated(result); + } + + public string GetResultText() + { + var durationString = String.Format("{0:0.000}", result.duration); + var sb = new StringBuilder(string.Format("{0} ({1}s)", displayName.Trim(), durationString)); + if (!string.IsNullOrEmpty(result.description)) + { + sb.AppendFormat("\n{0}", result.description); + } + if (!string.IsNullOrEmpty(result.messages)) + { + sb.Append("\n---\n"); + sb.Append(result.messages.Trim()); + } + if (!string.IsNullOrEmpty(result.stacktrace)) + { + sb.Append("\n---\n"); + sb.Append(result.stacktrace.Trim()); + } + if (!string.IsNullOrEmpty(result.output)) + { + sb.Append("\n---\n"); + sb.Append(result.output.Trim()); + } + if (sb.Length > k_ResultTestMaxLength) + { + sb.Length = k_ResultTestMaxLength; + sb.AppendFormat("...\n\n---MESSAGE TRUNCATED AT {0} CHARACTERS---", k_ResultTestMaxLength); + } + return sb.ToString().Trim(); + } + + private void ResultUpdated(TestRunnerResult testResult) + { + switch (testResult.resultStatus) + { + case TestRunnerResult.ResultStatus.Passed: + icon = Icons.s_SuccessImg; + break; + case TestRunnerResult.ResultStatus.Failed: + icon = Icons.s_FailImg; + break; + case TestRunnerResult.ResultStatus.Inconclusive: + icon = Icons.s_InconclusiveImg; + break; + case TestRunnerResult.ResultStatus.Skipped: + icon = Icons.s_IgnoreImg; + break; + default: + if (testResult.ignoredOrSkipped) + { + icon = Icons.s_IgnoreImg; + } + else if (testResult.notRunnable) + { + icon = Icons.s_FailImg; + } + else + { + icon = Icons.s_UnknownImg; + } + break; + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/TestRunnerResult.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/TestRunnerResult.cs new file mode 100644 index 00000000..b70d0ab5 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/TestRunnerResult.cs @@ -0,0 +1,149 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEditor.TestTools.TestRunner.Api; +using UnityEngine.TestTools.TestRunner.GUI; + +namespace UnityEditor.TestTools.TestRunner.GUI +{ + [Serializable] + internal class TestRunnerResult : TestRunnerFilter.IClearableResult + { + public string id; + public string uniqueId; + public string name; + public string fullName; + public ResultStatus resultStatus = ResultStatus.NotRun; + public float duration; + public string messages; + public string output; + public string stacktrace; + public bool notRunnable; + public bool ignoredOrSkipped; + public string description; + public bool isSuite; + public List categories; + public string parentId; + public string parentUniqueId; + + //This field is suppose to mark results from before domain reload + //Such result is outdated because the code might haev changed + //This field will get reset every time a domain reload happens + [NonSerialized] + public bool notOutdated; + + protected Action m_OnResultUpdate; + + internal TestRunnerResult(ITestAdaptor test) + { + id = test.Id; + uniqueId = test.UniqueName; + + fullName = test.FullName; + name = test.Name; + description = test.Description; + isSuite = test.IsSuite; + + ignoredOrSkipped = test.RunState == RunState.Ignored || test.RunState == RunState.Skipped; + notRunnable = test.RunState == RunState.NotRunnable; + + if (ignoredOrSkipped) + { + messages = test.SkipReason; + } + if (notRunnable) + { + resultStatus = ResultStatus.Failed; + messages = test.SkipReason; + } + categories = test.Categories.ToList(); + parentId = test.ParentId; + parentUniqueId = test.ParentUniqueName; + } + + internal TestRunnerResult(ITestResultAdaptor testResult) : this(testResult.Test) + { + notOutdated = true; + + messages = testResult.Message; + output = testResult.Output; + stacktrace = testResult.StackTrace; + duration = (float)testResult.Duration; + if (testResult.Test.IsSuite && testResult.ResultState == "Ignored") + { + resultStatus = ResultStatus.Passed; + } + else + { + resultStatus = ParseNUnitResultStatus(testResult.TestStatus); + } + } + + public void Update(TestRunnerResult result) + { + if (ReferenceEquals(result, null)) + return; + resultStatus = result.resultStatus; + duration = result.duration; + messages = result.messages; + output = result.output; + stacktrace = result.stacktrace; + ignoredOrSkipped = result.ignoredOrSkipped; + notRunnable = result.notRunnable; + description = result.description; + notOutdated = result.notOutdated; + if (m_OnResultUpdate != null) + m_OnResultUpdate(this); + } + + public void SetResultChangedCallback(Action resultUpdated) + { + m_OnResultUpdate = resultUpdated; + } + + [Serializable] + internal enum ResultStatus + { + NotRun, + Passed, + Failed, + Inconclusive, + Skipped + } + + private static ResultStatus ParseNUnitResultStatus(TestStatus status) + { + switch (status) + { + case TestStatus.Passed: + return ResultStatus.Passed; + case TestStatus.Failed: + return ResultStatus.Failed; + case TestStatus.Inconclusive: + return ResultStatus.Inconclusive; + case TestStatus.Skipped: + return ResultStatus.Skipped; + default: + return ResultStatus.NotRun; + } + } + + public override string ToString() + { + return string.Format("{0} ({1})", name, fullName); + } + + public string Id { get { return uniqueId; } } + public string FullName { get { return fullName; } } + public string ParentId { get { return parentUniqueId; } } + public bool IsSuite { get { return isSuite; } } + public List Categories { get { return categories; } } + + public void Clear() + { + resultStatus = ResultStatus.NotRun; + if (m_OnResultUpdate != null) + m_OnResultUpdate(this); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/TestRunnerUIFilter.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/TestRunnerUIFilter.cs new file mode 100644 index 00000000..a9df8e64 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/TestRunnerUIFilter.cs @@ -0,0 +1,167 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +using UnityEngine.TestTools.TestRunner.GUI; + +namespace UnityEditor.TestTools.TestRunner.GUI +{ + [Serializable] + internal class TestRunnerUIFilter + { + private int m_PassedCount; + private int m_FailedCount; + private int m_NotRunCount; + private int m_InconclusiveCount; + private int m_SkippedCount; + + public int PassedCount { get { return m_PassedCount; } } + public int FailedCount { get { return m_FailedCount + m_InconclusiveCount; } } + public int NotRunCount { get { return m_NotRunCount + m_SkippedCount; } } + + [SerializeField] + public bool PassedHidden; + [SerializeField] + public bool FailedHidden; + [SerializeField] + public bool NotRunHidden; + + [SerializeField] + private string m_SearchString; + [SerializeField] + private int selectedCategoryMask; + + public string[] availableCategories = new string[0]; + + + private GUIContent m_SucceededBtn; + private GUIContent m_FailedBtn; + private GUIContent m_NotRunBtn; + + public Action RebuildTestList; + public Action SearchStringChanged; + public bool IsFiltering + { + get + { + return !string.IsNullOrEmpty(m_SearchString) || PassedHidden || FailedHidden || NotRunHidden || + selectedCategoryMask != 0; + } + } + + public string[] CategoryFilter + { + get + { + var list = new List(); + for (int i = 0; i < availableCategories.Length; i++) + { + if ((selectedCategoryMask & (1 << i)) != 0) + { + list.Add(availableCategories[i]); + } + } + return list.ToArray(); + } + } + + public void UpdateCounters(List resultList) + { + m_PassedCount = m_FailedCount = m_NotRunCount = m_InconclusiveCount = m_SkippedCount = 0; + foreach (var result in resultList) + { + if (result.isSuite) + continue; + switch (result.resultStatus) + { + case TestRunnerResult.ResultStatus.Passed: + m_PassedCount++; + break; + case TestRunnerResult.ResultStatus.Failed: + m_FailedCount++; + break; + case TestRunnerResult.ResultStatus.Inconclusive: + m_InconclusiveCount++; + break; + case TestRunnerResult.ResultStatus.Skipped: + m_SkippedCount++; + break; + case TestRunnerResult.ResultStatus.NotRun: + default: + m_NotRunCount++; + break; + } + } + + var succeededTooltip = string.Format("Show tests that succeeded\n{0} succeeded", m_PassedCount); + m_SucceededBtn = new GUIContent(PassedCount.ToString(), Icons.s_SuccessImg, succeededTooltip); + var failedTooltip = string.Format("Show tests that failed\n{0} failed\n{1} inconclusive", m_FailedCount, m_InconclusiveCount); + m_FailedBtn = new GUIContent(FailedCount.ToString(), Icons.s_FailImg, failedTooltip); + var notRunTooltip = string.Format("Show tests that didn't run\n{0} didn't run\n{1} skipped or ignored", m_NotRunCount, m_SkippedCount); + m_NotRunBtn = new GUIContent(NotRunCount.ToString(), Icons.s_UnknownImg, notRunTooltip); + } + + public void Draw() + { + EditorGUI.BeginChangeCheck(); + m_SearchString = EditorGUILayout.ToolbarSearchField(m_SearchString); + if (EditorGUI.EndChangeCheck() && SearchStringChanged != null) + { + SearchStringChanged(m_SearchString); + } + + if (availableCategories != null && availableCategories.Any()) + { + EditorGUI.BeginChangeCheck(); + selectedCategoryMask = EditorGUILayout.MaskField(selectedCategoryMask, availableCategories, EditorStyles.toolbarDropDown, GUILayout.MaxWidth(150)); + if (EditorGUI.EndChangeCheck() && RebuildTestList != null) + { + RebuildTestList(); + } + } + else + { + EditorGUILayout.Popup(0, new[] { "" }, EditorStyles.toolbarDropDown, GUILayout.MaxWidth(150)); + } + + EditorGUI.BeginChangeCheck(); + if (m_SucceededBtn != null) + { + PassedHidden = !GUILayout.Toggle(!PassedHidden, m_SucceededBtn, EditorStyles.toolbarButton, GUILayout.MaxWidth(GetMaxWidth(PassedCount))); + } + if (m_FailedBtn != null) + { + FailedHidden = !GUILayout.Toggle(!FailedHidden, m_FailedBtn, EditorStyles.toolbarButton, GUILayout.MaxWidth(GetMaxWidth(FailedCount))); + } + if (m_NotRunBtn != null) + { + NotRunHidden = !GUILayout.Toggle(!NotRunHidden, m_NotRunBtn, EditorStyles.toolbarButton, GUILayout.MaxWidth(GetMaxWidth(NotRunCount))); + } + + if (EditorGUI.EndChangeCheck() && RebuildTestList != null) + { + RebuildTestList(); + } + } + + private static int GetMaxWidth(int count) + { + if (count < 10) + return 33; + return count < 100 ? 40 : 47; + } + + public void Clear() + { + PassedHidden = false; + FailedHidden = false; + NotRunHidden = false; + selectedCategoryMask = 0; + m_SearchString = ""; + if (SearchStringChanged != null) + { + SearchStringChanged(m_SearchString); + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/Views/EditModeTestListGUI.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/Views/EditModeTestListGUI.cs new file mode 100644 index 00000000..3de12539 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/Views/EditModeTestListGUI.cs @@ -0,0 +1,88 @@ +using System; +using System.Linq; +using UnityEditor.TestTools.TestRunner.Api; +using UnityEngine; +using UnityEngine.TestTools; +using UnityEngine.TestTools.TestRunner.GUI; + +namespace UnityEditor.TestTools.TestRunner.GUI +{ + [Serializable] + internal class EditModeTestListGUI : TestListGUI + { + public override TestMode TestMode + { + get { return TestMode.EditMode; } + } + + public override void RenderNoTestsInfo() + { + if (!TestListGUIHelper.SelectedFolderContainsTestAssembly()) + { + var noTestText = "No tests to show"; + + if (!PlayerSettings.playModeTestRunnerEnabled) + { + const string testsArePulledFromCustomAssemblies = + "EditMode tests can be in Editor only Assemblies, either in the editor special folder or Editor only Assembly Definitions with added Unity References \"Test Assemblies\"."; + noTestText += Environment.NewLine + testsArePulledFromCustomAssemblies; + } + + EditorGUILayout.HelpBox(noTestText, MessageType.Info); + if (GUILayout.Button("Create EditMode Test Assembly Folder")) + { + TestListGUIHelper.AddFolderAndAsmDefForTesting(isEditorOnly: true); + } + } + + if (!TestListGUIHelper.CanAddEditModeTestScriptAndItWillCompile()) + { + UnityEngine.GUI.enabled = false; + EditorGUILayout.HelpBox("EditMode test scripts can only be created in editor test assemblies.", MessageType.Warning); + } + if (GUILayout.Button("Create Test Script in current folder")) + { + TestListGUIHelper.AddTest(); + } + UnityEngine.GUI.enabled = true; + } + + public override void PrintHeadPanel() + { + base.PrintHeadPanel(); + DrawFilters(); + } + + protected override void RunTests(TestRunnerFilter filter) + { + if (EditorUtility.scriptCompilationFailed) + { + Debug.LogError("Fix compilation issues before running tests"); + return; + } + + filter.ClearResults(newResultList.OfType().ToList()); + + RerunCallbackData.instance.runFilter = filter; + RerunCallbackData.instance.testMode = TestMode.EditMode; + + var testRunnerApi = ScriptableObject.CreateInstance(); + testRunnerApi.Execute(new ExecutionSettings() + { + filter = new Filter() + { + categoryNames = filter.categoryNames, + groupNames = filter.groupNames, + testMode = TestMode, + testNames = filter.testNames + } + }); + } + + public override TestPlatform TestPlatform { get { return TestPlatform.EditMode; } } + protected override bool IsBusy() + { + return EditModeLauncher.IsRunning || EditorApplication.isCompiling || EditorApplication.isPlaying; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/Views/PlayModeTestListGUI.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/Views/PlayModeTestListGUI.cs new file mode 100644 index 00000000..40e3d2d5 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/Views/PlayModeTestListGUI.cs @@ -0,0 +1,106 @@ +using System; +using System.Linq; +using UnityEditor.SceneManagement; +using UnityEditor.TestTools.TestRunner.Api; +using UnityEngine; +using UnityEngine.TestTools; +using UnityEngine.SceneManagement; +using UnityEngine.TestTools.TestRunner; +using UnityEngine.TestTools.TestRunner.GUI; + +namespace UnityEditor.TestTools.TestRunner.GUI +{ + [Serializable] + internal class PlayModeTestListGUI : TestListGUI + { + public override TestMode TestMode + { + get { return TestMode.PlayMode; } + } + public override void PrintHeadPanel() + { + EditorGUILayout.BeginHorizontal(GUILayout.ExpandHeight(false)); + base.PrintHeadPanel(); + if (GUILayout.Button("Run all in player (" + EditorUserBuildSettings.activeBuildTarget + ")", EditorStyles.toolbarButton)) + { + RunTestsInPlayer(null); + } + EditorGUILayout.EndHorizontal(); + DrawFilters(); + EditorGUILayout.BeginHorizontal(GUILayout.ExpandHeight(false)); + EditorGUILayout.EndHorizontal(); + } + + public override void RenderNoTestsInfo() + { + if (!TestListGUIHelper.SelectedFolderContainsTestAssembly()) + { + var noTestText = "No tests to show"; + if (!PlayerSettings.playModeTestRunnerEnabled) + { + const string testsArePulledFromCustomAssemblues = "Test Assemblies are defined by Assembly Definitions where you add Unity References \"Test Assemblies\""; + const string infoTextAboutTestsInAllAssemblies = + "To have tests in all assemblies enable it in the Test Runner window context menu"; + noTestText += Environment.NewLine + testsArePulledFromCustomAssemblues + Environment.NewLine + + infoTextAboutTestsInAllAssemblies; + } + + EditorGUILayout.HelpBox(noTestText, MessageType.Info); + if (GUILayout.Button("Create PlayMode Test Assembly Folder")) + { + TestListGUIHelper.AddFolderAndAsmDefForTesting(); + } + } + + if (!TestListGUIHelper.CanAddPlayModeTestScriptAndItWillCompile()) + { + UnityEngine.GUI.enabled = false; + EditorGUILayout.HelpBox("PlayMode test scripts can only be created in non editor test assemblies.", MessageType.Warning); + } + if (GUILayout.Button("Create Test Script in current folder")) + { + TestListGUIHelper.AddTest(); + } + UnityEngine.GUI.enabled = true; + } + + protected override void RunTests(TestRunnerFilter filter) + { + // Give user chance to save the changes to their currently open scene because we close it and load our own + var cancelled = !EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo(); + if (cancelled) + return; + + filter.ClearResults(newResultList.OfType().ToList()); + + RerunCallbackData.instance.runFilter = filter; + RerunCallbackData.instance.testMode = TestMode.PlayMode; + + var testRunnerApi = ScriptableObject.CreateInstance(); + testRunnerApi.Execute(new ExecutionSettings() + { + filter = new Filter() + { + categoryNames = filter.categoryNames, + groupNames = filter.groupNames, + testMode = TestMode, + testNames = filter.testNames + } + }); + } + + protected void RunTestsInPlayer(TestRunnerFilter filter) + { + var settings = PlaymodeTestsControllerSettings.CreateRunnerSettings(filter); + var testExecutor = new PlayerLauncher(settings, null, null); + testExecutor.Run(); + GUIUtility.ExitGUI(); + } + + public override TestPlatform TestPlatform { get { return TestPlatform.PlayMode; } } + protected override bool IsBusy() + { + return PlaymodeLauncher.IsRunning || EditorApplication.isCompiling || EditorApplication.isPlaying; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/Views/TestListGUIBase.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/Views/TestListGUIBase.cs new file mode 100644 index 00000000..27c4d3fa --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/GUI/Views/TestListGUIBase.cs @@ -0,0 +1,449 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEditor.IMGUI.Controls; +using UnityEditor.TestTools.TestRunner.Api; +using UnityEngine; +using UnityEngine.TestTools.TestRunner.GUI; +using UnityEngine.TestTools; + +namespace UnityEditor.TestTools.TestRunner.GUI +{ + internal abstract class TestListGUI + { + private static readonly GUIContent s_GUIRunSelectedTests = EditorGUIUtility.TrTextContent("Run Selected", "Run selected test(s)"); + private static readonly GUIContent s_GUIRunAllTests = EditorGUIUtility.TrTextContent("Run All", "Run all tests"); + private static readonly GUIContent s_GUIRerunFailedTests = EditorGUIUtility.TrTextContent("Rerun Failed", "Rerun all failed tests"); + private static readonly GUIContent s_GUIRun = EditorGUIUtility.TrTextContent("Run"); + private static readonly GUIContent s_GUIRunUntilFailed = EditorGUIUtility.TrTextContent("Run Until Failed"); + private static readonly GUIContent s_GUIRun100Times = EditorGUIUtility.TrTextContent("Run 100 times"); + private static readonly GUIContent s_GUIOpenTest = EditorGUIUtility.TrTextContent("Open source code"); + private static readonly GUIContent s_GUIOpenErrorLine = EditorGUIUtility.TrTextContent("Open error line"); + + [SerializeField] + protected TestRunnerWindow m_Window; + [SerializeField] + public List newResultList = new List(); + [SerializeField] + private string m_ResultText; + [SerializeField] + private string m_ResultStacktrace; + + private TreeViewController m_TestListTree; + [SerializeField] + internal TreeViewState m_TestListState; + [SerializeField] + internal TestRunnerUIFilter m_TestRunnerUIFilter = new TestRunnerUIFilter(); + + private Vector2 m_TestInfoScroll, m_TestListScroll; + private string m_PreviousProjectPath; + private List m_QueuedResults = new List(); + + protected TestListGUI() + { + MonoCecilHelper = new MonoCecilHelper(); + AssetsDatabaseHelper = new AssetsDatabaseHelper(); + + GuiHelper = new GuiHelper(MonoCecilHelper, AssetsDatabaseHelper); + } + + protected IMonoCecilHelper MonoCecilHelper { get; private set; } + protected IAssetsDatabaseHelper AssetsDatabaseHelper { get; private set; } + protected IGuiHelper GuiHelper { get; private set; } + + public abstract TestMode TestMode { get; } + + public virtual void PrintHeadPanel() + { + EditorGUILayout.BeginHorizontal(EditorStyles.toolbar); + using (new EditorGUI.DisabledScope(IsBusy())) + { + if (GUILayout.Button(s_GUIRunAllTests, EditorStyles.toolbarButton)) + { + var filter = new TestRunnerFilter {categoryNames = m_TestRunnerUIFilter.CategoryFilter}; + RunTests(filter); + GUIUtility.ExitGUI(); + } + } + using (new EditorGUI.DisabledScope(m_TestListTree == null || !m_TestListTree.HasSelection() || IsBusy())) + { + if (GUILayout.Button(s_GUIRunSelectedTests, EditorStyles.toolbarButton)) + { + RunTests(GetSelectedTestsAsFilter(m_TestListTree.GetSelection())); + GUIUtility.ExitGUI(); + } + } + using (new EditorGUI.DisabledScope(m_TestRunnerUIFilter.FailedCount == 0 || IsBusy())) + { + if (GUILayout.Button(s_GUIRerunFailedTests, EditorStyles.toolbarButton)) + { + var failedTestnames = new List(); + foreach (var result in newResultList) + { + if (result.isSuite) + continue; + if (result.resultStatus == TestRunnerResult.ResultStatus.Failed || + result.resultStatus == TestRunnerResult.ResultStatus.Inconclusive) + failedTestnames.Add(result.fullName); + } + RunTests(new TestRunnerFilter() {testNames = failedTestnames.ToArray(), categoryNames = m_TestRunnerUIFilter.CategoryFilter}); + GUIUtility.ExitGUI(); + } + } + GUILayout.FlexibleSpace(); + EditorGUILayout.EndHorizontal(); + } + + protected void DrawFilters() + { + EditorGUILayout.BeginHorizontal(EditorStyles.toolbar); + m_TestRunnerUIFilter.Draw(); + EditorGUILayout.EndHorizontal(); + } + + public bool HasTreeData() + { + return m_TestListTree != null; + } + + public virtual void RenderTestList() + { + if (m_TestListTree == null) + { + GUILayout.Label("Loading..."); + return; + } + + m_TestListScroll = EditorGUILayout.BeginScrollView(m_TestListScroll, + GUILayout.ExpandWidth(true), + GUILayout.MaxWidth(2000)); + + if (m_TestListTree.data.root == null || m_TestListTree.data.rowCount == 0 || (!m_TestListTree.isSearching && !m_TestListTree.data.GetItem(0).hasChildren)) + { + if (m_TestRunnerUIFilter.IsFiltering) + { + if (GUILayout.Button("Clear filters")) + { + m_TestRunnerUIFilter.Clear(); + m_TestListTree.ReloadData(); + m_Window.Repaint(); + } + } + RenderNoTestsInfo(); + } + else + { + var treeRect = EditorGUILayout.GetControlRect(GUILayout.ExpandHeight(true), GUILayout.ExpandWidth(true)); + var treeViewKeyboardControlId = GUIUtility.GetControlID(FocusType.Keyboard); + + m_TestListTree.OnGUI(treeRect, treeViewKeyboardControlId); + } + + EditorGUILayout.EndScrollView(); + } + + public virtual void RenderNoTestsInfo() + { + EditorGUILayout.HelpBox("No tests to show", MessageType.Info); + } + + public void RenderDetails() + { + m_TestInfoScroll = EditorGUILayout.BeginScrollView(m_TestInfoScroll); + var resultTextSize = TestRunnerWindow.Styles.info.CalcSize(new GUIContent(m_ResultText)); + EditorGUILayout.SelectableLabel(m_ResultText, TestRunnerWindow.Styles.info, + GUILayout.ExpandHeight(true), + GUILayout.ExpandWidth(true), + GUILayout.MinWidth(resultTextSize.x), + GUILayout.MinHeight(resultTextSize.y)); + EditorGUILayout.EndScrollView(); + } + + public void Reload() + { + if (m_TestListTree != null) + { + m_TestListTree.ReloadData(); + UpdateQueuedResults(); + } + } + + public void Repaint() + { + if (m_TestListTree == null || m_TestListTree.data.root == null) + { + return; + } + + m_TestListTree.Repaint(); + if (m_TestListTree.data.rowCount == 0) + m_TestListTree.SetSelection(new int[0], false); + TestSelectionCallback(m_TestListState.selectedIDs.ToArray()); + } + + public void Init(TestRunnerWindow window, ITestAdaptor rootTest) + { + if (m_Window == null) + { + m_Window = window; + } + + if (m_TestListTree == null) + { + if (m_TestListState == null) + { + m_TestListState = new TreeViewState(); + } + if (m_TestListTree == null) + m_TestListTree = new TreeViewController(m_Window, m_TestListState); + + m_TestListTree.deselectOnUnhandledMouseDown = false; + + m_TestListTree.selectionChangedCallback += TestSelectionCallback; + m_TestListTree.itemDoubleClickedCallback += TestDoubleClickCallback; + m_TestListTree.contextClickItemCallback += TestContextClickCallback; + + var testListTreeViewDataSource = new TestListTreeViewDataSource(m_TestListTree, this, rootTest); + + if (!newResultList.Any()) + testListTreeViewDataSource.ExpandTreeOnCreation(); + + m_TestListTree.Init(new Rect(), + testListTreeViewDataSource, + new TestListTreeViewGUI(m_TestListTree), + null); + } + + EditorApplication.update += RepaintIfProjectPathChanged; + + m_TestRunnerUIFilter.UpdateCounters(newResultList); + m_TestRunnerUIFilter.RebuildTestList = () => m_TestListTree.ReloadData(); + m_TestRunnerUIFilter.SearchStringChanged = s => m_TestListTree.searchString = s; + } + + public void UpdateResult(TestRunnerResult result) + { + if (!HasTreeData()) + { + m_QueuedResults.Add(result); + return; + } + + if (newResultList.All(x => x.uniqueId != result.uniqueId)) + { + return; + } + + var testRunnerResult = newResultList.FirstOrDefault(x => x.uniqueId == result.uniqueId); + if (testRunnerResult != null) + { + testRunnerResult.Update(result); + } + + Repaint(); + m_Window.Repaint(); + } + + private void UpdateQueuedResults() + { + foreach (var testRunnerResult in m_QueuedResults) + { + var existingResult = newResultList.FirstOrDefault(x => x.uniqueId == testRunnerResult.uniqueId); + if (existingResult != null) + { + existingResult.Update(testRunnerResult); + } + } + m_QueuedResults.Clear(); + TestSelectionCallback(m_TestListState.selectedIDs.ToArray()); + Repaint(); + m_Window.Repaint(); + } + + internal void TestSelectionCallback(int[] selected) + { + if (m_TestListTree != null && selected.Length == 1) + { + if (m_TestListTree != null) + { + var node = m_TestListTree.FindItem(selected[0]); + if (node is TestTreeViewItem) + { + var test = node as TestTreeViewItem; + m_ResultText = test.GetResultText(); + m_ResultStacktrace = test.result.stacktrace; + } + } + } + else if (selected.Length == 0) + { + m_ResultText = ""; + } + } + + protected virtual void TestDoubleClickCallback(int id) + { + if (IsBusy()) + return; + + RunTests(GetSelectedTestsAsFilter(new List { id })); + GUIUtility.ExitGUI(); + } + + protected virtual void RunTests(TestRunnerFilter filter) + { + throw new NotImplementedException(); + } + + protected virtual void TestContextClickCallback(int id) + { + if (id == 0) + return; + + var m = new GenericMenu(); + var testFilter = GetSelectedTestsAsFilter(m_TestListState.selectedIDs); + var multilineSelection = m_TestListState.selectedIDs.Count > 1; + + if (!multilineSelection) + { + var testNode = GetSelectedTest(); + var isNotSuite = !testNode.IsGroupNode; + if (isNotSuite) + { + if (!string.IsNullOrEmpty(m_ResultStacktrace)) + { + m.AddItem(s_GUIOpenErrorLine, + false, + data => + { + if (!GuiHelper.OpenScriptInExternalEditor(m_ResultStacktrace)) + { + GuiHelper.OpenScriptInExternalEditor(testNode.type, testNode.method); + } + }, + ""); + } + + m.AddItem(s_GUIOpenTest, + false, + data => GuiHelper.OpenScriptInExternalEditor(testNode.type, testNode.method), + ""); + m.AddSeparator(""); + } + } + + if (!IsBusy()) + { + m.AddItem(multilineSelection ? s_GUIRunSelectedTests : s_GUIRun, + false, + data => RunTests(testFilter), + ""); + + if (EditorPrefs.GetBool("DeveloperMode", false)) + { + m.AddItem(multilineSelection ? s_GUIRunSelectedTests : s_GUIRunUntilFailed, + false, + data => + { + testFilter.testRepetitions = int.MaxValue; + RunTests(testFilter); + }, + ""); + + m.AddItem(multilineSelection ? s_GUIRunSelectedTests : s_GUIRun100Times, + false, + data => + { + testFilter.testRepetitions = 100; + RunTests(testFilter); + }, + ""); + } + } + else + m.AddDisabledItem(multilineSelection ? s_GUIRunSelectedTests : s_GUIRun, false); + + m.ShowAsContext(); + } + + private TestRunnerFilter GetSelectedTestsAsFilter(IEnumerable selectedIDs) + { + var namesToRun = new List(); + var exactNamesToRun = new List(); + var assembliesToRun = new List(); + foreach (var lineId in selectedIDs) + { + var line = m_TestListTree.FindItem(lineId); + if (line is TestTreeViewItem) + { + var testLine = line as TestTreeViewItem; + if (testLine.IsGroupNode && !testLine.FullName.Contains("+")) + { + if (testLine.parent != null && testLine.parent.displayName == "Invisible Root Item") + { + //Root node selected. Use an empty TestRunnerFilter to run every test + namesToRun.Clear(); + exactNamesToRun.Clear(); + assembliesToRun.Clear(); + break; + } + + if (testLine.FullName.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) + assembliesToRun.Add(TestRunnerFilter.AssemblyNameFromPath(testLine.FullName)); + else + namesToRun.Add(string.Format("^{0}$", testLine.FullName)); + } + else + exactNamesToRun.Add(testLine.FullName); + } + } + + var filter = new TestRunnerFilter + { + assemblyNames = assembliesToRun.ToArray(), + groupNames = namesToRun.ToArray(), + testNames = exactNamesToRun.ToArray(), + categoryNames = m_TestRunnerUIFilter.CategoryFilter + }; + return filter; + } + + private TestTreeViewItem GetSelectedTest() + { + foreach (var lineId in m_TestListState.selectedIDs) + { + var line = m_TestListTree.FindItem(lineId); + if (line is TestTreeViewItem) + { + return line as TestTreeViewItem; + } + } + return null; + } + + public abstract TestPlatform TestPlatform { get; } + + public void RebuildUIFilter() + { + m_TestRunnerUIFilter.UpdateCounters(newResultList); + if (m_TestRunnerUIFilter.IsFiltering) + { + m_TestListTree.ReloadData(); + } + } + + public void RepaintIfProjectPathChanged() + { + var path = TestListGUIHelper.GetActiveFolderPath(); + if (path != m_PreviousProjectPath) + { + m_PreviousProjectPath = path; + TestRunnerWindow.s_Instance.Repaint(); + } + + EditorApplication.update -= RepaintIfProjectPathChanged; + } + + protected abstract bool IsBusy(); + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/NUnitExtension/Attributes/AssetPipelineIgnore.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/NUnitExtension/Attributes/AssetPipelineIgnore.cs new file mode 100644 index 00000000..e71b62c9 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/NUnitExtension/Attributes/AssetPipelineIgnore.cs @@ -0,0 +1,63 @@ +using System; +using NUnit.Framework; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; + +namespace UnityEditor.TestTools +{ + /// + /// Ignore attributes dedicated to Asset Import Pipeline backend version handling. + /// + internal static class AssetPipelineIgnore + { + internal enum AssetPipelineBackend + { + V1, + V2 + } + + /// + /// Ignore the test when running with the legacy Asset Import Pipeline V1 backend. + /// + internal class IgnoreInV1 : AssetPipelineIgnoreAttribute + { + public IgnoreInV1(string ignoreReason) : base(AssetPipelineBackend.V1, ignoreReason) {} + } + + /// + /// Ignore the test when running with the latest Asset Import Pipeline V2 backend. + /// + internal class IgnoreInV2 : AssetPipelineIgnoreAttribute + { + public IgnoreInV2(string ignoreReason) : base(AssetPipelineBackend.V2, ignoreReason) {} + } + + [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method)] + internal class AssetPipelineIgnoreAttribute : NUnitAttribute, IApplyToTest + { + readonly string m_IgnoreReason; + readonly AssetPipelineBackend m_IgnoredBackend; + static readonly AssetPipelineBackend k_ActiveBackend = AssetDatabase.IsV2Enabled() + ? AssetPipelineBackend.V2 + : AssetPipelineBackend.V1; + + static string ActiveBackendName = Enum.GetName(typeof(AssetPipelineBackend), k_ActiveBackend); + + public AssetPipelineIgnoreAttribute(AssetPipelineBackend backend, string ignoreReason) + { + m_IgnoredBackend = backend; + m_IgnoreReason = ignoreReason; + } + + public void ApplyToTest(Test test) + { + if (k_ActiveBackend == m_IgnoredBackend) + { + test.RunState = RunState.Ignored; + var skipReason = string.Format("Not supported by asset pipeline {0} backend {1}", ActiveBackendName, m_IgnoreReason); + test.Properties.Add(PropertyNames.SkipReason, skipReason); + } + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/NUnitExtension/TestRunnerStateSerializer.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/NUnitExtension/TestRunnerStateSerializer.cs new file mode 100644 index 00000000..a24190e4 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/NUnitExtension/TestRunnerStateSerializer.cs @@ -0,0 +1,162 @@ +using System; +using System.Reflection; +using System.Text; +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.TestRunner.NUnitExtensions.Runner; +using UnityEngine.TestTools.NUnitExtensions; +using UnityEngine.TestTools.Logging; + +namespace UnityEditor.TestTools.TestRunner +{ + [Serializable] + internal class TestRunnerStateSerializer : IStateSerializer + { + private const BindingFlags Flags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy; + + [SerializeField] + private HideFlags m_OriginalHideFlags; + + [SerializeField] + private bool m_ShouldRestore; + + [SerializeField] + private string m_TestObjectTypeName; + + [SerializeField] + private ScriptableObject m_TestObject; + + [SerializeField] + private string m_TestObjectTxt; + + [SerializeField] + private long StartTicks; + + [SerializeField] + private double StartTimeOA; + + [SerializeField] + private string output; + + [SerializeField] + private LogMatch[] m_ExpectedLogs; + + public bool ShouldRestore() + { + return m_ShouldRestore; + } + + public void SaveContext() + { + var currentContext = UnityTestExecutionContext.CurrentContext; + + if (currentContext.TestObject != null) + { + m_TestObjectTypeName = currentContext.TestObject.GetType().AssemblyQualifiedName; + m_TestObject = null; + m_TestObjectTxt = null; + if (currentContext.TestObject is ScriptableObject) + { + m_TestObject = currentContext.TestObject as ScriptableObject; + m_OriginalHideFlags = m_TestObject.hideFlags; + m_TestObject.hideFlags |= HideFlags.DontSave; + } + else + { + m_TestObjectTxt = JsonUtility.ToJson(currentContext.TestObject); + } + } + + output = currentContext.CurrentResult.Output; + StartTicks = currentContext.StartTicks; + StartTimeOA = currentContext.StartTime.ToOADate(); + if (LogScope.HasCurrentLogScope()) + { + m_ExpectedLogs = LogScope.Current.ExpectedLogs.ToArray(); + } + + m_ShouldRestore = true; + } + + public void RestoreContext() + { + var currentContext = UnityTestExecutionContext.CurrentContext; + + var outputProp = currentContext.CurrentResult.GetType().BaseType.GetField("_output", Flags); + (outputProp.GetValue(currentContext.CurrentResult) as StringBuilder).Append(output); + + currentContext.StartTicks = StartTicks; + currentContext.StartTime = DateTime.FromOADate(StartTimeOA); + if (LogScope.HasCurrentLogScope()) + { + LogScope.Current.ExpectedLogs = new Queue(m_ExpectedLogs); + } + + m_ShouldRestore = false; + } + + public bool CanRestoreFromScriptableObject(Type requestedType) + { + if (m_TestObject == null) + { + return false; + } + return m_TestObjectTypeName == requestedType.AssemblyQualifiedName; + } + + public ScriptableObject RestoreScriptableObjectInstance() + { + if (m_TestObject == null) + { + Debug.LogError("No object to restore"); + return null; + } + EditorApplication.playModeStateChanged += OnPlayModeStateChanged; + var temp = m_TestObject; + m_TestObject = null; + m_TestObjectTypeName = null; + return temp; + } + + public bool CanRestoreFromJson(Type requestedType) + { + if (string.IsNullOrEmpty(m_TestObjectTxt)) + { + return false; + } + return m_TestObjectTypeName == requestedType.AssemblyQualifiedName; + } + + public void RestoreClassFromJson(ref object instance) + { + if (string.IsNullOrEmpty(m_TestObjectTxt)) + { + Debug.LogWarning("No JSON representation to restore"); + return; + } + JsonUtility.FromJsonOverwrite(m_TestObjectTxt, instance); + m_TestObjectTxt = null; + m_TestObjectTypeName = null; + } + + private void OnPlayModeStateChanged(PlayModeStateChange state) + { + if (m_TestObject == null) + { + EditorApplication.playModeStateChanged -= OnPlayModeStateChanged; + return; + } + + //We set the DontSave flag here because the ScriptableObject would be nulled right before entering EditMode + if (state == PlayModeStateChange.ExitingPlayMode) + { + m_TestObject.hideFlags |= HideFlags.DontSave; + } + else if (state == PlayModeStateChange.EnteredEditMode) + { + m_TestObject.hideFlags = m_OriginalHideFlags; + EditorApplication.playModeStateChanged -= OnPlayModeStateChanged; + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/RequireApiProfileAttribute.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/RequireApiProfileAttribute.cs new file mode 100644 index 00000000..e99d4524 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/RequireApiProfileAttribute.cs @@ -0,0 +1,32 @@ +using System; +using System.Linq; +using NUnit.Framework; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; + +namespace UnityEditor.TestTools +{ + [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method)] + internal class RequireApiProfileAttribute : NUnitAttribute, IApplyToTest + { + public ApiCompatibilityLevel[] apiProfiles { get; private set; } + + public RequireApiProfileAttribute(params ApiCompatibilityLevel[] apiProfiles) + { + this.apiProfiles = apiProfiles; + } + + void IApplyToTest.ApplyToTest(Test test) + { + test.Properties.Add(PropertyNames.Category, string.Format("ApiProfile({0})", string.Join(", ", apiProfiles.Select(p => p.ToString()).OrderBy(p => p).ToArray()))); + ApiCompatibilityLevel testProfile = PlayerSettings.GetApiCompatibilityLevel(EditorUserBuildSettings.activeBuildTargetGroup); + + if (!apiProfiles.Contains(testProfile)) + { + string skipReason = "Skipping test as it requires a compatible api profile set: " + string.Join(", ", apiProfiles.Select(p => p.ToString()).ToArray()); + test.RunState = RunState.Skipped; + test.Properties.Add(PropertyNames.SkipReason, skipReason); + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/RequirePlatformSupportAttribute.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/RequirePlatformSupportAttribute.cs new file mode 100644 index 00000000..321a0fe0 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/RequirePlatformSupportAttribute.cs @@ -0,0 +1,33 @@ +using System; +using System.Linq; +using NUnit.Framework; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; + +namespace UnityEditor.TestTools +{ + [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method)] + public class RequirePlatformSupportAttribute : NUnitAttribute, IApplyToTest + { + public RequirePlatformSupportAttribute(params BuildTarget[] platforms) + { + this.platforms = platforms; + } + + public BuildTarget[] platforms { get; private set; } + + void IApplyToTest.ApplyToTest(Test test) + { + test.Properties.Add(PropertyNames.Category, string.Format("RequirePlatformSupport({0})", string.Join(", ", platforms.Select(p => p.ToString()).OrderBy(p => p).ToArray()))); + + if (!platforms.All(p => BuildPipeline.IsBuildTargetSupported(BuildTargetGroup.Unknown, p))) + { + var missingPlatforms = platforms.Where(p => !BuildPipeline.IsBuildTargetSupported(BuildTargetGroup.Unknown, p)).Select(p => p.ToString()).ToArray(); + string skipReason = "Test cannot be run as it requires support for the following platforms to be installed: " + string.Join(", ", missingPlatforms); + + test.RunState = RunState.Skipped; + test.Properties.Add(PropertyNames.SkipReason, skipReason); + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestBuildAssemblyFilter.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestBuildAssemblyFilter.cs new file mode 100644 index 00000000..4f0a0413 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestBuildAssemblyFilter.cs @@ -0,0 +1,21 @@ +using System.Linq; +using UnityEditor.Build; + +namespace UnityEditor.TestRunner +{ + internal class TestBuildAssemblyFilter : IFilterBuildAssemblies + { + private const string nunitAssemblyName = "nunit.framework"; + private const string unityTestRunnerAssemblyName = "UnityEngine.TestRunner"; + + public int callbackOrder { get; } + public string[] OnFilterAssemblies(BuildOptions buildOptions, string[] assemblies) + { + if ((buildOptions & BuildOptions.IncludeTestAssemblies) == BuildOptions.IncludeTestAssemblies || PlayerSettings.playModeTestRunnerEnabled) + { + return assemblies; + } + return assemblies.Where(x => !x.Contains(nunitAssemblyName) && !x.Contains(unityTestRunnerAssemblyName)).ToArray(); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/AttributeFinderBase.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/AttributeFinderBase.cs new file mode 100644 index 00000000..0c069e58 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/AttributeFinderBase.cs @@ -0,0 +1,95 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using NUnit.Framework.Interfaces; +using UnityEngine; +using UnityEngine.TestTools; + +namespace UnityEditor.TestTools.TestRunner +{ + internal abstract class AttributeFinderBase + { + public abstract IEnumerable Search(ITest tests, ITestFilter filter, RuntimePlatform testTargetPlatform); + } + + internal abstract class AttributeFinderBase : AttributeFinderBase where T2 : Attribute + { + private readonly Func m_TypeSelector; + protected AttributeFinderBase(Func typeSelector) + { + m_TypeSelector = typeSelector; + } + + public override IEnumerable Search(ITest tests, ITestFilter filter, RuntimePlatform testTargetPlatform) + { + var selectedTests = new List(); + GetMatchingTests(tests, filter, ref selectedTests, testTargetPlatform); + + var result = new List(); + result.AddRange(GetTypesFromPrebuildAttributes(selectedTests)); + result.AddRange(GetTypesFromInterface(selectedTests, testTargetPlatform)); + + return result.Distinct(); + } + + private static void GetMatchingTests(ITest tests, ITestFilter filter, ref List resultList, RuntimePlatform testTargetPlatform) + { + foreach (var test in tests.Tests) + { + if (IsTestEnabledOnPlatform(test, testTargetPlatform)) + { + if (test.IsSuite) + { + GetMatchingTests(test, filter, ref resultList, testTargetPlatform); + } + else + { + if (filter.Pass(test)) + resultList.Add(test); + } + } + } + } + + private static bool IsTestEnabledOnPlatform(ITest test, RuntimePlatform testTargetPlatform) + { + if (test.Method == null) + { + return true; + } + + var attributesFromMethods = test.Method.GetCustomAttributes(true).Select(attribute => attribute); + var attributesFromTypes = test.Method.TypeInfo.GetCustomAttributes(true).Select(attribute => attribute); + + if (!attributesFromMethods.All(a => a.IsPlatformSupported(testTargetPlatform))) + { + return false; + } + + if (!attributesFromTypes.All(a => a.IsPlatformSupported(testTargetPlatform))) + { + return false; + } + + return true; + } + + private IEnumerable GetTypesFromPrebuildAttributes(IEnumerable tests) + { + var attributesFromMethods = tests.SelectMany(t => t.Method.GetCustomAttributes(true).Select(attribute => attribute)); + var attributesFromTypes = tests.SelectMany(t => t.Method.TypeInfo.GetCustomAttributes(true).Select(attribute => attribute)); + + var result = new List(); + result.AddRange(attributesFromMethods); + result.AddRange(attributesFromTypes); + + return result.Select(m_TypeSelector).Where(type => type != null); + } + + private static IEnumerable GetTypesFromInterface(IEnumerable selectedTests, RuntimePlatform testTargetPlatform) + { + var typesWithInterfaces = selectedTests.Where(t => typeof(T1).IsAssignableFrom(t.Method.TypeInfo.Type) && IsTestEnabledOnPlatform(t, testTargetPlatform)); + return typesWithInterfaces.Select(t => t.Method.TypeInfo.Type); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/EditModeLauncher.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/EditModeLauncher.cs new file mode 100644 index 00000000..d8314d3c --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/EditModeLauncher.cs @@ -0,0 +1,141 @@ +using System.Collections.Generic; +using NUnit.Framework.Interfaces; +using UnityEditor.SceneManagement; +using UnityEditor.TestTools.TestRunner.Api; +using UnityEngine; +using UnityEngine.SceneManagement; +using UnityEngine.TestTools; +using UnityEngine.TestTools.TestRunner; +using UnityEngine.TestTools.TestRunner.GUI; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class EditModeLauncher : TestLauncherBase + { + public static bool IsRunning; + private readonly EditModeRunner m_EditModeRunner; + + public EditModeLauncher(TestRunnerFilter filter, TestPlatform platform) + { + m_EditModeRunner = ScriptableObject.CreateInstance(); + m_EditModeRunner.UnityTestAssemblyRunnerFactory = new UnityTestAssemblyRunnerFactory(); + m_EditModeRunner.Init(filter, platform); + } + + public override void Run() + { + // Give user chance to save the changes to their currently open scene because we close it and load our own + var cancelled = !EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo(); + if (cancelled) + return; + + IsRunning = true; + var exceptionThrown = ExecutePreBuildSetupMethods(m_EditModeRunner.GetLoadedTests(), m_EditModeRunner.GetFilter()); + if (exceptionThrown) + { + CallbacksDelegator.instance.RunFailed("Run Failed: One or more errors in a prebuild setup. See the editor log for details."); + return; + } + + var undoGroup = Undo.GetCurrentGroup(); + SceneSetup[] previousSceneSetup; + if (!OpenNewScene(out previousSceneSetup)) + return; + + var callback = AddEventHandler(); + callback.previousSceneSetup = previousSceneSetup; + callback.undoGroup = undoGroup; + callback.runner = m_EditModeRunner; + AddEventHandler(); + + m_EditModeRunner.Run(); + AddEventHandler(); + } + + private static bool OpenNewScene(out SceneSetup[] previousSceneSetup) + { + previousSceneSetup = null; + + var sceneCount = SceneManager.sceneCount; + + var scene = SceneManager.GetSceneAt(0); + var isSceneNotPersisted = string.IsNullOrEmpty(scene.path); + + if (sceneCount == 1 && isSceneNotPersisted) + { + EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Single); + return true; + } + RemoveUntitledScenes(); + + // In case the user chose not to save the dirty scenes we reload them + ReloadUnsavedDirtyScene(); + + previousSceneSetup = EditorSceneManager.GetSceneManagerSetup(); + + scene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Additive); + SceneManager.SetActiveScene(scene); + + return true; + } + + private static void ReloadUnsavedDirtyScene() + { + for (var i = 0; i < SceneManager.sceneCount; i++) + { + var scene = SceneManager.GetSceneAt(i); + var isSceneNotPersisted = string.IsNullOrEmpty(scene.path); + var isSceneDirty = scene.isDirty; + if (isSceneNotPersisted && isSceneDirty) + { + EditorSceneManager.ReloadScene(scene); + } + } + } + + private static void RemoveUntitledScenes() + { + int sceneCount = SceneManager.sceneCount; + + var scenesToClose = new List(); + for (var i = 0; i < sceneCount; i++) + { + var scene = SceneManager.GetSceneAt(i); + var isSceneNotPersisted = string.IsNullOrEmpty(scene.path); + if (isSceneNotPersisted) + { + scenesToClose.Add(scene); + } + } + foreach (Scene scene in scenesToClose) + { + EditorSceneManager.CloseScene(scene, true); + } + } + + public class BackgroundListener : ScriptableObject, ITestRunnerListener + { + public void RunStarted(ITest testsToRun) + { + } + + public void RunFinished(ITestResult testResults) + { + IsRunning = false; + } + + public void TestStarted(ITest test) + { + } + + public void TestFinished(ITestResult result) + { + } + } + + public T AddEventHandler() where T : ScriptableObject, ITestRunnerListener + { + return m_EditModeRunner.AddEventHandler(); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/EditModeLauncherContextSettings.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/EditModeLauncherContextSettings.cs new file mode 100644 index 00000000..e20305cd --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/EditModeLauncherContextSettings.cs @@ -0,0 +1,31 @@ +using System; +using UnityEngine; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class EditModeLauncherContextSettings : IDisposable + { + private bool m_RunInBackground; + + public EditModeLauncherContextSettings() + { + SetupProjectParameters(); + } + + public void Dispose() + { + CleanupProjectParameters(); + } + + private void SetupProjectParameters() + { + m_RunInBackground = Application.runInBackground; + Application.runInBackground = true; + } + + private void CleanupProjectParameters() + { + Application.runInBackground = m_RunInBackground; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/PlatformSetup/AndroidPlatformSetup.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/PlatformSetup/AndroidPlatformSetup.cs new file mode 100644 index 00000000..9f39c0aa --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/PlatformSetup/AndroidPlatformSetup.cs @@ -0,0 +1,62 @@ +using System; +using UnityEngine; +using System.Net; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class AndroidPlatformSetup : IPlatformSetup + { + private string m_oldApplicationIdentifier; + private string m_oldDeviceSocketAddress; + [SerializeField] + private bool m_Stripping; + + public void Setup() + { + m_oldApplicationIdentifier = PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.Android); + PlayerSettings.SetApplicationIdentifier(BuildTargetGroup.Android, "com.UnityTestRunner.UnityTestRunner"); + + m_oldDeviceSocketAddress = EditorUserBuildSettings.androidDeviceSocketAddress; + var androidDeviceConnection = Environment.GetEnvironmentVariable("ANDROID_DEVICE_CONNECTION"); + EditorUserBuildSettings.waitForPlayerConnection = true; + if (androidDeviceConnection != null) + { + EditorUserBuildSettings.androidDeviceSocketAddress = androidDeviceConnection; + } + m_Stripping = PlayerSettings.stripEngineCode; + PlayerSettings.stripEngineCode = false; + } + + public void PostBuildAction() + { + PlayerSettings.stripEngineCode = m_Stripping; + } + + public void PostSuccessfulBuildAction() + { + var connectionResult = -1; + var maxTryCount = 10; + var tryCount = maxTryCount; + while (tryCount-- > 0 && connectionResult == -1) + { + connectionResult = EditorConnectionInternal.ConnectPlayerProxy(IPAddress.Loopback.ToString(), 34999); + if (EditorUtility.DisplayCancelableProgressBar("Editor Connection", "Connecting to the player", + 1 - ((float)tryCount / maxTryCount))) + { + EditorUtility.ClearProgressBar(); + throw new TestLaunchFailedException(); + } + } + EditorUtility.ClearProgressBar(); + if (connectionResult == -1) + throw new TestLaunchFailedException( + "Timed out trying to connect to the player. Player failed to launch or crashed soon after launching"); + } + + public void CleanUp() + { + EditorUserBuildSettings.androidDeviceSocketAddress = m_oldDeviceSocketAddress; + PlayerSettings.SetApplicationIdentifier(BuildTargetGroup.Android, m_oldApplicationIdentifier); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/PlatformSetup/ApplePlatformSetup.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/PlatformSetup/ApplePlatformSetup.cs new file mode 100644 index 00000000..59cc6889 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/PlatformSetup/ApplePlatformSetup.cs @@ -0,0 +1,38 @@ +using System; +using System.Diagnostics; +using UnityEngine; + +namespace UnityEditor.TestTools.TestRunner +{ + [Serializable] + internal class ApplePlatformSetup : IPlatformSetup + { + [SerializeField] + private bool m_Stripping; + + public ApplePlatformSetup(BuildTarget buildTarget) + { + } + + public void Setup() + { + // Camera and fonts are stripped out and app crashes on iOS when test runner is trying to add a scene with... camera and text + m_Stripping = PlayerSettings.stripEngineCode; + PlayerSettings.stripEngineCode = false; + } + + public void PostBuildAction() + { + // Restoring player setting as early as possible + PlayerSettings.stripEngineCode = m_Stripping; + } + + public void PostSuccessfulBuildAction() + { + } + + public void CleanUp() + { + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/PlatformSetup/IPlatformSetup.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/PlatformSetup/IPlatformSetup.cs new file mode 100644 index 00000000..0cbcb33c --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/PlatformSetup/IPlatformSetup.cs @@ -0,0 +1,10 @@ +namespace UnityEditor.TestTools.TestRunner +{ + internal interface IPlatformSetup + { + void Setup(); + void PostBuildAction(); + void PostSuccessfulBuildAction(); + void CleanUp(); + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/PlatformSetup/LuminPlatformSetup.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/PlatformSetup/LuminPlatformSetup.cs new file mode 100644 index 00000000..1d038092 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/PlatformSetup/LuminPlatformSetup.cs @@ -0,0 +1,46 @@ +using System; +using System.Threading; +using UnityEngine; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class LuminPlatformSetup : IPlatformSetup + { + private const string kDeviceAddress = "127.0.0.1"; + private const int kDevicePort = 55000; + + public void Setup() + { + } + + public void PostBuildAction() + { + } + + public void PostSuccessfulBuildAction() + { + var connectionResult = -1; + var maxTryCount = 100; + var tryCount = maxTryCount; + while (tryCount-- > 0 && connectionResult == -1) + { + Thread.Sleep(1000); + connectionResult = EditorConnectionInternal.ConnectPlayerProxy(kDeviceAddress, kDevicePort); + if (EditorUtility.DisplayCancelableProgressBar("Editor Connection", "Connecting to the player", + 1 - ((float)tryCount / maxTryCount))) + { + EditorUtility.ClearProgressBar(); + throw new TestLaunchFailedException(); + } + } + EditorUtility.ClearProgressBar(); + if (connectionResult == -1) + throw new TestLaunchFailedException( + "Timed out trying to connect to the player. Player failed to launch or crashed soon after launching"); + } + + public void CleanUp() + { + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/PlatformSetup/PlatformSpecificSetup.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/PlatformSetup/PlatformSpecificSetup.cs new file mode 100644 index 00000000..7db58016 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/PlatformSetup/PlatformSpecificSetup.cs @@ -0,0 +1,105 @@ +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace UnityEditor.TestTools.TestRunner +{ + [Serializable] + internal class PlatformSpecificSetup + { + [SerializeField] + private ApplePlatformSetup m_AppleiOSPlatformSetup = new ApplePlatformSetup(BuildTarget.iOS); + [SerializeField] + private ApplePlatformSetup m_AppleTvOSPlatformSetup = new ApplePlatformSetup(BuildTarget.tvOS); + [SerializeField] + private XboxOnePlatformSetup m_XboxOnePlatformSetup = new XboxOnePlatformSetup(); + [SerializeField] + private AndroidPlatformSetup m_AndroidPlatformSetup = new AndroidPlatformSetup(); + [SerializeField] + private SwitchPlatformSetup m_SwitchPlatformSetup = new SwitchPlatformSetup(); + + [SerializeField] + private UwpPlatformSetup m_UwpPlatformSetup = new UwpPlatformSetup(); + + [SerializeField] + private LuminPlatformSetup m_LuminPlatformSetup = new LuminPlatformSetup(); + + + private IDictionary m_SetupTypes; + + [SerializeField] + private BuildTarget m_Target; + + public PlatformSpecificSetup() + { + } + + public PlatformSpecificSetup(BuildTarget target) + { + m_Target = target; + } + + public void Setup() + { + var dictionary = GetSetup(); + + if (!dictionary.ContainsKey(m_Target)) + { + return; + } + + dictionary[m_Target].Setup(); + } + + public void PostBuildAction() + { + var dictionary = GetSetup(); + + if (!dictionary.ContainsKey(m_Target)) + { + return; + } + + dictionary[m_Target].PostBuildAction(); + } + + public void PostSuccessfulBuildAction() + { + var dictionary = GetSetup(); + + if (!dictionary.ContainsKey(m_Target)) + { + return; + } + + dictionary[m_Target].PostSuccessfulBuildAction(); + } + + public void CleanUp() + { + var dictionary = GetSetup(); + + if (!dictionary.ContainsKey(m_Target)) + { + return; + } + + dictionary[m_Target].CleanUp(); + } + + private IDictionary GetSetup() + { + m_SetupTypes = new Dictionary() + { + {BuildTarget.iOS, m_AppleiOSPlatformSetup}, + {BuildTarget.tvOS, m_AppleTvOSPlatformSetup}, + {BuildTarget.XboxOne, m_XboxOnePlatformSetup}, + {BuildTarget.Android, m_AndroidPlatformSetup}, + {BuildTarget.WSAPlayer, m_UwpPlatformSetup}, + {BuildTarget.Lumin, m_LuminPlatformSetup}, + {BuildTarget.Switch, m_SwitchPlatformSetup} + }; + return m_SetupTypes; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/PlatformSetup/SwitchPlatformSetup.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/PlatformSetup/SwitchPlatformSetup.cs new file mode 100644 index 00000000..20cabe0f --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/PlatformSetup/SwitchPlatformSetup.cs @@ -0,0 +1,33 @@ +namespace UnityEditor.TestTools.TestRunner +{ + internal class SwitchPlatformSetup : IPlatformSetup + { + public void Setup() + { + EditorUserBuildSettings.switchCreateRomFile = true; + EditorUserBuildSettings.switchNVNGraphicsDebugger = false; + EditorUserBuildSettings.switchNVNDrawValidation = true; // catches more graphics errors + EditorUserBuildSettings.development = true; + EditorUserBuildSettings.switchRedirectWritesToHostMount = true; + + // We can use these when more debugging is required: + //EditorUserBuildSettings.switchNVNDrawValidation = false; // cannot be used with shader debug + //EditorUserBuildSettings.switchNVNGraphicsDebugger = true; + //EditorUserBuildSettings.switchNVNShaderDebugging = true; + //EditorUserBuildSettings.switchCreateSolutionFile = true; // for shorter iteration time + //EditorUserBuildSettings.allowDebugging = true; // managed debugger can be attached + } + + public void PostBuildAction() + { + } + + public void PostSuccessfulBuildAction() + { + } + + public void CleanUp() + { + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/PlatformSetup/UwpPlatformSetup.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/PlatformSetup/UwpPlatformSetup.cs new file mode 100644 index 00000000..6eb634a5 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/PlatformSetup/UwpPlatformSetup.cs @@ -0,0 +1,48 @@ +using System; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class UwpPlatformSetup : IPlatformSetup + { + private const string k_SettingsBuildConfiguration = "BuildConfiguration"; + private bool m_InternetClientServer; + private bool m_PrivateNetworkClientServer; + + public void Setup() + { + m_InternetClientServer = PlayerSettings.WSA.GetCapability(PlayerSettings.WSACapability.InternetClientServer); + m_PrivateNetworkClientServer = PlayerSettings.WSA.GetCapability(PlayerSettings.WSACapability.PrivateNetworkClientServer); + PlayerSettings.WSA.SetCapability(PlayerSettings.WSACapability.InternetClientServer, true); + PlayerSettings.WSA.SetCapability(PlayerSettings.WSACapability.PrivateNetworkClientServer, true); + + // This setting is initialized only when Window Store App is selected from the Build Settings window, and + // is typically an empty strings when running tests via UTR on the command-line. + bool wsaSettingNotInitialized = string.IsNullOrEmpty(EditorUserBuildSettings.wsaArchitecture); + + // If WSA build settings aren't fully initialized or running from a build machine, specify a default build configuration. + // Otherwise we can use the existing configuration specified by the user in Build Settings. + if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("UNITY_THISISABUILDMACHINE")) || wsaSettingNotInitialized) + { + EditorUserBuildSettings.wsaSubtarget = WSASubtarget.PC; + EditorUserBuildSettings.wsaArchitecture = "x64"; + EditorUserBuildSettings.SetPlatformSettings(BuildPipeline.GetBuildTargetName(BuildTarget.WSAPlayer), k_SettingsBuildConfiguration, WSABuildType.Debug.ToString()); + EditorUserBuildSettings.wsaUWPBuildType = WSAUWPBuildType.ExecutableOnly; + PlayerSettings.SetIl2CppCompilerConfiguration(BuildTargetGroup.WSA, Il2CppCompilerConfiguration.Debug); + } + } + + public void PostBuildAction() + { + } + + public void PostSuccessfulBuildAction() + { + } + + public void CleanUp() + { + PlayerSettings.WSA.SetCapability(PlayerSettings.WSACapability.InternetClientServer, m_InternetClientServer); + PlayerSettings.WSA.SetCapability(PlayerSettings.WSACapability.PrivateNetworkClientServer, m_PrivateNetworkClientServer); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/PlatformSetup/XboxOnePlatformSetup.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/PlatformSetup/XboxOnePlatformSetup.cs new file mode 100644 index 00000000..0897dc55 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/PlatformSetup/XboxOnePlatformSetup.cs @@ -0,0 +1,43 @@ +namespace UnityEditor.TestTools.TestRunner +{ + internal class XboxOnePlatformSetup : IPlatformSetup + { + private XboxOneDeployMethod oldXboxOneDeployMethod; + private XboxOneDeployDrive oldXboxOneDeployDrive; + private string oldXboxOneAdditionalDebugPorts; + + public void Setup() + { + oldXboxOneDeployMethod = EditorUserBuildSettings.xboxOneDeployMethod; + oldXboxOneDeployDrive = EditorUserBuildSettings.xboxOneDeployDrive; + oldXboxOneAdditionalDebugPorts = EditorUserBuildSettings.xboxOneAdditionalDebugPorts; + + EditorUserBuildSettings.xboxOneDeployMethod = XboxOneDeployMethod.Package; + EditorUserBuildSettings.xboxOneDeployDrive = XboxOneDeployDrive.Default; + + // This causes the XboxOne post processing systems to open this port in your package manifest. + // In addition it will open the ephemeral range for debug connections as well. + // Failure to do this will cause connection problems. + EditorUserBuildSettings.xboxOneAdditionalDebugPorts = "34999"; + } + + public void PostBuildAction() + { + } + + public void PostSuccessfulBuildAction() + { + } + + public void CleanUp() + { + EditorUserBuildSettings.xboxOneDeployMethod = oldXboxOneDeployMethod; + EditorUserBuildSettings.xboxOneDeployDrive = oldXboxOneDeployDrive; + + // This causes the XboxOne post processing systems to open this port in your package manifest. + // In addition it will open the ephemeral range for debug connections as well. + // Failure to do this will cause connection problems. + EditorUserBuildSettings.xboxOneAdditionalDebugPorts = oldXboxOneAdditionalDebugPorts; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/PlayerLauncher.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/PlayerLauncher.cs new file mode 100644 index 00000000..7655d4d8 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/PlayerLauncher.cs @@ -0,0 +1,185 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using UnityEditor; +using UnityEditor.TestRunner.TestLaunchers; +using UnityEditor.TestTools.TestRunner.Api; +using UnityEngine; +using UnityEngine.SceneManagement; +using UnityEngine.TestTools.TestRunner; +using UnityEngine.TestTools.TestRunner.Callbacks; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class TestLaunchFailedException : Exception + { + public TestLaunchFailedException() {} + public TestLaunchFailedException(string message) : base(message) {} + } + + [Serializable] + internal class PlayerLauncher : RuntimeTestLauncherBase + { + private readonly PlaymodeTestsControllerSettings m_Settings; + private readonly BuildTarget m_TargetPlatform; + private string m_TempBuildLocation; + private ITestRunSettings m_OverloadTestRunSettings; + + public PlayerLauncher(PlaymodeTestsControllerSettings settings, BuildTarget? targetPlatform, ITestRunSettings overloadTestRunSettings) + { + m_Settings = settings; + m_TargetPlatform = targetPlatform ?? EditorUserBuildSettings.activeBuildTarget; + m_OverloadTestRunSettings = overloadTestRunSettings; + } + + protected override RuntimePlatform? TestTargetPlatform + { + get { return BuildTargetConverter.TryConvertToRuntimePlatform(m_TargetPlatform); } + } + + public override void Run() + { + var editorConnectionTestCollector = RemoteTestRunController.instance; + editorConnectionTestCollector.hideFlags = HideFlags.HideAndDontSave; + editorConnectionTestCollector.Init(m_TargetPlatform); + + var remotePlayerLogController = RemotePlayerLogController.instance; + remotePlayerLogController.hideFlags = HideFlags.HideAndDontSave; + + using (var settings = new PlayerLauncherContextSettings(m_OverloadTestRunSettings)) + { + var sceneName = CreateSceneName(); + var scene = PrepareScene(sceneName); + + var filter = m_Settings.filter.BuildNUnitFilter(); + var runner = LoadTests(filter); + var exceptionThrown = ExecutePreBuildSetupMethods(runner.LoadedTest, filter); + if (exceptionThrown) + { + ReopenOriginalScene(m_Settings.originalScene); + AssetDatabase.DeleteAsset(sceneName); + CallbacksDelegator.instance.RunFailed("Run Failed: One or more errors in a prebuild setup. See the editor log for details."); + return; + } + + var playerBuildOptions = GetBuildOptions(scene); + + var success = BuildAndRunPlayer(playerBuildOptions); + editorConnectionTestCollector.PostBuildAction(); + ExecutePostBuildCleanupMethods(runner.LoadedTest, filter); + + ReopenOriginalScene(m_Settings.originalScene); + AssetDatabase.DeleteAsset(sceneName); + + if (!success) + { + ScriptableObject.DestroyImmediate(editorConnectionTestCollector); + Debug.LogError("Player build failed"); + throw new TestLaunchFailedException("Player build failed"); + } + + editorConnectionTestCollector.PostSuccessfulBuildAction(); + } + } + + public Scene PrepareScene(string sceneName) + { + var scene = CreateBootstrapScene(sceneName, runner => + { + runner.AddEventHandlerMonoBehaviour(); + runner.settings = m_Settings; + runner.AddEventHandlerMonoBehaviour(); + }); + return scene; + } + + private static bool BuildAndRunPlayer(PlayerLauncherBuildOptions buildOptions) + { + Debug.LogFormat(LogType.Log, LogOption.NoStacktrace, null, "Building player with following options:\n{0}", buildOptions); + + + // Android has to be in listen mode to establish player connection + if (buildOptions.BuildPlayerOptions.target == BuildTarget.Android) + { + buildOptions.BuildPlayerOptions.options &= ~BuildOptions.ConnectToHost; + } + + // For now, so does Lumin + if (buildOptions.BuildPlayerOptions.target == BuildTarget.Lumin) + { + buildOptions.BuildPlayerOptions.options &= ~BuildOptions.ConnectToHost; + } + + var result = BuildPipeline.BuildPlayer(buildOptions.BuildPlayerOptions); + if (result.summary.result != Build.Reporting.BuildResult.Succeeded) + Debug.LogError(result.SummarizeErrors()); + + return result.summary.result == Build.Reporting.BuildResult.Succeeded; + } + + private PlayerLauncherBuildOptions GetBuildOptions(Scene scene) + { + var buildOptions = new BuildPlayerOptions(); + var reduceBuildLocationPathLength = false; + + //Some platforms hit MAX_PATH limits during the build process, in these cases minimize the path length + if ((m_TargetPlatform == BuildTarget.WSAPlayer) || (m_TargetPlatform == BuildTarget.XboxOne)) + { + reduceBuildLocationPathLength = true; + } + + var scenes = new List() { scene.path }; + scenes.AddRange(EditorBuildSettings.scenes.Select(x => x.path)); + buildOptions.scenes = scenes.ToArray(); + + buildOptions.options |= BuildOptions.AutoRunPlayer | BuildOptions.Development | BuildOptions.ConnectToHost | BuildOptions.IncludeTestAssemblies | BuildOptions.StrictMode; + buildOptions.target = m_TargetPlatform; + + if (EditorUserBuildSettings.waitForPlayerConnection) + buildOptions.options |= BuildOptions.WaitForPlayerConnection; + + var buildTargetGroup = EditorUserBuildSettings.activeBuildTargetGroup; + var uniqueTempPathInProject = FileUtil.GetUniqueTempPathInProject(); + + if (reduceBuildLocationPathLength) + { + uniqueTempPathInProject = Path.GetTempFileName(); + File.Delete(uniqueTempPathInProject); + Directory.CreateDirectory(uniqueTempPathInProject); + } + + //Check if Lz4 is supported for the current buildtargetgroup and enable it if need be + if (PostprocessBuildPlayer.SupportsLz4Compression(buildTargetGroup, m_TargetPlatform)) + { + if (EditorUserBuildSettings.GetCompressionType(buildTargetGroup) == Compression.Lz4) + buildOptions.options |= BuildOptions.CompressWithLz4; + else if (EditorUserBuildSettings.GetCompressionType(buildTargetGroup) == Compression.Lz4HC) + buildOptions.options |= BuildOptions.CompressWithLz4HC; + } + + m_TempBuildLocation = Path.GetFullPath(uniqueTempPathInProject); + + string extensionForBuildTarget = PostprocessBuildPlayer.GetExtensionForBuildTarget(buildTargetGroup, buildOptions.target, buildOptions.options); + + var playerExecutableName = "PlayerWithTests"; + var playerDirectoryName = reduceBuildLocationPathLength ? "PwT" : "PlayerWithTests"; + + var locationPath = Path.Combine(m_TempBuildLocation, playerDirectoryName); + + if (!string.IsNullOrEmpty(extensionForBuildTarget)) + { + playerExecutableName += string.Format(".{0}", extensionForBuildTarget); + locationPath = Path.Combine(locationPath, playerExecutableName); + } + + buildOptions.locationPathName = locationPath; + + return new PlayerLauncherBuildOptions + { + BuildPlayerOptions = buildOptions, + PlayerDirectory = Path.Combine(m_TempBuildLocation, playerDirectoryName), + }; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/PlayerLauncherBuildOptions.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/PlayerLauncherBuildOptions.cs new file mode 100644 index 00000000..b4985147 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/PlayerLauncherBuildOptions.cs @@ -0,0 +1,23 @@ +using System.Text; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class PlayerLauncherBuildOptions + { + public BuildPlayerOptions BuildPlayerOptions; + public string PlayerDirectory; + + public override string ToString() + { + var str = new StringBuilder(); + str.AppendLine("locationPathName = " + BuildPlayerOptions.locationPathName); + str.AppendLine("target = " + BuildPlayerOptions.target); + str.AppendLine("scenes = " + string.Join(", ", BuildPlayerOptions.scenes)); + str.AppendLine("assetBundleManifestPath = " + BuildPlayerOptions.assetBundleManifestPath); + str.AppendLine("options.Development = " + ((BuildPlayerOptions.options & BuildOptions.Development) != 0)); + str.AppendLine("options.AutoRunPlayer = " + ((BuildPlayerOptions.options & BuildOptions.AutoRunPlayer) != 0)); + str.AppendLine("options.ForceEnableAssertions = " + ((BuildPlayerOptions.options & BuildOptions.ForceEnableAssertions) != 0)); + return str.ToString(); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/PlayerLauncherContextSettings.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/PlayerLauncherContextSettings.cs new file mode 100644 index 00000000..89b1cb22 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/PlayerLauncherContextSettings.cs @@ -0,0 +1,106 @@ +using System; +using UnityEditor.TestTools.TestRunner.Api; +using UnityEngine; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class PlayerLauncherContextSettings : IDisposable + { + private ITestRunSettings m_OverloadSettings; + + private EditorBuildSettingsScene[] m_EditorBuildSettings; +#pragma warning disable 618 + private ResolutionDialogSetting m_DisplayResolutionDialog; +#pragma warning restore 618 + private bool m_RunInBackground; + private FullScreenMode m_FullScreenMode; + private bool m_ResizableWindow; + private bool m_ShowUnitySplashScreen; + private string m_OldproductName; + private string m_OldAotOptions; + private Lightmapping.GIWorkflowMode m_OldLightmapping; + private bool m_explicitNullChecks; + + private bool m_Disposed; + + public PlayerLauncherContextSettings(ITestRunSettings overloadSettings) + { + m_OverloadSettings = overloadSettings; + SetupProjectParameters(); + + if (overloadSettings != null) + { + overloadSettings.Apply(); + } + } + + public void Dispose() + { + if (!m_Disposed) + { + CleanupProjectParameters(); + if (m_OverloadSettings != null) + { + m_OverloadSettings.Dispose(); + } + + m_Disposed = true; + } + } + + private void SetupProjectParameters() + { + EditorApplication.LockReloadAssemblies(); + + m_EditorBuildSettings = EditorBuildSettings.scenes; + +#pragma warning disable 618 + m_DisplayResolutionDialog = PlayerSettings.displayResolutionDialog; + PlayerSettings.displayResolutionDialog = ResolutionDialogSetting.Disabled; +#pragma warning restore 618 + + m_RunInBackground = PlayerSettings.runInBackground; + PlayerSettings.runInBackground = true; + + m_FullScreenMode = PlayerSettings.fullScreenMode; + PlayerSettings.fullScreenMode = FullScreenMode.Windowed; + + m_OldAotOptions = PlayerSettings.aotOptions; + PlayerSettings.aotOptions = "nimt-trampolines=1024"; + + m_ResizableWindow = PlayerSettings.resizableWindow; + PlayerSettings.resizableWindow = true; + + m_ShowUnitySplashScreen = PlayerSettings.SplashScreen.show; + PlayerSettings.SplashScreen.show = false; + + m_OldproductName = PlayerSettings.productName; + PlayerSettings.productName = "UnityTestFramework"; + + m_OldLightmapping = Lightmapping.giWorkflowMode; + Lightmapping.giWorkflowMode = Lightmapping.GIWorkflowMode.OnDemand; + + m_explicitNullChecks = EditorUserBuildSettings.explicitNullChecks; + EditorUserBuildSettings.explicitNullChecks = true; + } + + private void CleanupProjectParameters() + { + EditorBuildSettings.scenes = m_EditorBuildSettings; + + PlayerSettings.fullScreenMode = m_FullScreenMode; + PlayerSettings.runInBackground = m_RunInBackground; +#pragma warning disable 618 + PlayerSettings.displayResolutionDialog = m_DisplayResolutionDialog; +#pragma warning restore 618 + PlayerSettings.resizableWindow = m_ResizableWindow; + PlayerSettings.SplashScreen.show = m_ShowUnitySplashScreen; + PlayerSettings.productName = m_OldproductName; + PlayerSettings.aotOptions = m_OldAotOptions; + Lightmapping.giWorkflowMode = m_OldLightmapping; + EditorUserBuildSettings.explicitNullChecks = m_explicitNullChecks; + + EditorApplication.UnlockReloadAssemblies(); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/PlaymodeLauncher.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/PlaymodeLauncher.cs new file mode 100644 index 00000000..78a9c727 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/PlaymodeLauncher.cs @@ -0,0 +1,129 @@ +using System; +using System.Collections.Generic; +using NUnit.Framework.Interfaces; +using UnityEditor.TestTools.TestRunner.Api; +using UnityEngine; +using UnityEngine.SceneManagement; +using UnityEngine.TestTools.TestRunner; +using UnityEngine.TestTools.TestRunner.Callbacks; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class PlaymodeLauncher : RuntimeTestLauncherBase + { + public static bool IsRunning; + private Scene m_Scene; + private bool m_IsTestSetupPerformed; + private readonly PlaymodeTestsControllerSettings m_Settings; + private ITestFilter testFilter; + + [SerializeField] + private List m_EventHandlers = new List(); + + public PlaymodeLauncher(PlaymodeTestsControllerSettings settings) + { + m_Settings = settings; + } + + public override void Run() + { + IsRunning = true; + ConsoleWindow.SetConsoleErrorPause(false); + Application.runInBackground = true; + + var sceneName = CreateSceneName(); + m_Scene = CreateBootstrapScene(sceneName, runner => + { + runner.AddEventHandlerMonoBehaviour(); + runner.AddEventHandlerScriptableObject(); + runner.AddEventHandlerScriptableObject(); + + foreach (var eventHandler in m_EventHandlers) + { + var obj = ScriptableObject.CreateInstance(eventHandler); + runner.AddEventHandlerScriptableObject(obj as ITestRunnerListener); + } + + runner.settings = m_Settings; + }); + + if (m_Settings.sceneBased) + { + var newListOfScenes = + new List {new EditorBuildSettingsScene(sceneName, true)}; + newListOfScenes.AddRange(EditorBuildSettings.scenes); + EditorBuildSettings.scenes = newListOfScenes.ToArray(); + } + + EditorApplication.update += UpdateCallback; + } + + public void UpdateCallback() + { + if (m_IsTestSetupPerformed) + { + if (m_Scene.IsValid()) + SceneManager.SetActiveScene(m_Scene); + EditorApplication.update -= UpdateCallback; + EditorApplication.isPlaying = true; + } + else + { + testFilter = m_Settings.filter.BuildNUnitFilter(); + var runner = LoadTests(testFilter); + + var exceptionThrown = ExecutePreBuildSetupMethods(runner.LoadedTest, testFilter); + if (exceptionThrown) + { + EditorApplication.update -= UpdateCallback; + IsRunning = false; + var controller = PlaymodeTestsController.GetController(); + ReopenOriginalScene(controller); + AssetDatabase.DeleteAsset(controller.settings.bootstrapScene); + CallbacksDelegator.instance.RunFailed("Run Failed: One or more errors in a prebuild setup. See the editor log for details."); + return; + } + m_IsTestSetupPerformed = true; + } + } + + [InitializeOnLoad] + public class BackgroundWatcher + { + static BackgroundWatcher() + { + EditorApplication.playModeStateChanged += OnPlayModeStateChanged; + } + + private static void OnPlayModeStateChanged(PlayModeStateChange state) + { + if (!PlaymodeTestsController.IsControllerOnScene()) + return; + var runner = PlaymodeTestsController.GetController(); + if (runner == null) + return; + if (state == PlayModeStateChange.ExitingPlayMode) + { + AssetDatabase.DeleteAsset(runner.settings.bootstrapScene); + ExecutePostBuildCleanupMethods(runner.m_Runner.LoadedTest, runner.settings.filter.BuildNUnitFilter(), Application.platform); + IsRunning = false; + } + else if (state == PlayModeStateChange.EnteredEditMode) + { + //reopen the original scene once we exit playmode + ReopenOriginalScene(runner); + } + } + } + + protected static void ReopenOriginalScene(PlaymodeTestsController runner) + { + ReopenOriginalScene(runner.settings.originalScene); + } + + public void AddEventHandler() where T : ScriptableObject, ITestRunnerListener + { + m_EventHandlers.Add(typeof(T)); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/PostbuildCleanupAttributeFinder.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/PostbuildCleanupAttributeFinder.cs new file mode 100644 index 00000000..32dee2b6 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/PostbuildCleanupAttributeFinder.cs @@ -0,0 +1,9 @@ +using UnityEngine.TestTools; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class PostbuildCleanupAttributeFinder : AttributeFinderBase + { + public PostbuildCleanupAttributeFinder() : base(attribute => attribute.TargetClass) {} + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/PrebuildSetupAttributeFinder.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/PrebuildSetupAttributeFinder.cs new file mode 100644 index 00000000..b51241f5 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/PrebuildSetupAttributeFinder.cs @@ -0,0 +1,9 @@ +using UnityEngine.TestTools; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class PrebuildSetupAttributeFinder : AttributeFinderBase + { + public PrebuildSetupAttributeFinder() : base((attribute) => attribute.TargetClass) {} + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/RemotePlayerLogController.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/RemotePlayerLogController.cs new file mode 100644 index 00000000..25f4b651 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/RemotePlayerLogController.cs @@ -0,0 +1,83 @@ +using System; +using System.Collections.Generic; +using UnityEditor.DeploymentTargets; +using UnityEditor.TestTools.TestRunner.CommandLineTest; +using UnityEngine; + +namespace UnityEditor.TestRunner.TestLaunchers +{ + [Serializable] + internal class RemotePlayerLogController : ScriptableSingleton + { + private List m_LogWriters; + + private Dictionary m_Loggers; + + private string m_DeviceLogsDirectory; + + public void SetBuildTarget(BuildTarget buildTarget) + { + m_Loggers = GetDeploymentTargetLoggers(buildTarget); + } + + public void SetLogsDirectory(string dir) + { + m_DeviceLogsDirectory = dir; + } + + public void StartLogWriters() + { + if (m_DeviceLogsDirectory == null || m_Loggers == null) + return; + + m_LogWriters = new List(); + + foreach (var logger in m_Loggers) + { + m_LogWriters.Add(new LogWriter(m_DeviceLogsDirectory, logger.Key, logger.Value)); + logger.Value.Start(); + } + } + + public void StopLogWriters() + { + if (m_LogWriters == null) + return; + + foreach (var logWriter in m_LogWriters) + { + logWriter.Stop(); + } + } + + private Dictionary GetDeploymentTargetLoggers(BuildTarget buildTarget) + { + DeploymentTargetManager deploymentTargetManager; + + try + { + deploymentTargetManager = DeploymentTargetManager.CreateInstance(EditorUserBuildSettings.activeBuildTargetGroup, buildTarget); + } + catch (NotSupportedException ex) + { + Debug.Log(ex.Message); + Debug.Log("Deployment target logger not initialised"); + return null; + } + + var targets = deploymentTargetManager.GetKnownTargets(); + var loggers = new Dictionary(); + + foreach (var target in targets) + { + if (target.status != DeploymentTargetStatus.Ready) continue; + + var logger = deploymentTargetManager.GetTargetLogger(target.id); + logger.Clear(); + loggers.Add(target.id, logger); + } + + return loggers; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/RemotePlayerTestController.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/RemotePlayerTestController.cs new file mode 100644 index 00000000..a7288ba1 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/RemotePlayerTestController.cs @@ -0,0 +1,81 @@ +using System; +using UnityEditor.Networking.PlayerConnection; +using UnityEditor.TestTools.TestRunner; +using UnityEditor.TestTools.TestRunner.Api; +using UnityEditor.TestTools.TestRunner.UnityTestProtocol; +using UnityEngine; +using UnityEngine.Networking.PlayerConnection; +using UnityEngine.TestRunner.TestLaunchers; + +namespace UnityEditor.TestRunner.TestLaunchers +{ + [Serializable] + internal class RemoteTestRunController : ScriptableSingleton + { + [SerializeField] + private RemoteTestResultReciever m_RemoteTestResultReciever; + + [SerializeField] + private PlatformSpecificSetup m_PlatformSpecificSetup; + + [SerializeField] + private bool m_RegisteredConnectionCallbacks; + + public void Init(BuildTarget buildTarget) + { + m_PlatformSpecificSetup = new PlatformSpecificSetup(buildTarget); + m_PlatformSpecificSetup.Setup(); + m_RemoteTestResultReciever = new RemoteTestResultReciever(); + EditorConnection.instance.Initialize(); + if (!m_RegisteredConnectionCallbacks) + { + EditorConnection.instance.Initialize(); + DelegateEditorConnectionEvents(); + } + } + + private void DelegateEditorConnectionEvents() + { + m_RegisteredConnectionCallbacks = true; + //This is needed because RemoteTestResultReciever is not a ScriptableObject + EditorConnection.instance.Register(PlayerConnectionMessageIds.runStartedMessageId, RunStarted); + EditorConnection.instance.Register(PlayerConnectionMessageIds.runFinishedMessageId, RunFinished); + EditorConnection.instance.Register(PlayerConnectionMessageIds.testStartedMessageId, TestStarted); + EditorConnection.instance.Register(PlayerConnectionMessageIds.testFinishedMessageId, TestFinished); + } + + private void RunStarted(MessageEventArgs messageEventArgs) + { + m_RemoteTestResultReciever.RunStarted(messageEventArgs); + CallbacksDelegator.instance.RunStartedRemotely(messageEventArgs.data); + } + + private void RunFinished(MessageEventArgs messageEventArgs) + { + m_RemoteTestResultReciever.RunFinished(messageEventArgs); + m_PlatformSpecificSetup.CleanUp(); + + CallbacksDelegator.instance.RunFinishedRemotely(messageEventArgs.data); + } + + private void TestStarted(MessageEventArgs messageEventArgs) + { + CallbacksDelegator.instance.TestStartedRemotely(messageEventArgs.data); + } + + private void TestFinished(MessageEventArgs messageEventArgs) + { + CallbacksDelegator.instance.TestFinishedRemotely(messageEventArgs.data); + } + + public void PostBuildAction() + { + m_PlatformSpecificSetup.PostBuildAction(); + } + + public void PostSuccessfulBuildAction() + { + m_PlatformSpecificSetup.PostSuccessfulBuildAction(); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/RemoteTestResultReciever.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/RemoteTestResultReciever.cs new file mode 100644 index 00000000..b45141b6 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/RemoteTestResultReciever.cs @@ -0,0 +1,22 @@ +using System; +using UnityEditor.Networking.PlayerConnection; +using UnityEngine; +using UnityEngine.Networking.PlayerConnection; +using UnityEngine.TestRunner.TestLaunchers; + +namespace UnityEditor.TestTools.TestRunner +{ + [Serializable] + internal class RemoteTestResultReciever + { + public void RunStarted(MessageEventArgs messageEventArgs) + { + } + + public void RunFinished(MessageEventArgs messageEventArgs) + { + EditorConnection.instance.Send(PlayerConnectionMessageIds.runFinishedMessageId, null, messageEventArgs.playerId); + EditorConnection.instance.DisconnectAll(); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/RuntimeTestLauncherBase.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/RuntimeTestLauncherBase.cs new file mode 100644 index 00000000..4f4aeb40 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/RuntimeTestLauncherBase.cs @@ -0,0 +1,92 @@ +using System; +using System.Linq; +using NUnit.Framework.Interfaces; +using UnityEditor.Events; +using UnityEditor.SceneManagement; +using UnityEngine; +using UnityEngine.SceneManagement; +using UnityEngine.TestRunner.NUnitExtensions.Runner; +using UnityEngine.TestTools; +using UnityEngine.TestTools.NUnitExtensions; +using UnityEngine.TestTools.TestRunner; +using UnityEngine.TestTools.Utils; + +namespace UnityEditor.TestTools.TestRunner +{ + internal abstract class RuntimeTestLauncherBase : TestLauncherBase + { + protected Scene CreateBootstrapScene(string sceneName, Action runnerSetup) + { + var scene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); + var go = new GameObject(PlaymodeTestsController.kPlaymodeTestControllerName); + + var editorLoadedTestAssemblyProvider = new EditorLoadedTestAssemblyProvider(new EditorCompilationInterfaceProxy(), new EditorAssembliesProxy()); + + var runner = go.AddComponent(); + runnerSetup(runner); + runner.settings.bootstrapScene = sceneName; + runner.AssembliesWithTests = editorLoadedTestAssemblyProvider.GetAssembliesGroupedByType(TestPlatform.PlayMode).Select(x => x.Assembly.GetName().Name).ToList(); + + EditorSceneManager.MarkSceneDirty(scene); + AssetDatabase.SaveAssets(); + EditorSceneManager.SaveScene(scene, sceneName, false); + + return scene; + } + + public string CreateSceneName() + { + return "Assets/InitTestScene" + DateTime.Now.Ticks + ".unity"; + } + + protected UnityTestAssemblyRunner LoadTests(ITestFilter filter) + { + var editorLoadedTestAssemblyProvider = new EditorLoadedTestAssemblyProvider(new EditorCompilationInterfaceProxy(), new EditorAssembliesProxy()); + var assembliesWithTests = editorLoadedTestAssemblyProvider.GetAssembliesGroupedByType(TestPlatform.PlayMode).Select(x => x.Assembly.GetName().Name).ToList(); + + var nUnitTestAssemblyRunner = new UnityTestAssemblyRunner(new UnityTestAssemblyBuilder(), null); + var assemblyProvider = new PlayerTestAssemblyProvider(new AssemblyLoadProxy(), assembliesWithTests); + nUnitTestAssemblyRunner.Load(assemblyProvider.GetUserAssemblies().Select(a => a.Assembly).ToArray(), UnityTestAssemblyBuilder.GetNUnitTestBuilderSettings(TestPlatform.PlayMode)); + return nUnitTestAssemblyRunner; + } + + protected static void ReopenOriginalScene(string originalSceneName) + { + EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects); + if (!string.IsNullOrEmpty(originalSceneName)) + { + EditorSceneManager.OpenScene(originalSceneName); + } + } + } + + internal static class PlaymodeTestsControllerExtensions + { + internal static T AddEventHandlerMonoBehaviour(this PlaymodeTestsController controller) where T : MonoBehaviour, ITestRunnerListener + { + var eventHandler = controller.gameObject.AddComponent(); + SetListeners(controller, eventHandler); + return eventHandler; + } + + internal static T AddEventHandlerScriptableObject(this PlaymodeTestsController controller) where T : ScriptableObject, ITestRunnerListener + { + var eventListener = ScriptableObject.CreateInstance(); + AddEventHandlerScriptableObject(controller, eventListener); + return eventListener; + } + + internal static void AddEventHandlerScriptableObject(this PlaymodeTestsController controller, ITestRunnerListener obj) + { + SetListeners(controller, obj); + } + + private static void SetListeners(PlaymodeTestsController controller, ITestRunnerListener eventHandler) + { + UnityEventTools.AddPersistentListener(controller.testStartedEvent, eventHandler.TestStarted); + UnityEventTools.AddPersistentListener(controller.testFinishedEvent, eventHandler.TestFinished); + UnityEventTools.AddPersistentListener(controller.runStartedEvent, eventHandler.RunStarted); + UnityEventTools.AddPersistentListener(controller.runFinishedEvent, eventHandler.RunFinished); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/TestLauncherBase.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/TestLauncherBase.cs new file mode 100644 index 00000000..cb8b5c48 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestLaunchers/TestLauncherBase.cs @@ -0,0 +1,66 @@ +using System; +using NUnit.Framework.Interfaces; +using UnityEngine; +using UnityEngine.TestTools; + +namespace UnityEditor.TestTools.TestRunner +{ + internal abstract class TestLauncherBase + { + public abstract void Run(); + + protected virtual RuntimePlatform? TestTargetPlatform + { + get { return Application.platform; } + } + + protected bool ExecutePreBuildSetupMethods(ITest tests, ITestFilter testRunnerFilter) + { + var attributeFinder = new PrebuildSetupAttributeFinder(); + var logString = "Executing setup for: {0}"; + return ExecuteMethods(tests, testRunnerFilter, attributeFinder, logString, targetClass => targetClass.Setup(), TestTargetPlatform); + } + + public void ExecutePostBuildCleanupMethods(ITest tests, ITestFilter testRunnerFilter) + { + ExecutePostBuildCleanupMethods(tests, testRunnerFilter, TestTargetPlatform); + } + + public static void ExecutePostBuildCleanupMethods(ITest tests, ITestFilter testRunnerFilter, RuntimePlatform? testTargetPlatform) + { + var attributeFinder = new PostbuildCleanupAttributeFinder(); + var logString = "Executing cleanup for: {0}"; + ExecuteMethods(tests, testRunnerFilter, attributeFinder, logString, targetClass => targetClass.Cleanup(), testTargetPlatform); + } + + private static bool ExecuteMethods(ITest tests, ITestFilter testRunnerFilter, AttributeFinderBase attributeFinder, string logString, Action action, RuntimePlatform? testTargetPlatform) + { + var exceptionsThrown = false; + + if (testTargetPlatform == null) + { + Debug.LogError("Could not determine test target platform from build target " + EditorUserBuildSettings.activeBuildTarget); + return true; + } + + foreach (var targetClassType in attributeFinder.Search(tests, testRunnerFilter, testTargetPlatform.Value)) + { + try + { + var targetClass = (T)Activator.CreateInstance(targetClassType); + + Debug.LogFormat(logString, targetClassType.FullName); + action(targetClass); + } + catch (InvalidCastException) {} + catch (Exception e) + { + Debug.LogException(e); + exceptionsThrown = true; + } + } + + return exceptionsThrown; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestResultSerializer.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestResultSerializer.cs new file mode 100644 index 00000000..f471feec --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestResultSerializer.cs @@ -0,0 +1,71 @@ +using System; +using System.Reflection; +using System.Text; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; +using UnityEngine; + +namespace UnityEditor.TestTools.TestRunner +{ + [Serializable] + internal class TestResultSerializer + { + private static readonly BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Public | + BindingFlags.Instance | BindingFlags.FlattenHierarchy; + + [SerializeField] public string id; + + [SerializeField] public string fullName; + + [SerializeField] private double duration; + + [SerializeField] private string label; + + [SerializeField] private string message; + + [SerializeField] private string output; + + [SerializeField] private string site; + + [SerializeField] private string stacktrace; + + [SerializeField] private double startTimeAO; + + [SerializeField] private string status; + + public static TestResultSerializer MakeFromTestResult(ITestResult result) + { + var wrapper = new TestResultSerializer(); + wrapper.id = result.Test.Id; + wrapper.fullName = result.FullName; + wrapper.status = result.ResultState.Status.ToString(); + wrapper.label = result.ResultState.Label; + wrapper.site = result.ResultState.Site.ToString(); + wrapper.output = result.Output; + wrapper.duration = result.Duration; + wrapper.stacktrace = result.StackTrace; + wrapper.message = result.Message; + wrapper.startTimeAO = result.StartTime.ToOADate(); + return wrapper; + } + + public void RestoreTestResult(TestResult result) + { + var resultState = new ResultState((TestStatus)Enum.Parse(typeof(TestStatus), status), label, + (FailureSite)Enum.Parse(typeof(FailureSite), site)); + result.GetType().BaseType.GetField("_resultState", flags).SetValue(result, resultState); + result.GetType().BaseType.GetField("_output", flags).SetValue(result, new StringBuilder(output)); + result.GetType().BaseType.GetField("_duration", flags).SetValue(result, duration); + result.GetType().BaseType.GetField("_message", flags).SetValue(result, message); + result.GetType().BaseType.GetField("_stackTrace", flags).SetValue(result, stacktrace); + result.GetType() + .BaseType.GetProperty("StartTime", flags) + .SetValue(result, DateTime.FromOADate(startTimeAO), null); + } + + public bool IsPassed() + { + return status == TestStatus.Passed.ToString(); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Callbacks/EditModeRunnerCallback.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Callbacks/EditModeRunnerCallback.cs new file mode 100644 index 00000000..9b92fbc0 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Callbacks/EditModeRunnerCallback.cs @@ -0,0 +1,190 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using NUnit.Framework; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; +using UnityEditor.SceneManagement; +using UnityEngine; +using UnityEngine.TestTools.TestRunner; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class EditModeRunnerCallback : ScriptableObject, ITestRunnerListener + { + private EditModeLauncherContextSettings m_Settings; + public SceneSetup[] previousSceneSetup; + public int undoGroup; + public EditModeRunner runner; + + private bool m_Canceled; + private ITest m_CurrentTest; + private int m_TotalTests; + + [SerializeField] + private List m_PendingTests; + [SerializeField] + private string m_LastCountedTestName; + [SerializeField] + private bool m_RunRestarted; + + public void OnDestroy() + { + CleanUp(); + } + + public void RunStarted(ITest testsToRun) + { + Setup(); + if (m_PendingTests == null) + { + m_PendingTests = GetTestsExpectedToRun(testsToRun, runner.GetFilter()); + m_TotalTests = m_PendingTests.Count; + } + } + + public void OnEnable() + { + if (m_RunRestarted) + { + Setup(); + } + } + + private void Setup() + { + m_Settings = new EditModeLauncherContextSettings(); + Application.logMessageReceivedThreaded += LogReceived; + EditorApplication.playModeStateChanged += WaitForExitPlaymode; + EditorApplication.update += DisplayProgressBar; + AssemblyReloadEvents.beforeAssemblyReload += BeforeAssemblyReload; + } + + private void BeforeAssemblyReload() + { + if (m_CurrentTest != null) + { + m_LastCountedTestName = m_CurrentTest.FullName; + m_RunRestarted = true; + } + } + + private void DisplayProgressBar() + { + if (m_CurrentTest == null) + return; + if (!m_Canceled && EditorUtility.DisplayCancelableProgressBar("Test Runner", "Running test " + m_CurrentTest.Name, Math.Min(1.0f, (float)(m_TotalTests - m_PendingTests.Count) / m_TotalTests))) + { + EditorApplication.update -= DisplayProgressBar; + m_Canceled = true; + EditorUtility.ClearProgressBar(); + runner.OnRunCancel(); + } + } + + private static void LogReceived(string message, string stacktrace, LogType type) + { + if (TestContext.Out != null) + TestContext.Out.WriteLine(message); + } + + private static void WaitForExitPlaymode(PlayModeStateChange state) + { + if (state == PlayModeStateChange.EnteredEditMode) + { + EditorApplication.playModeStateChanged -= WaitForExitPlaymode; + //because logMessage is reset on Enter EditMode + //we remove and add the callback + //because Unity + Application.logMessageReceivedThreaded -= LogReceived; + Application.logMessageReceivedThreaded += LogReceived; + } + } + + public void RunFinished(ITestResult result) + { + if (previousSceneSetup != null && previousSceneSetup.Length > 0) + { + try + { + EditorSceneManager.RestoreSceneManagerSetup(previousSceneSetup); + } + catch (ArgumentException e) + { + Debug.LogWarning(e.Message); + } + } + else + { + EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Single); + } + CleanUp(); + PerformUndo(undoGroup); + } + + private void CleanUp() + { + m_CurrentTest = null; + EditorUtility.ClearProgressBar(); + if (m_Settings != null) + { + m_Settings.Dispose(); + } + Application.logMessageReceivedThreaded -= LogReceived; + EditorApplication.update -= DisplayProgressBar; + } + + public void TestStarted(ITest test) + { + if (test.IsSuite || !(test is TestMethod)) + { + return; + } + + m_CurrentTest = test; + + if (m_RunRestarted) + { + if (test.FullName == m_LastCountedTestName) + m_RunRestarted = false; + } + } + + public void TestFinished(ITestResult result) + { + if (result.Test is TestMethod) + { + m_PendingTests.Remove(result.Test.FullName); + } + } + + private static void PerformUndo(int undoGroup) + { + EditorUtility.DisplayProgressBar("Undo", "Reverting changes to the scene", 0); + var undoStartTime = DateTime.Now; + Undo.RevertAllDownToGroup(undoGroup); + if ((DateTime.Now - undoStartTime).TotalSeconds > 1) + Debug.LogWarning("Undo after editor test run took " + (DateTime.Now - undoStartTime).Seconds + " seconds."); + EditorUtility.ClearProgressBar(); + } + + private static List GetTestsExpectedToRun(ITest test, ITestFilter filter) + { + var expectedTests = new List(); + + if (filter.Pass(test)) + { + if (test.IsSuite) + { + expectedTests.AddRange(test.Tests.SelectMany(subTest => GetTestsExpectedToRun(subTest, filter))); + } + else + { + expectedTests.Add(test.FullName); + } + } + + return expectedTests; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Callbacks/RerunCallback.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Callbacks/RerunCallback.cs new file mode 100644 index 00000000..0bd60e9d --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Callbacks/RerunCallback.cs @@ -0,0 +1,83 @@ +using UnityEditor.TestTools.TestRunner.Api; +using UnityEditor.TestTools.TestRunner.CommandLineTest; +using UnityEngine.TestTools.TestRunner.GUI; +using UnityEngine; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class RerunCallback : ScriptableObject, ICallbacks + { + public static bool useMockRunFilter = false; + public static TestRunnerFilter mockRunFilter = null; + + public void RunFinished(ITestResultAdaptor result) + { + if (RerunCallbackData.instance.runFilter == null) + RerunCallbackData.instance.runFilter = new TestRunnerFilter(); + + var runFilter = RerunCallbackData.instance.runFilter; + + if (useMockRunFilter) + { + runFilter = mockRunFilter; + } + + runFilter.testRepetitions--; + if (runFilter.testRepetitions <= 0 || result.TestStatus != TestStatus.Passed) + { + ExitCallbacks.preventExit = false; + return; + } + + ExitCallbacks.preventExit = true; + if (EditorApplication.isPlaying) + { + EditorApplication.playModeStateChanged += WaitForExitPlaymode; + return; + } + + if (!useMockRunFilter) + { + ExecuteTestRunnerAPI(); + } + } + + private static void WaitForExitPlaymode(PlayModeStateChange state) + { + if (state == PlayModeStateChange.EnteredEditMode) + { + ExecuteTestRunnerAPI(); + } + } + + private static void ExecuteTestRunnerAPI() + { + var runFilter = RerunCallbackData.instance.runFilter; + var testMode = RerunCallbackData.instance.testMode; + + var testRunnerApi = ScriptableObject.CreateInstance(); + testRunnerApi.Execute(new Api.ExecutionSettings() + { + filter = new Filter() + { + categoryNames = runFilter.categoryNames, + groupNames = runFilter.groupNames, + testMode = testMode, + testNames = runFilter.testNames + } + }); + } + + public void TestStarted(ITestAdaptor test) + { + } + + public void TestFinished(ITestResultAdaptor result) + { + } + + public void RunStarted(ITestAdaptor testsToRun) + { + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Callbacks/RerunCallbackData.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Callbacks/RerunCallbackData.cs new file mode 100644 index 00000000..270a5c5d --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Callbacks/RerunCallbackData.cs @@ -0,0 +1,15 @@ +using UnityEditor.TestTools.TestRunner.Api; +using UnityEngine; +using UnityEngine.TestTools.TestRunner.GUI; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class RerunCallbackData : ScriptableSingleton + { + [SerializeField] + internal TestRunnerFilter runFilter; + + [SerializeField] + internal TestMode testMode; + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Callbacks/RerunCallbackInitializer.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Callbacks/RerunCallbackInitializer.cs new file mode 100644 index 00000000..2260d4da --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Callbacks/RerunCallbackInitializer.cs @@ -0,0 +1,17 @@ +using UnityEngine; +using UnityEditor.TestTools.TestRunner.Api; + +namespace UnityEditor.TestTools.TestRunner +{ + [InitializeOnLoad] + static class RerunCallbackInitializer + { + static RerunCallbackInitializer() + { + var testRunnerApi = ScriptableObject.CreateInstance(); + + var rerunCallback = ScriptableObject.CreateInstance(); + testRunnerApi.RegisterCallbacks(rerunCallback); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Callbacks/TestRunnerCallback.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Callbacks/TestRunnerCallback.cs new file mode 100644 index 00000000..4234754a --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Callbacks/TestRunnerCallback.cs @@ -0,0 +1,37 @@ +using NUnit.Framework.Interfaces; +using UnityEngine; +using UnityEngine.TestTools.TestRunner; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class TestRunnerCallback : ScriptableObject, ITestRunnerListener + { + public void RunStarted(ITest testsToRun) + { + EditorApplication.playModeStateChanged += OnPlayModeStateChanged; + } + + private void OnPlayModeStateChanged(PlayModeStateChange state) + { + if (state == PlayModeStateChange.ExitingPlayMode) + { + EditorApplication.playModeStateChanged -= OnPlayModeStateChanged; + //We need to make sure we don't block NUnit thread in case we exit PlayMode earlier + PlaymodeTestsController.TryCleanup(); + } + } + + public void RunFinished(ITestResult testResults) + { + EditorApplication.isPlaying = false; + } + + public void TestStarted(ITest testName) + { + } + + public void TestFinished(ITestResult test) + { + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Callbacks/WindowResultUpdater.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Callbacks/WindowResultUpdater.cs new file mode 100644 index 00000000..e3f0be06 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Callbacks/WindowResultUpdater.cs @@ -0,0 +1,32 @@ +using UnityEditor.TestTools.TestRunner.Api; + +namespace UnityEditor.TestTools.TestRunner.GUI +{ + internal class WindowResultUpdater : ICallbacks + { + public void RunStarted(ITestAdaptor testsToRun) + { + } + + public void RunFinished(ITestResultAdaptor testResults) + { + if (TestRunnerWindow.s_Instance != null) + { + TestRunnerWindow.s_Instance.RebuildUIFilter(); + } + } + + public void TestStarted(ITestAdaptor testName) + { + } + + public void TestFinished(ITestResultAdaptor test) + { + if (TestRunnerWindow.s_Instance == null) + return; + + var result = new TestRunnerResult(test); + TestRunnerWindow.s_Instance.m_SelectedTestTypes.UpdateResult(result); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/EditModePCHelper.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/EditModePCHelper.cs new file mode 100644 index 00000000..8776887c --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/EditModePCHelper.cs @@ -0,0 +1,32 @@ +using System.Collections; +using System.Reflection; +using UnityEngine.TestTools; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class EditModePcHelper : TestCommandPcHelper + { + public override void SetEnumeratorPC(IEnumerator enumerator, int pc) + { + GetPCFieldInfo(enumerator).SetValue(enumerator, pc); + } + + public override int GetEnumeratorPC(IEnumerator enumerator) + { + if (enumerator == null) + { + return 0; + } + return (int)GetPCFieldInfo(enumerator).GetValue(enumerator); + } + + private FieldInfo GetPCFieldInfo(IEnumerator enumerator) + { + var field = enumerator.GetType().GetField("$PC", BindingFlags.NonPublic | BindingFlags.Instance); + if (field == null) // Roslyn + field = enumerator.GetType().GetField("<>1__state", BindingFlags.NonPublic | BindingFlags.Instance); + + return field; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/EditModeRunner.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/EditModeRunner.cs new file mode 100644 index 00000000..12b4cc7d --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/EditModeRunner.cs @@ -0,0 +1,423 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; +using UnityEngine; +using UnityEngine.TestTools.NUnitExtensions; +using UnityEngine.TestTools.TestRunner; +using UnityEngine.TestTools; +using UnityEngine.TestTools.TestRunner.GUI; +using UnityEditor.Callbacks; +using UnityEngine.TestRunner.NUnitExtensions; +using UnityEngine.TestRunner.NUnitExtensions.Runner; + +namespace UnityEditor.TestTools.TestRunner +{ + internal interface IUnityTestAssemblyRunnerFactory + { + IUnityTestAssemblyRunner Create(TestPlatform testPlatform, WorkItemFactory factory); + } + + internal class UnityTestAssemblyRunnerFactory : IUnityTestAssemblyRunnerFactory + { + public IUnityTestAssemblyRunner Create(TestPlatform testPlatform, WorkItemFactory factory) + { + return new UnityTestAssemblyRunner(new UnityTestAssemblyBuilder(), factory); + } + } + + [Serializable] + internal class EditModeRunner : ScriptableObject, IDisposable + { + [SerializeField] + private TestRunnerFilter m_Filter; + + //The counter from the IEnumerator object + [SerializeField] + private int m_CurrentPC; + + [SerializeField] + private bool m_ExecuteOnEnable; + + [SerializeField] + private List m_AlreadyStartedTests; + + [SerializeField] + private List m_ExecutedTests; + + [SerializeField] + private List m_CallbackObjects = new List(); + + [SerializeField] + private TestStartedEvent m_TestStartedEvent = new TestStartedEvent(); + + [SerializeField] + private TestFinishedEvent m_TestFinishedEvent = new TestFinishedEvent(); + + [SerializeField] + private RunStartedEvent m_RunStartedEvent = new RunStartedEvent(); + + [SerializeField] + private RunFinishedEvent m_RunFinishedEvent = new RunFinishedEvent(); + + [SerializeField] + private TestRunnerStateSerializer m_TestRunnerStateSerializer = new TestRunnerStateSerializer(); + + [SerializeField] + private TestFileCleanupVerifier m_CleanupVerifier = new TestFileCleanupVerifier(); + + [SerializeField] + private bool m_RunningTests; + + [SerializeField] + private TestPlatform m_TestPlatform; + + [SerializeField] + private object m_CurrentYieldObject; + + [SerializeField] + private BeforeAfterTestCommandState m_SetUpTearDownState; + [SerializeField] + private BeforeAfterTestCommandState m_OuterUnityTestActionState; + + internal IUnityTestAssemblyRunner m_Runner; + + private ConstructDelegator m_ConstructDelegator; + + private IEnumerator m_RunStep; + + public IUnityTestAssemblyRunnerFactory UnityTestAssemblyRunnerFactory { get; set; } + + public void Init(TestRunnerFilter filter, TestPlatform platform) + { + m_Filter = filter; + m_TestPlatform = platform; + m_AlreadyStartedTests = new List(); + m_ExecutedTests = new List(); + InitRunner(); + } + + private void InitRunner() + { + //We give the EditMode platform here so we dont suddenly create Playmode work items in the test Runner. + m_Runner = (UnityTestAssemblyRunnerFactory ?? new UnityTestAssemblyRunnerFactory()).Create(TestPlatform.EditMode, new EditmodeWorkItemFactory()); + var testAssemblyProvider = new EditorLoadedTestAssemblyProvider(new EditorCompilationInterfaceProxy(), new EditorAssembliesProxy()); + var loadedTests = m_Runner.Load( + testAssemblyProvider.GetAssembliesGroupedByType(m_TestPlatform).Select(x => x.Assembly).ToArray(), + UnityTestAssemblyBuilder.GetNUnitTestBuilderSettings(m_TestPlatform)); + loadedTests.ParseForNameDuplicates(); + hideFlags |= HideFlags.DontSave; + EnumerableSetUpTearDownCommand.ActivePcHelper = new EditModePcHelper(); + OuterUnityTestActionCommand.ActivePcHelper = new EditModePcHelper(); + } + + public void OnEnable() + { + if (m_ExecuteOnEnable) + { + InitRunner(); + m_ExecuteOnEnable = false; + foreach (var callback in m_CallbackObjects) + { + AddListeners(callback as ITestRunnerListener); + } + m_ConstructDelegator = new ConstructDelegator(m_TestRunnerStateSerializer); + + EnumeratorStepHelper.SetEnumeratorPC(m_CurrentPC); + + UnityWorkItemDataHolder.alreadyExecutedTests = m_ExecutedTests.Select(x => x.fullName).ToList(); + UnityWorkItemDataHolder.alreadyStartedTests = m_AlreadyStartedTests; + Run(); + } + } + + public void TestStartedEvent(ITest test) + { + m_AlreadyStartedTests.Add(test.FullName); + } + + public void TestFinishedEvent(ITestResult testResult) + { + m_AlreadyStartedTests.Remove(testResult.FullName); + m_ExecutedTests.Add(TestResultSerializer.MakeFromTestResult(testResult)); + } + + public void Run() + { + EditModeTestCallbacks.RestoringTestContext += OnRestoringTest; + var context = m_Runner.GetCurrentContext(); + if (m_SetUpTearDownState == null) + { + m_SetUpTearDownState = CreateInstance(); + } + context.SetUpTearDownState = m_SetUpTearDownState; + + if (m_OuterUnityTestActionState == null) + { + m_OuterUnityTestActionState = CreateInstance(); + } + context.OuterUnityTestActionState = m_OuterUnityTestActionState; + + m_CleanupVerifier.RegisterExistingFiles(); + + if (!m_RunningTests) + { + m_RunStartedEvent.Invoke(m_Runner.LoadedTest); + } + + if (m_ConstructDelegator == null) + m_ConstructDelegator = new ConstructDelegator(m_TestRunnerStateSerializer); + + Reflect.ConstructorCallWrapper = m_ConstructDelegator.Delegate; + m_TestStartedEvent.AddListener(TestStartedEvent); + m_TestFinishedEvent.AddListener(TestFinishedEvent); + + AssemblyReloadEvents.beforeAssemblyReload += OnBeforeAssemblyReload; + + RunningTests = true; + + EditorApplication.LockReloadAssemblies(); + + var testListenerWrapper = new TestListenerWrapper(m_TestStartedEvent, m_TestFinishedEvent); + m_RunStep = m_Runner.Run(testListenerWrapper, m_Filter.BuildNUnitFilter()).GetEnumerator(); + m_RunningTests = true; + + EditorApplication.update += TestConsumer; + } + + private void OnBeforeAssemblyReload() + { + EditorApplication.update -= TestConsumer; + + if (m_ExecuteOnEnable) + { + AssemblyReloadEvents.beforeAssemblyReload -= OnBeforeAssemblyReload; + return; + } + + if (m_Runner != null && m_Runner.TopLevelWorkItem != null) + m_Runner.TopLevelWorkItem.ResultedInDomainReload = true; + + if (RunningTests) + { + Debug.LogError("TestRunner: Unexpected assembly reload happened while running tests"); + + EditorUtility.ClearProgressBar(); + + if (m_Runner.GetCurrentContext() != null && m_Runner.GetCurrentContext().CurrentResult != null) + { + m_Runner.GetCurrentContext().CurrentResult.SetResult(ResultState.Cancelled, "Unexpected assembly reload happened"); + } + OnRunCancel(); + } + } + + private bool RunningTests; + + private Stack StepStack = new Stack(); + + private bool MoveNextAndUpdateYieldObject() + { + var result = m_RunStep.MoveNext(); + + if (result) + { + m_CurrentYieldObject = m_RunStep.Current; + while (m_CurrentYieldObject is IEnumerator) // going deeper + { + var currentEnumerator = (IEnumerator)m_CurrentYieldObject; + + // go deeper and add parent to stack + StepStack.Push(m_RunStep); + + m_RunStep = currentEnumerator; + m_CurrentYieldObject = m_RunStep.Current; + } + + if (StepStack.Count > 0 && m_CurrentYieldObject != null) // not null and not IEnumerator, nested + { + Debug.LogError("EditMode test can only yield null, but not <" + m_CurrentYieldObject.GetType().Name + ">"); + } + + return true; + } + + if (StepStack.Count == 0) // done + return false; + + m_RunStep = StepStack.Pop(); // going up + return MoveNextAndUpdateYieldObject(); + } + + private void TestConsumer() + { + var moveNext = MoveNextAndUpdateYieldObject(); + + if (m_CurrentYieldObject != null) + { + InvokeDelegator(); + } + + if (!moveNext && !m_Runner.IsTestComplete) + { + CompleteTestRun(); + throw new IndexOutOfRangeException("There are no more elements to process and IsTestComplete is false"); + } + + if (m_Runner.IsTestComplete) + { + CompleteTestRun(); + } + } + + private void CompleteTestRun() + { + EditorApplication.update -= TestConsumer; + TestLauncherBase.ExecutePostBuildCleanupMethods(this.GetLoadedTests(), this.GetFilter(), Application.platform); + m_CleanupVerifier.VerifyNoNewFilesAdded(); + m_RunFinishedEvent.Invoke(m_Runner.Result); + + if (m_ConstructDelegator != null) + m_ConstructDelegator.DestroyCurrentTestObjectIfExists(); + Dispose(); + UnityWorkItemDataHolder.alreadyExecutedTests = null; + } + + private void OnRestoringTest() + { + var item = m_ExecutedTests.Find(t => t.fullName == UnityTestExecutionContext.CurrentContext.CurrentTest.FullName); + if (item != null) + { + item.RestoreTestResult(UnityTestExecutionContext.CurrentContext.CurrentResult); + } + } + + private static bool IsCancelled() + { + return UnityTestExecutionContext.CurrentContext.ExecutionStatus == TestExecutionStatus.AbortRequested || UnityTestExecutionContext.CurrentContext.ExecutionStatus == TestExecutionStatus.StopRequested; + } + + private void InvokeDelegator() + { + if (m_CurrentYieldObject == null) + { + return; + } + + if (IsCancelled()) + { + return; + } + + if (m_CurrentYieldObject is RestoreTestContextAfterDomainReload) + { + if (m_TestRunnerStateSerializer.ShouldRestore()) + { + m_TestRunnerStateSerializer.RestoreContext(); + } + + return; + } + + try + { + if (m_CurrentYieldObject is IEditModeTestYieldInstruction) + { + var editModeTestYieldInstruction = (IEditModeTestYieldInstruction)m_CurrentYieldObject; + if (editModeTestYieldInstruction.ExpectDomainReload) + { + PrepareForDomainReload(); + } + return; + } + } + catch (Exception e) + { + UnityTestExecutionContext.CurrentContext.CurrentResult.RecordException(e); + return; + } + + Debug.LogError("EditMode test can only yield null"); + } + + private void CompilationFailureWatch() + { + if (EditorApplication.isCompiling) + return; + + EditorApplication.update -= CompilationFailureWatch; + + if (EditorUtility.scriptCompilationFailed) + { + EditorUtility.ClearProgressBar(); + OnRunCancel(); + } + } + + private void PrepareForDomainReload() + { + m_TestRunnerStateSerializer.SaveContext(); + m_CurrentPC = EnumeratorStepHelper.GetEnumeratorPC(TestEnumerator.Enumerator); + m_ExecuteOnEnable = true; + + RunningTests = false; + } + + public T AddEventHandler() where T : ScriptableObject, ITestRunnerListener + { + var eventHandler = CreateInstance(); + eventHandler.hideFlags |= HideFlags.DontSave; + m_CallbackObjects.Add(eventHandler); + + AddListeners(eventHandler); + + return eventHandler; + } + + private void AddListeners(ITestRunnerListener eventHandler) + { + m_TestStartedEvent.AddListener(eventHandler.TestStarted); + m_TestFinishedEvent.AddListener(eventHandler.TestFinished); + m_RunStartedEvent.AddListener(eventHandler.RunStarted); + m_RunFinishedEvent.AddListener(eventHandler.RunFinished); + } + + public void Dispose() + { + Reflect.MethodCallWrapper = null; + EditorApplication.update -= TestConsumer; + + DestroyImmediate(this); + + if (m_CallbackObjects != null) + { + foreach (var obj in m_CallbackObjects) + { + DestroyImmediate(obj); + } + m_CallbackObjects.Clear(); + } + RunningTests = false; + EditorApplication.UnlockReloadAssemblies(); + } + + public void OnRunCancel() + { + UnityWorkItemDataHolder.alreadyExecutedTests = null; + m_ExecuteOnEnable = false; + m_Runner.StopRun(); + } + + public ITest GetLoadedTests() + { + return m_Runner.LoadedTest; + } + + public ITestFilter GetFilter() + { + return m_Filter.BuildNUnitFilter(); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/EditmodeWorkItemFactory.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/EditmodeWorkItemFactory.cs new file mode 100644 index 00000000..c2bf9212 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/EditmodeWorkItemFactory.cs @@ -0,0 +1,14 @@ +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; +using UnityEngine.TestRunner.NUnitExtensions.Runner; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class EditmodeWorkItemFactory : WorkItemFactory + { + protected override UnityWorkItem Create(TestMethod method, ITestFilter filter, ITest loadedTest) + { + return new EditorEnumeratorTestWorkItem(method, filter); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/EditorEnumeratorTestWorkItem.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/EditorEnumeratorTestWorkItem.cs new file mode 100644 index 00000000..90353a20 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/EditorEnumeratorTestWorkItem.cs @@ -0,0 +1,181 @@ +using System; +using System.Collections; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; +using NUnit.Framework.Internal.Commands; +using NUnit.Framework.Internal.Execution; +using UnityEngine; +using UnityEngine.TestRunner.NUnitExtensions.Runner; +using UnityEngine.TestTools; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class EditorEnumeratorTestWorkItem : UnityWorkItem + { + private TestCommand m_Command; + + public EditorEnumeratorTestWorkItem(TestMethod test, ITestFilter filter) + : base(test, null) + { + m_Command = test.RunState == RunState.Runnable || test.RunState == RunState.Explicit && filter.IsExplicitMatch(test) + ? CommandBuilder.MakeTestCommand(test) + : CommandBuilder.MakeSkipCommand(test); + } + + private static IEnumerableTestMethodCommand FindFirstIEnumerableTestMethodCommand(TestCommand command) + { + if (command == null) + { + return null; + } + + if (command is IEnumerableTestMethodCommand) + { + return (IEnumerableTestMethodCommand)command; + } + + if (command is DelegatingTestCommand) + { + var delegatingTestCommand = (DelegatingTestCommand)command; + return FindFirstIEnumerableTestMethodCommand(delegatingTestCommand.GetInnerCommand()); + } + return null; + } + + protected override IEnumerable PerformWork() + { + if (IsCancelledRun()) + { + yield break; + } + + if (m_DontRunRestoringResult) + { + if (EditModeTestCallbacks.RestoringTestContext == null) + { + throw new NullReferenceException("RestoringTestContext is not set"); + } + EditModeTestCallbacks.RestoringTestContext(); + Result = Context.CurrentResult; + yield break; + } + + try + { + if (IsCancelledRun()) + { + yield break; + } + + if (m_Command is SkipCommand) + { + m_Command.Execute(Context); + Result = Context.CurrentResult; + yield break; + } + + //Check if we can execute this test + var firstEnumerableCommand = FindFirstIEnumerableTestMethodCommand(m_Command); + if (firstEnumerableCommand == null) + { + Context.CurrentResult.SetResult(ResultState.Error, "Returning IEnumerator but not using test attribute supporting this"); + yield break; + } + + if (m_Command.Test.Method.ReturnType.IsType(typeof(IEnumerator))) + { + if (m_Command is ApplyChangesToContextCommand) + { + var applyChangesToContextCommand = ((ApplyChangesToContextCommand)m_Command); + applyChangesToContextCommand.ApplyChanges(Context); + m_Command = applyChangesToContextCommand.GetInnerCommand(); + } + + var innerCommand = (IEnumerableTestMethodCommand)m_Command; + if (innerCommand == null) + { + Debug.Log("failed getting innerCommand"); + throw new Exception("Tests returning IEnumerator can only use test attributes handling those"); + } + + foreach (var workItemStep in innerCommand.ExecuteEnumerable(Context)) + { + if (IsCancelledRun()) + { + yield break; + } + + if (workItemStep is TestEnumerator) + { + if (EnumeratorStepHelper.UpdateEnumeratorPcIfNeeded(TestEnumerator.Enumerator)) + { + yield return new RestoreTestContextAfterDomainReload(); + } + continue; + } + + if (workItemStep is AsyncOperation) + { + var asyncOperation = (AsyncOperation)workItemStep; + while (!asyncOperation.isDone) + { + if (IsCancelledRun()) + { + yield break; + } + + yield return null; + } + continue; + } + + ResultedInDomainReload = false; + + if (workItemStep is IEditModeTestYieldInstruction) + { + var editModeTestYieldInstruction = (IEditModeTestYieldInstruction)workItemStep; + yield return editModeTestYieldInstruction; + var enumerator = editModeTestYieldInstruction.Perform(); + while (true) + { + bool moveNext; + try + { + moveNext = enumerator.MoveNext(); + } + catch (Exception e) + { + Context.CurrentResult.RecordException(e); + break; + } + + if (!moveNext) + { + break; + } + yield return null; + } + } + else + { + yield return workItemStep; + } + } + + Result = Context.CurrentResult; + EditorApplication.isPlaying = false; + yield return null; + } + } + finally + { + WorkItemComplete(); + } + } + + private bool IsCancelledRun() + { + return Context.ExecutionStatus == TestExecutionStatus.AbortRequested || Context.ExecutionStatus == TestExecutionStatus.StopRequested; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/EnumeratorStepHelper.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/EnumeratorStepHelper.cs new file mode 100644 index 00000000..98eeda86 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/EnumeratorStepHelper.cs @@ -0,0 +1,51 @@ +using System.Collections; +using System.Reflection; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class EnumeratorStepHelper + { + private static int m_PC; + + public static void SetEnumeratorPC(int pc) + { + m_PC = pc; + } + + /// + /// Gets the current enumerator PC + /// + /// + /// The PC + /// 0 if no current Enumeration + /// + public static int GetEnumeratorPC(IEnumerator enumerator) + { + if (enumerator == null) + { + return 0; + } + return (int)GetPCFieldInfo(enumerator).GetValue(enumerator); + } + + public static bool UpdateEnumeratorPcIfNeeded(IEnumerator enumerator) + { + if (m_PC > 0) + { + GetPCFieldInfo(enumerator).SetValue(enumerator, m_PC); + m_PC = 0; + return true; + } + return false; + } + + private static FieldInfo GetPCFieldInfo(IEnumerator enumerator) + { + var field = enumerator.GetType().GetField("$PC", BindingFlags.NonPublic | BindingFlags.Instance); + if (field == null) // Roslyn + field = enumerator.GetType().GetField("<>1__state", BindingFlags.NonPublic | BindingFlags.Instance); + + return field; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Messages/EnterPlayMode.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Messages/EnterPlayMode.cs new file mode 100644 index 00000000..796c531d --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Messages/EnterPlayMode.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections; +using UnityEditor; + +namespace UnityEngine.TestTools +{ + public class EnterPlayMode : IEditModeTestYieldInstruction + { + public bool ExpectDomainReload { get; } + public bool ExpectedPlaymodeState { get; private set; } + + public EnterPlayMode(bool expectDomainReload = true) + { + ExpectDomainReload = expectDomainReload; + } + + public IEnumerator Perform() + { + if (EditorApplication.isPlaying) + { + throw new Exception("Editor is already in PlayMode"); + } + if (EditorUtility.scriptCompilationFailed) + { + throw new Exception("Script compilation failed"); + } + yield return null; + ExpectedPlaymodeState = true; + + EditorApplication.UnlockReloadAssemblies(); + EditorApplication.isPlaying = true; + + while (!EditorApplication.isPlaying) + { + yield return null; + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Messages/ExitPlayMode.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Messages/ExitPlayMode.cs new file mode 100644 index 00000000..2eed28ba --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Messages/ExitPlayMode.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections; +using UnityEditor; + +namespace UnityEngine.TestTools +{ + public class ExitPlayMode : IEditModeTestYieldInstruction + { + public bool ExpectDomainReload { get; } + public bool ExpectedPlaymodeState { get; private set; } + + public ExitPlayMode() + { + ExpectDomainReload = false; + ExpectedPlaymodeState = false; + } + + public IEnumerator Perform() + { + if (!EditorApplication.isPlayingOrWillChangePlaymode) + { + throw new Exception("Editor is already in EditMode"); + } + + EditorApplication.isPlaying = false; + while (EditorApplication.isPlaying) + { + yield return null; + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Messages/RecompileScripts.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Messages/RecompileScripts.cs new file mode 100644 index 00000000..cd15bf3f --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Messages/RecompileScripts.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections; +using UnityEditor; + +namespace UnityEngine.TestTools +{ + internal class RecompileScripts : IEditModeTestYieldInstruction + { + public RecompileScripts() : this(true) + { + } + + public RecompileScripts(bool expectScriptCompilation) : this(expectScriptCompilation, true) + { + } + + public RecompileScripts(bool expectScriptCompilation, bool expectScriptCompilationSuccess) + { + ExpectScriptCompilation = expectScriptCompilation; + ExpectScriptCompilationSuccess = expectScriptCompilationSuccess; + ExpectDomainReload = true; + } + + public bool ExpectDomainReload { get; private set; } + public bool ExpectedPlaymodeState { get; } + public bool ExpectScriptCompilation { get; private set; } + public bool ExpectScriptCompilationSuccess { get; private set; } + public static RecompileScripts Current { get; private set; } + + public IEnumerator Perform() + { + Current = this; + + // We need to yield, to give the test runner a chance to prepare for the domain reload + // If the script compilation happens very fast, then EditModeRunner.MoveNextAndUpdateYieldObject will not have a chance to set m_CurrentYieldObject + // This really should be fixed in EditModeRunner.MoveNextAndUpdateYieldObject + yield return null; + + AssetDatabase.Refresh(); + + if (ExpectScriptCompilation && !EditorApplication.isCompiling) + { + Current = null; + throw new Exception("Editor does not need to recompile scripts"); + } + + EditorApplication.UnlockReloadAssemblies(); + + while (EditorApplication.isCompiling) + { + yield return null; + } + + Current = null; + + if (ExpectScriptCompilationSuccess && EditorUtility.scriptCompilationFailed) + { + EditorApplication.LockReloadAssemblies(); + throw new Exception("Script compilation failed"); + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Messages/WaitForDomainReload.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Messages/WaitForDomainReload.cs new file mode 100644 index 00000000..be5534bb --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Messages/WaitForDomainReload.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections; +using UnityEditor; + +namespace UnityEngine.TestTools +{ + internal class WaitForDomainReload : IEditModeTestYieldInstruction + { + public WaitForDomainReload() + { + ExpectDomainReload = true; + } + + public bool ExpectDomainReload { get;  } + public bool ExpectedPlaymodeState { get; } + + public IEnumerator Perform() + { + EditorApplication.UnlockReloadAssemblies(); + + // Detect if AssetDatabase.Refresh was called (true) or if it will be called on next tick + bool isAsync = EditorApplication.isCompiling; + + yield return null; + + if (!isAsync) + { + EditorApplication.LockReloadAssemblies(); + throw new Exception("Expected domain reload, but it did not occur"); + } + + while (EditorApplication.isCompiling) + { + yield return null; + } + + if (EditorUtility.scriptCompilationFailed) + { + EditorApplication.LockReloadAssemblies(); + throw new Exception("Script compilation failed"); + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/TestFileCleanupVerifier.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/TestFileCleanupVerifier.cs new file mode 100644 index 00000000..45417cd6 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/TestFileCleanupVerifier.cs @@ -0,0 +1,98 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using UnityEngine; + +namespace UnityEditor.TestTools.TestRunner +{ + [Serializable] + internal class TestFileCleanupVerifier + { + const string k_Indent = " "; + + [SerializeField] + List m_ExistingFiles; + + [SerializeField] + bool m_ExistingFilesScanned; + + public Action logAction = Debug.LogWarning; + + private Func getAllAssetPathsAction; + public Func GetAllAssetPathsAction + { + get + { + if (getAllAssetPathsAction != null) + { + return getAllAssetPathsAction; + } + return AssetDatabase.GetAllAssetPaths; + } + set + { + getAllAssetPathsAction = value; + } + } + + public void RegisterExistingFiles() + { + if (m_ExistingFilesScanned) + { + return; + } + + m_ExistingFiles = GetAllFilesInAssetsDirectory().ToList(); + m_ExistingFilesScanned = true; + } + + public void VerifyNoNewFilesAdded() + { + var currentFiles = GetAllFilesInAssetsDirectory().ToList(); + + //Expect that if its the same amount of files, there havent been any changes + //This is to optimize if there are many files + if (currentFiles.Count != m_ExistingFiles.Count) + { + LogWarningForFilesIfAny(currentFiles.Except(m_ExistingFiles)); + } + } + + void LogWarningForFilesIfAny(IEnumerable filePaths) + { + if (!filePaths.Any()) + { + return; + } + + var stringWriter = new StringWriter(); + stringWriter.WriteLine("Files generated by test without cleanup."); + stringWriter.WriteLine(k_Indent + "Found {0} new files.", filePaths.Count()); + + foreach (var filePath in filePaths) + { + stringWriter.WriteLine(k_Indent + filePath); + } + + LogAction(stringWriter.ToString()); + } + + private void LogAction(object obj) + { + if (this.logAction != null) + { + this.logAction(obj); + } + else + { + Debug.LogWarning(obj); + } + } + + private IEnumerable GetAllFilesInAssetsDirectory() + { + return GetAllAssetPathsAction(); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Utils/CachingTestListProvider.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Utils/CachingTestListProvider.cs new file mode 100644 index 00000000..ff540e67 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Utils/CachingTestListProvider.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using UnityEditor.TestTools.TestRunner.Api; +using UnityEngine.TestRunner.NUnitExtensions; +using UnityEngine.TestTools; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class CachingTestListProvider + { + private readonly ITestListProvider m_InnerTestListProvider; + private readonly ITestListCache m_TestListCache; + private readonly ITestAdaptorFactory m_TestAdaptorFactory; + public CachingTestListProvider(ITestListProvider innerTestListProvider, ITestListCache testListCache, ITestAdaptorFactory testAdaptorFactory) + { + m_InnerTestListProvider = innerTestListProvider; + m_TestListCache = testListCache; + m_TestAdaptorFactory = testAdaptorFactory; + } + + public IEnumerator GetTestListAsync(TestPlatform platform) + { + var testFromCache = m_TestListCache.GetTestFromCacheAsync(platform); + while (testFromCache.MoveNext()) + { + yield return null; + } + + + if (testFromCache.Current != null) + { + yield return testFromCache.Current; + } + else + { + var test = m_InnerTestListProvider.GetTestListAsync(platform); + while (test.MoveNext()) + { + yield return null; + } + + test.Current.ParseForNameDuplicates(); + m_TestListCache.CacheTest(platform, test.Current); + yield return m_TestAdaptorFactory.Create(test.Current); + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Utils/EditorAssembliesProxy.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Utils/EditorAssembliesProxy.cs new file mode 100644 index 00000000..56826194 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Utils/EditorAssembliesProxy.cs @@ -0,0 +1,13 @@ +using System.Linq; +using UnityEngine.TestTools.Utils; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class EditorAssembliesProxy : IEditorAssembliesProxy + { + public IAssemblyWrapper[] loadedAssemblies + { + get { return EditorAssemblies.loadedAssemblies.Select(x => new EditorAssemblyWrapper(x)).ToArray(); } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Utils/EditorAssemblyWrapper.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Utils/EditorAssemblyWrapper.cs new file mode 100644 index 00000000..804eb4b1 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Utils/EditorAssemblyWrapper.cs @@ -0,0 +1,18 @@ +using System.Reflection; +using UnityEngine.TestTools.Utils; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class EditorAssemblyWrapper : AssemblyWrapper + { + public EditorAssemblyWrapper(Assembly assembly) + : base(assembly) {} + + public override AssemblyName[] GetReferencedAssemblies() + { + return Assembly.GetReferencedAssemblies(); + } + + public override string Location { get { return Assembly.Location; } } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Utils/EditorCompilationInterfaceProxy.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Utils/EditorCompilationInterfaceProxy.cs new file mode 100644 index 00000000..ad0b5ad5 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Utils/EditorCompilationInterfaceProxy.cs @@ -0,0 +1,17 @@ +using UnityEditor.Scripting.ScriptCompilation; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class EditorCompilationInterfaceProxy : IEditorCompilationInterfaceProxy + { + public ScriptAssembly[] GetAllEditorScriptAssemblies() + { + return EditorCompilationInterface.Instance.GetAllEditorScriptAssemblies(EditorCompilationInterface.GetAdditionalEditorScriptCompilationOptions()); + } + + public PrecompiledAssembly[] GetAllPrecompiledAssemblies() + { + return EditorCompilationInterface.Instance.GetAllPrecompiledAssemblies(); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Utils/EditorLoadedTestAssemblyProvider.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Utils/EditorLoadedTestAssemblyProvider.cs new file mode 100644 index 00000000..6d8cc0e6 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Utils/EditorLoadedTestAssemblyProvider.cs @@ -0,0 +1,69 @@ +using System.Collections.Generic; +using System.IO; +using System.Linq; +using UnityEditor.Scripting.ScriptCompilation; +using UnityEngine.TestTools; +using UnityEngine.TestTools.Utils; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class EditorLoadedTestAssemblyProvider + { + private const string k_NunitAssemblyName = "nunit.framework"; + private const string k_TestRunnerAssemblyName = "UnityEngine.TestRunner"; + internal const string k_PerformanceTestingAssemblyName = "Unity.PerformanceTesting"; + + private readonly IEditorAssembliesProxy m_EditorAssembliesProxy; + private readonly ScriptAssembly[] m_AllEditorScriptAssemblies; + private readonly PrecompiledAssembly[] m_AllPrecompiledAssemblies; + + public EditorLoadedTestAssemblyProvider(IEditorCompilationInterfaceProxy compilationInterfaceProxy, IEditorAssembliesProxy editorAssembliesProxy) + { + m_EditorAssembliesProxy = editorAssembliesProxy; + m_AllEditorScriptAssemblies = compilationInterfaceProxy.GetAllEditorScriptAssemblies(); + m_AllPrecompiledAssemblies = compilationInterfaceProxy.GetAllPrecompiledAssemblies(); + } + + public List GetAssembliesGroupedByType(TestPlatform mode) + { + var assemblies = GetAssembliesGroupedByTypeAsync(mode); + while (assemblies.MoveNext()) + { + } + + return assemblies.Current; + } + + public IEnumerator> GetAssembliesGroupedByTypeAsync(TestPlatform mode) + { + IAssemblyWrapper[] loadedAssemblies = m_EditorAssembliesProxy.loadedAssemblies; + + IDictionary> result = new Dictionary>() + { + {TestPlatform.EditMode, new List() }, + {TestPlatform.PlayMode, new List() } + }; + + foreach (var loadedAssembly in loadedAssemblies) + { + if (loadedAssembly.GetReferencedAssemblies().Any(x => x.Name == k_NunitAssemblyName || x.Name == k_TestRunnerAssemblyName || x.Name == k_PerformanceTestingAssemblyName)) + { + var assemblyName = new FileInfo(loadedAssembly.Location).Name; + var scriptAssemblies = m_AllEditorScriptAssemblies.Where(x => x.Filename == assemblyName).ToList(); + var precompiledAssemblies = m_AllPrecompiledAssemblies.Where(x => new FileInfo(x.Path).Name == assemblyName).ToList(); + if (scriptAssemblies.Count < 1 && precompiledAssemblies.Count < 1) + { + continue; + } + + var assemblyFlags = scriptAssemblies.Any() ? scriptAssemblies.Single().Flags : precompiledAssemblies.Single().Flags; + var assemblyType = (assemblyFlags & AssemblyFlags.EditorOnly) == AssemblyFlags.EditorOnly ? TestPlatform.EditMode : TestPlatform.PlayMode; + result[assemblyType].Add(loadedAssembly); + yield return null; + } + } + + yield return result[mode]; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Utils/IEditorAssembliesProxy.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Utils/IEditorAssembliesProxy.cs new file mode 100644 index 00000000..35ec87d0 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Utils/IEditorAssembliesProxy.cs @@ -0,0 +1,9 @@ +using UnityEngine.TestTools.Utils; + +namespace UnityEditor.TestTools.TestRunner +{ + internal interface IEditorAssembliesProxy + { + IAssemblyWrapper[] loadedAssemblies { get; } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Utils/IEditorCompilationInterfaceProxy.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Utils/IEditorCompilationInterfaceProxy.cs new file mode 100644 index 00000000..25defb78 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Utils/IEditorCompilationInterfaceProxy.cs @@ -0,0 +1,10 @@ +using UnityEditor.Scripting.ScriptCompilation; + +namespace UnityEditor.TestTools.TestRunner +{ + internal interface IEditorCompilationInterfaceProxy + { + ScriptAssembly[] GetAllEditorScriptAssemblies(); + PrecompiledAssembly[] GetAllPrecompiledAssemblies(); + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Utils/ITestListCache.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Utils/ITestListCache.cs new file mode 100644 index 00000000..5df7a784 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Utils/ITestListCache.cs @@ -0,0 +1,13 @@ +using System.Collections.Generic; +using NUnit.Framework.Interfaces; +using UnityEditor.TestTools.TestRunner.Api; +using UnityEngine.TestTools; + +namespace UnityEditor.TestTools.TestRunner +{ + interface ITestListCache + { + void CacheTest(TestPlatform platform, ITest test); + IEnumerator GetTestFromCacheAsync(TestPlatform platform); + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Utils/ITestListCacheData.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Utils/ITestListCacheData.cs new file mode 100644 index 00000000..c93762d9 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Utils/ITestListCacheData.cs @@ -0,0 +1,12 @@ +using System.Collections.Generic; +using UnityEngine.TestRunner.TestLaunchers; +using UnityEngine.TestTools; + +namespace UnityEditor.TestTools.TestRunner +{ + interface ITestListCacheData + { + List platforms { get; } + List cachedData { get; } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Utils/ITestListProvider.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Utils/ITestListProvider.cs new file mode 100644 index 00000000..b734f536 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Utils/ITestListProvider.cs @@ -0,0 +1,11 @@ +using System.Collections.Generic; +using NUnit.Framework.Interfaces; +using UnityEngine.TestTools; + +namespace UnityEditor.TestTools.TestRunner +{ + interface ITestListProvider + { + IEnumerator GetTestListAsync(TestPlatform platform); + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Utils/TestListCache.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Utils/TestListCache.cs new file mode 100644 index 00000000..6f48c9c8 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Utils/TestListCache.cs @@ -0,0 +1,64 @@ +using System.Collections.Generic; +using NUnit.Framework.Interfaces; +using UnityEditor.TestTools.TestRunner.Api; +using UnityEngine.TestRunner.TestLaunchers; +using UnityEngine.TestTools; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class TestListCache : ITestListCache + { + private readonly ITestAdaptorFactory m_TestAdaptorFactory; + private readonly IRemoteTestResultDataFactory m_TestResultDataFactory; + private readonly ITestListCacheData m_TestListCacheData; + + public TestListCache(ITestAdaptorFactory testAdaptorFactory, IRemoteTestResultDataFactory testResultDataFactory, ITestListCacheData testListCacheData) + { + m_TestAdaptorFactory = testAdaptorFactory; + m_TestResultDataFactory = testResultDataFactory; + m_TestListCacheData = testListCacheData; + } + + public void CacheTest(TestPlatform platform, ITest test) + { + var data = m_TestResultDataFactory.CreateFromTest(test); + + var index = m_TestListCacheData.platforms.IndexOf(platform); + if (index < 0) + { + m_TestListCacheData.cachedData.Add(data); + m_TestListCacheData.platforms.Add(platform); + } + else + { + m_TestListCacheData.cachedData[index] = data; + } + } + + public IEnumerator GetTestFromCacheAsync(TestPlatform platform) + { + var index = m_TestListCacheData.platforms.IndexOf(platform); + if (index < 0) + { + yield return null; + yield break; + } + + var testData = m_TestListCacheData.cachedData[index]; + var test = m_TestAdaptorFactory.BuildTreeAsync(testData); + while (test.MoveNext()) + { + yield return null; + } + + yield return test.Current; + } + + [Callbacks.DidReloadScripts] + private static void ScriptReloaded() + { + TestListCacheData.instance.cachedData.Clear(); + TestListCacheData.instance.platforms.Clear(); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Utils/TestListCacheData.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Utils/TestListCacheData.cs new file mode 100644 index 00000000..58acbc0b --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Utils/TestListCacheData.cs @@ -0,0 +1,26 @@ +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.TestRunner.TestLaunchers; +using UnityEngine.TestTools; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class TestListCacheData : ScriptableSingleton, ITestListCacheData + { + [SerializeField] + private List m_Platforms = new List(); + + [SerializeField] + private List m_CachedData = new List(); + + public List platforms + { + get { return m_Platforms; } + } + + public List cachedData + { + get { return m_CachedData; } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Utils/TestListJob.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Utils/TestListJob.cs new file mode 100644 index 00000000..0df60c35 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Utils/TestListJob.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using UnityEditor.TestTools.TestRunner.Api; +using UnityEngine.TestTools; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class TestListJob + { + private CachingTestListProvider m_TestListProvider; + private TestPlatform m_Platform; + private Action m_Callback; + private IEnumerator m_ResultEnumerator; + public TestListJob(CachingTestListProvider testListProvider, TestPlatform platform, Action callback) + { + m_TestListProvider = testListProvider; + m_Platform = platform; + m_Callback = callback; + } + + public void Start() + { + m_ResultEnumerator = m_TestListProvider.GetTestListAsync(m_Platform); + EditorApplication.update += EditorUpdate; + } + + private void EditorUpdate() + { + if (!m_ResultEnumerator.MoveNext()) + { + m_Callback(m_ResultEnumerator.Current); + EditorApplication.update -= EditorUpdate; + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Utils/TestListProvider.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Utils/TestListProvider.cs new file mode 100644 index 00000000..f7d9a82c --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunner/Utils/TestListProvider.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using NUnit.Framework.Interfaces; +using UnityEngine.TestTools; +using UnityEngine.TestTools.NUnitExtensions; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class TestListProvider : ITestListProvider + { + private readonly EditorLoadedTestAssemblyProvider m_AssemblyProvider; + private readonly UnityTestAssemblyBuilder m_AssemblyBuilder; + + public TestListProvider(EditorLoadedTestAssemblyProvider assemblyProvider, UnityTestAssemblyBuilder assemblyBuilder) + { + m_AssemblyProvider = assemblyProvider; + m_AssemblyBuilder = assemblyBuilder; + } + + public IEnumerator GetTestListAsync(TestPlatform platform) + { + var assemblies = m_AssemblyProvider.GetAssembliesGroupedByTypeAsync(platform); + while (assemblies.MoveNext()) + { + yield return null; + } + + var settings = UnityTestAssemblyBuilder.GetNUnitTestBuilderSettings(platform); + var test = m_AssemblyBuilder.BuildAsync(assemblies.Current.Select(x => x.Assembly).ToArray(), settings); + while (test.MoveNext()) + { + yield return null; + } + + yield return test.Current; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunnerWindow.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunnerWindow.cs new file mode 100644 index 00000000..a591508a --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunnerWindow.cs @@ -0,0 +1,274 @@ +using System; +using UnityEditor.Callbacks; +using UnityEditor.TestTools.TestRunner.Api; +using UnityEditor.TestTools.TestRunner.GUI; +using UnityEngine; + +namespace UnityEditor.TestTools.TestRunner +{ + [Serializable] + internal class TestRunnerWindow : EditorWindow, IHasCustomMenu + { + internal static class Styles + { + public static GUIStyle info; + public static GUIStyle testList; + + static Styles() + { + info = new GUIStyle(EditorStyles.wordWrappedLabel); + info.wordWrap = false; + info.stretchHeight = true; + info.margin.right = 15; + + testList = new GUIStyle("CN Box"); + testList.margin.top = 0; + testList.padding.left = 3; + } + } + + private readonly GUIContent m_GUIHorizontalSplit = EditorGUIUtility.TrTextContent("Horizontal layout"); + private readonly GUIContent m_GUIVerticalSplit = EditorGUIUtility.TrTextContent("Vertical layout"); + private readonly GUIContent m_GUIEnableaPlaymodeTestsRunner = EditorGUIUtility.TrTextContent("Enable playmode tests for all assemblies"); + private readonly GUIContent m_GUIDisablePlaymodeTestsRunner = EditorGUIUtility.TrTextContent("Disable playmode tests for all assemblies"); + private readonly GUIContent m_GUIRunPlayModeTestAsEditModeTests = EditorGUIUtility.TrTextContent("Run playmode tests as editmode tests"); + + internal static TestRunnerWindow s_Instance; + private bool m_IsBuilding; + [NonSerialized] + private bool m_Enabled; + public TestFilterSettings filterSettings; + + private readonly SplitterState m_Spl = new SplitterState(new float[] { 75, 25 }, new[] { 32, 32 }, null); + + private TestRunnerWindowSettings m_Settings; + + private enum TestRunnerMenuLabels + { + PlayMode = 0, + EditMode = 1 + } + [SerializeField] + private int m_TestTypeToolbarIndex = (int)TestRunnerMenuLabels.EditMode; + [SerializeField] + private PlayModeTestListGUI m_PlayModeTestListGUI; + [SerializeField] + private EditModeTestListGUI m_EditModeTestListGUI; + + internal TestListGUI m_SelectedTestTypes; + + private ITestRunnerApi m_testRunnerApi; + + private WindowResultUpdater m_WindowResultUpdater; + + [MenuItem("Window/General/Test Runner", false, 201, false)] + public static void ShowPlaymodeTestsRunnerWindowCodeBased() + { + if (s_Instance != null) + { + try + { + s_Instance.Close(); + } + catch (Exception exception) + { + Debug.LogException(exception); + } + } + + s_Instance = GetWindow("Test Runner"); + s_Instance.Show(); + } + + static TestRunnerWindow() + { + InitBackgroundRunners(); + } + + private static void InitBackgroundRunners() + { + EditorApplication.playModeStateChanged -= OnPlayModeStateChanged; + EditorApplication.playModeStateChanged += OnPlayModeStateChanged; + } + + [DidReloadScripts] + private static void CompilationCallback() + { + UpdateWindow(); + } + + private static void OnPlayModeStateChanged(PlayModeStateChange state) + { + if (s_Instance && state == PlayModeStateChange.EnteredEditMode && s_Instance.m_SelectedTestTypes.HasTreeData()) + { + //repaint message details after exit playmode + s_Instance.m_SelectedTestTypes.TestSelectionCallback(s_Instance.m_SelectedTestTypes.m_TestListState.selectedIDs.ToArray()); + s_Instance.Repaint(); + } + } + + public void OnDestroy() + { + EditorApplication.playModeStateChanged -= OnPlayModeStateChanged; + if (m_testRunnerApi != null) + { + m_testRunnerApi.UnregisterCallbacks(m_WindowResultUpdater); + } + } + + private void OnEnable() + { + s_Instance = this; + SelectTestListGUI(m_TestTypeToolbarIndex); + + m_testRunnerApi = ScriptableObject.CreateInstance(); + m_WindowResultUpdater = new WindowResultUpdater(); + m_testRunnerApi.RegisterCallbacks(m_WindowResultUpdater); + } + + private void Enable() + { + m_Settings = new TestRunnerWindowSettings("UnityEditor.PlaymodeTestsRunnerWindow"); + filterSettings = new TestFilterSettings("UnityTest.IntegrationTestsRunnerWindow"); + + if (m_SelectedTestTypes == null) + { + SelectTestListGUI(m_TestTypeToolbarIndex); + } + + StartRetrieveTestList(); + m_SelectedTestTypes.Reload(); + m_Enabled = true; + } + + private void SelectTestListGUI(int testTypeToolbarIndex) + { + if (testTypeToolbarIndex == (int)TestRunnerMenuLabels.PlayMode) + { + if (m_PlayModeTestListGUI == null) + { + m_PlayModeTestListGUI = new PlayModeTestListGUI(); + } + m_SelectedTestTypes = m_PlayModeTestListGUI; + } + else if (testTypeToolbarIndex == (int)TestRunnerMenuLabels.EditMode) + { + if (m_EditModeTestListGUI == null) + { + m_EditModeTestListGUI = new EditModeTestListGUI(); + } + m_SelectedTestTypes = m_EditModeTestListGUI; + } + } + + private void StartRetrieveTestList() + { + if (!m_SelectedTestTypes.HasTreeData()) + { + m_testRunnerApi.RetrieveTestList(new ExecutionSettings() { filter = new Filter() { testMode = m_SelectedTestTypes.TestMode } }, (rootTest) => + { + m_SelectedTestTypes.Init(this, rootTest); + m_SelectedTestTypes.Reload(); + }); + } + } + + public void OnGUI() + { + if (!m_Enabled) + { + Enable(); + } + + if (BuildPipeline.isBuildingPlayer) + { + m_IsBuilding = true; + } + else if (m_IsBuilding) + { + m_IsBuilding = false; + Repaint(); + } + + EditorGUILayout.BeginHorizontal(); + GUILayout.FlexibleSpace(); + var selectedIndex = m_TestTypeToolbarIndex; + m_TestTypeToolbarIndex = GUILayout.Toolbar(m_TestTypeToolbarIndex, Enum.GetNames(typeof(TestRunnerMenuLabels)), "LargeButton", UnityEngine.GUI.ToolbarButtonSize.FitToContents); + GUILayout.FlexibleSpace(); + EditorGUILayout.EndHorizontal(); + + if (selectedIndex != m_TestTypeToolbarIndex) + { + SelectTestListGUI(m_TestTypeToolbarIndex); + StartRetrieveTestList(); + } + + EditorGUILayout.BeginVertical(); + using (new EditorGUI.DisabledScope(EditorApplication.isPlayingOrWillChangePlaymode)) + { + m_SelectedTestTypes.PrintHeadPanel(); + } + EditorGUILayout.EndVertical(); + + if (m_Settings.verticalSplit) + SplitterGUILayout.BeginVerticalSplit(m_Spl); + else + SplitterGUILayout.BeginHorizontalSplit(m_Spl); + + EditorGUILayout.BeginVertical(); + EditorGUILayout.BeginVertical(Styles.testList); + m_SelectedTestTypes.RenderTestList(); + EditorGUILayout.EndVertical(); + EditorGUILayout.EndVertical(); + + m_SelectedTestTypes.RenderDetails(); + + if (m_Settings.verticalSplit) + SplitterGUILayout.EndVerticalSplit(); + else + SplitterGUILayout.EndHorizontalSplit(); + } + + public void AddItemsToMenu(GenericMenu menu) + { + menu.AddItem(m_GUIVerticalSplit, m_Settings.verticalSplit, m_Settings.ToggleVerticalSplit); + menu.AddItem(m_GUIHorizontalSplit, !m_Settings.verticalSplit, m_Settings.ToggleVerticalSplit); + + menu.AddSeparator(null); + + var playModeTestRunnerEnabled = PlayerSettings.playModeTestRunnerEnabled; + var currentActive = playModeTestRunnerEnabled ? m_GUIDisablePlaymodeTestsRunner : m_GUIEnableaPlaymodeTestsRunner; + + if (EditorPrefs.GetBool("InternalMode", false)) + { + menu.AddItem(m_GUIRunPlayModeTestAsEditModeTests, PlayerSettings.runPlayModeTestAsEditModeTest, () => + { + PlayerSettings.runPlayModeTestAsEditModeTest = !PlayerSettings.runPlayModeTestAsEditModeTest; + }); + } + + menu.AddItem(currentActive, false, () => + { + PlayerSettings.playModeTestRunnerEnabled = !playModeTestRunnerEnabled; + EditorUtility.DisplayDialog(currentActive.text, "You need to restart the editor now", "Ok"); + }); + } + + public void RebuildUIFilter() + { + if (m_SelectedTestTypes != null && m_SelectedTestTypes.HasTreeData()) + { + m_SelectedTestTypes.RebuildUIFilter(); + } + } + + public static void UpdateWindow() + { + if (s_Instance != null && s_Instance.m_SelectedTestTypes != null) + { + s_Instance.m_SelectedTestTypes.Repaint(); + s_Instance.Repaint(); + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunnerWindowSettings.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunnerWindowSettings.cs new file mode 100644 index 00000000..366df260 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestRunnerWindowSettings.cs @@ -0,0 +1,26 @@ +namespace UnityEditor.TestTools.TestRunner +{ + internal class TestRunnerWindowSettings + { + public bool verticalSplit; + + private readonly string m_PrefsKey; + + public TestRunnerWindowSettings(string prefsKey) + { + m_PrefsKey = prefsKey; + verticalSplit = EditorPrefs.GetBool(m_PrefsKey + ".verticalSplit", true); + } + + public void ToggleVerticalSplit() + { + verticalSplit = !verticalSplit; + Save(); + } + + private void Save() + { + EditorPrefs.SetBool(m_PrefsKey + ".verticalSplit", verticalSplit); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestSettings/ITestSettings.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestSettings/ITestSettings.cs new file mode 100644 index 00000000..d2720372 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestSettings/ITestSettings.cs @@ -0,0 +1,22 @@ +using System; + +namespace UnityEditor.TestTools.TestRunner +{ + internal interface ITestSettings : IDisposable + { + ScriptingImplementation? scriptingBackend { get; set; } + + string Architecture { get; set; } + + ApiCompatibilityLevel? apiProfile { get; set; } + + bool? appleEnableAutomaticSigning { get; set; } + string appleDeveloperTeamID { get; set; } + ProvisioningProfileType? iOSManualProvisioningProfileType { get; set; } + string iOSManualProvisioningProfileID { get; set; } + ProvisioningProfileType? tvOSManualProvisioningProfileType { get; set; } + string tvOSManualProvisioningProfileID { get; set; } + + void SetupProjectParameters(); + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestSettings/ITestSettingsDeserializer.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestSettings/ITestSettingsDeserializer.cs new file mode 100644 index 00000000..701c91d8 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestSettings/ITestSettingsDeserializer.cs @@ -0,0 +1,7 @@ +namespace UnityEditor.TestTools.TestRunner +{ + interface ITestSettingsDeserializer + { + ITestSettings GetSettingsFromJsonFile(string jsonFilePath); + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestSettings/TestSettings.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestSettings/TestSettings.cs new file mode 100644 index 00000000..a5bdf7ad --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestSettings/TestSettings.cs @@ -0,0 +1,160 @@ +using System; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class TestSettings : ITestSettings + { + private readonly TestSetting[] m_Settings = + { + new TestSetting( + settings => settings.scriptingBackend, + () => PlayerSettings.GetScriptingBackend(EditorUserBuildSettings.activeBuildTargetGroup), + implementation => PlayerSettings.SetScriptingBackend(EditorUserBuildSettings.activeBuildTargetGroup, implementation.Value)), + new TestSetting( + settings => settings.Architecture, + () => EditorUserBuildSettings.activeBuildTarget == BuildTarget.Android ? PlayerSettings.Android.targetArchitectures.ToString() : null, + architecture => + { + if (EditorUserBuildSettings.activeBuildTarget == BuildTarget.Android) + { + if (!string.IsNullOrEmpty(architecture)) + { + var targetArchitectures = (AndroidArchitecture)Enum.Parse(typeof(AndroidArchitecture), architecture, true); + PlayerSettings.Android.targetArchitectures = targetArchitectures; + } + } + }), + new TestSetting( + settings => settings.apiProfile, + () => PlayerSettings.GetApiCompatibilityLevel(EditorUserBuildSettings.activeBuildTargetGroup), + implementation => + { + if (Enum.IsDefined(typeof(ApiCompatibilityLevel), implementation.Value)) + { + PlayerSettings.SetApiCompatibilityLevel(EditorUserBuildSettings.activeBuildTargetGroup, + implementation.Value); + } + }), + new TestSetting( + settings => settings.appleEnableAutomaticSigning, + () => PlayerSettings.iOS.appleEnableAutomaticSigning, + enableAutomaticSigning => + { + if (enableAutomaticSigning != null) + PlayerSettings.iOS.appleEnableAutomaticSigning = enableAutomaticSigning.Value; + }), + new TestSetting( + settings => settings.appleDeveloperTeamID, + () => PlayerSettings.iOS.appleDeveloperTeamID, + developerTeam => + { + if (developerTeam != null) + PlayerSettings.iOS.appleDeveloperTeamID = developerTeam; + }), + new TestSetting( + settings => settings.iOSManualProvisioningProfileType, + () => PlayerSettings.iOS.iOSManualProvisioningProfileType, + profileType => + { + if (profileType != null) + PlayerSettings.iOS.iOSManualProvisioningProfileType = profileType.Value; + }), + new TestSetting( + settings => settings.iOSManualProvisioningProfileID, + () => PlayerSettings.iOS.iOSManualProvisioningProfileID, + provisioningUUID => + { + if (provisioningUUID != null) + PlayerSettings.iOS.iOSManualProvisioningProfileID = provisioningUUID; + }), + new TestSetting( + settings => settings.tvOSManualProvisioningProfileType, + () => PlayerSettings.iOS.tvOSManualProvisioningProfileType, + profileType => + { + if (profileType != null) + PlayerSettings.iOS.tvOSManualProvisioningProfileType = profileType.Value; + }), + new TestSetting( + settings => settings.tvOSManualProvisioningProfileID, + () => PlayerSettings.iOS.tvOSManualProvisioningProfileID, + provisioningUUID => + { + if (provisioningUUID != null) + PlayerSettings.iOS.tvOSManualProvisioningProfileID = provisioningUUID; + }), + }; + + private bool m_Disposed; + + public ScriptingImplementation? scriptingBackend { get; set; } + + public string Architecture { get; set; } + + public ApiCompatibilityLevel? apiProfile { get; set; } + + public bool? appleEnableAutomaticSigning { get; set; } + public string appleDeveloperTeamID { get; set; } + public ProvisioningProfileType? iOSManualProvisioningProfileType { get; set; } + public string iOSManualProvisioningProfileID { get; set; } + public ProvisioningProfileType? tvOSManualProvisioningProfileType { get; set; } + public string tvOSManualProvisioningProfileID { get; set; } + + public void Dispose() + { + if (!m_Disposed) + { + foreach (var testSetting in m_Settings) + { + testSetting.Cleanup(); + } + + m_Disposed = true; + } + } + + public void SetupProjectParameters() + { + foreach (var testSetting in m_Settings) + { + testSetting.Setup(this); + } + } + + private abstract class TestSetting + { + public abstract void Setup(TestSettings settings); + public abstract void Cleanup(); + } + + private class TestSetting : TestSetting + { + private T m_ValueBeforeSetup; + private Func m_GetFromSettings; + private Func m_GetCurrentValue; + private Action m_SetValue; + + public TestSetting(Func getFromSettings, Func getCurrentValue, Action setValue) + { + m_GetFromSettings = getFromSettings; + m_GetCurrentValue = getCurrentValue; + m_SetValue = setValue; + } + + public override void Setup(TestSettings settings) + { + m_ValueBeforeSetup = m_GetCurrentValue(); + var newValue = m_GetFromSettings(settings); + if (newValue != null) + { + m_SetValue(newValue); + } + } + + public override void Cleanup() + { + m_SetValue(m_ValueBeforeSetup); + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestSettings/TestSettingsDeserializer.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestSettings/TestSettingsDeserializer.cs new file mode 100644 index 00000000..cdba06e9 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/TestSettings/TestSettingsDeserializer.cs @@ -0,0 +1,130 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using UnityEngine; + +namespace UnityEditor.TestTools.TestRunner +{ + /// + /// Handles deserialization of TestSettings from a provided json file path. + /// + internal class TestSettingsDeserializer : ITestSettingsDeserializer + { + private static readonly SettingsMap[] s_SettingsMapping = + { + new SettingsMap("scriptingBackend", (settings, value) => settings.scriptingBackend = value), + new SettingsMap("architecture", (settings, value) => settings.Architecture = value), + new SettingsMap("apiProfile", (settings, value) => settings.apiProfile = value), + new SettingsMap("appleEnableAutomaticSigning", (settings, value) => settings.appleEnableAutomaticSigning = value), + new SettingsMap("appleDeveloperTeamID", (settings, value) => settings.appleDeveloperTeamID = value), + new SettingsMap("iOSManualProvisioningProfileType", (settings, value) => settings.iOSManualProvisioningProfileType = value), + new SettingsMap("iOSManualProvisioningProfileID", (settings, value) => settings.iOSManualProvisioningProfileID = value), + new SettingsMap("tvOSManualProvisioningProfileType", (settings, value) => settings.tvOSManualProvisioningProfileType = value), + new SettingsMap("tvOSManualProvisioningProfileID", (settings, value) => settings.tvOSManualProvisioningProfileID = value), + }; + + private readonly Func m_TestSettingsFactory; + public TestSettingsDeserializer(Func testSettingsFactory) + { + m_TestSettingsFactory = testSettingsFactory; + } + + public ITestSettings GetSettingsFromJsonFile(string jsonFilePath) + { + var text = File.ReadAllText(jsonFilePath); + var settingsDictionary = Json.Deserialize(text) as Dictionary; + + var testSettings = m_TestSettingsFactory(); + if (settingsDictionary == null) + { + return testSettings; + } + + foreach (var settingsMap in s_SettingsMapping) + { + if (!settingsDictionary.ContainsKey(settingsMap.Key)) + { + continue; + } + + if (settingsMap.Type.IsEnum) + { + SetEnumValue(settingsMap.Key, settingsDictionary[settingsMap.Key], settingsMap.Type, value => settingsMap.ApplyToSettings(testSettings, value)); + } + else + { + SetValue(settingsMap.Key, settingsDictionary[settingsMap.Key], settingsMap.Type, value => settingsMap.ApplyToSettings(testSettings, value)); + } + } + + return testSettings; + } + + private abstract class SettingsMap + { + public string Key { get; } + public Type Type { get; } + protected SettingsMap(string key, Type type) + { + Key = key; + Type = type; + } + + public abstract void ApplyToSettings(ITestSettings settings, object value); + } + + private class SettingsMap : SettingsMap + { + private Action m_Setter; + public SettingsMap(string key, Action setter) : base(key, typeof(T)) + { + m_Setter = setter; + } + + public override void ApplyToSettings(ITestSettings settings, object value) + { + m_Setter(settings, (T)value); + } + } + + private static void SetEnumValue(string key, object value, Type type, Action setter) + { + object enumValue; + if (TryGetEnum(value as string, type, out enumValue)) + { + setter(enumValue); + return; + } + + var acceptedValues = string.Join(", ", Enum.GetValues(type).OfType().Select(val => val.ToString()).ToArray()); + + Debug.LogFormat("Could not convert '{0}' argument '{1}' to a valid {2}. Accepted values: {3}.", key, value, type.Name, acceptedValues); + } + + private static bool TryGetEnum(string value, Type type, out object enumValue) + { + try + { + enumValue = Enum.Parse(type, value, true); + return true; + } + catch (Exception) + { + enumValue = null; + return false; + } + } + + private static void SetValue(string key, object value, Type type, Action setter) + { + if (type.IsInstanceOfType(value)) + { + setter(value); + return; + } + + Debug.LogFormat("Could not convert '{0}' argument '{1}' to a valid {2}.", key, value, type.Name); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityEditor.TestRunner.asmdef b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityEditor.TestRunner.asmdef new file mode 100644 index 00000000..efdc7cf6 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityEditor.TestRunner.asmdef @@ -0,0 +1,21 @@ +{ + "name": "UnityEditor.TestRunner", + "references": [ + "UnityEngine.TestRunner" + ], + "includePlatforms": [ + "Editor" + ], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": true, + "precompiledReferences": [ + "nunit.framework.dll", + "Mono.Cecil.dll", + "Mono.Cecil.Pdb.dll", + "Mono.Cecil.Mdb.dll", + "Mono.Cecil.Rocks.dll" + ], + "autoReferenced": false, + "defineConstraints": [] +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityTestProtocol/AssemblyCompilationErrorsMessage.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityTestProtocol/AssemblyCompilationErrorsMessage.cs new file mode 100644 index 00000000..7f00c5b6 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityTestProtocol/AssemblyCompilationErrorsMessage.cs @@ -0,0 +1,13 @@ +namespace UnityEditor.TestTools.TestRunner.UnityTestProtocol +{ + internal class AssemblyCompilationErrorsMessage : Message + { + public string assembly; + public string[] errors; + + public AssemblyCompilationErrorsMessage() + { + type = "AssemblyCompilationErrors"; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityTestProtocol/ITestRunnerApiMapper.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityTestProtocol/ITestRunnerApiMapper.cs new file mode 100644 index 00000000..f7dcacfe --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityTestProtocol/ITestRunnerApiMapper.cs @@ -0,0 +1,15 @@ +using System.Collections.Generic; +using UnityEditor.TestTools.TestRunner.Api; + +namespace UnityEditor.TestTools.TestRunner.UnityTestProtocol +{ + interface ITestRunnerApiMapper + { + string GetRunStateFromResultNunitXml(ITestResultAdaptor result); + TestState GetTestStateFromResult(ITestResultAdaptor result); + List FlattenTestNames(ITestAdaptor testsToRun); + TestPlanMessage MapTestToTestPlanMessage(ITestAdaptor testsToRun); + TestStartedMessage MapTestToTestStartedMessage(ITestAdaptor test); + TestFinishedMessage TestResultToTestFinishedMessage(ITestResultAdaptor result); + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityTestProtocol/IUtpLogger.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityTestProtocol/IUtpLogger.cs new file mode 100644 index 00000000..bdb96c13 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityTestProtocol/IUtpLogger.cs @@ -0,0 +1,7 @@ +namespace UnityEditor.TestTools.TestRunner.UnityTestProtocol +{ + interface IUtpLogger + { + void Log(Message msg); + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityTestProtocol/IUtpMessageReporter.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityTestProtocol/IUtpMessageReporter.cs new file mode 100644 index 00000000..3a9895e1 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityTestProtocol/IUtpMessageReporter.cs @@ -0,0 +1,14 @@ +using System.Collections.Generic; +using UnityEditor.Compilation; +using UnityEditor.TestTools.TestRunner.Api; + +namespace UnityEditor.TestTools.TestRunner.UnityTestProtocol +{ + internal interface IUtpMessageReporter + { + void ReportAssemblyCompilationErrors(string assembly, IEnumerable errorCompilerMessages); + void ReportTestFinished(ITestResultAdaptor result); + void ReportTestRunStarted(ITestAdaptor testsToRun); + void ReportTestStarted(ITestAdaptor test); + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityTestProtocol/Message.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityTestProtocol/Message.cs new file mode 100644 index 00000000..d10a5e42 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityTestProtocol/Message.cs @@ -0,0 +1,29 @@ +using System; +using System.Diagnostics; + +namespace UnityEditor.TestTools.TestRunner.UnityTestProtocol +{ + [Serializable] + internal abstract class Message + { + public string type; + // Milliseconds since unix epoch + public ulong time; + public int version; + public string phase; + public int processId; + + protected Message() + { + version = 2; + phase = "Immediate"; + processId = Process.GetCurrentProcess().Id; + AddTimeStamp(); + } + + public void AddTimeStamp() + { + time = Convert.ToUInt64((DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityTestProtocol/TestFinishedMessage.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityTestProtocol/TestFinishedMessage.cs new file mode 100644 index 00000000..6280fd07 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityTestProtocol/TestFinishedMessage.cs @@ -0,0 +1,17 @@ +namespace UnityEditor.TestTools.TestRunner.UnityTestProtocol +{ + internal class TestFinishedMessage : Message + { + public string name; + public TestState state; + public string message; + public ulong duration; // milliseconds + public ulong durationMicroseconds; + + public TestFinishedMessage() + { + type = "TestStatus"; + phase = "End"; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityTestProtocol/TestPlanMessage.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityTestProtocol/TestPlanMessage.cs new file mode 100644 index 00000000..c0a76dad --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityTestProtocol/TestPlanMessage.cs @@ -0,0 +1,14 @@ +using System.Collections.Generic; + +namespace UnityEditor.TestTools.TestRunner.UnityTestProtocol +{ + internal class TestPlanMessage : Message + { + public List tests; + + public TestPlanMessage() + { + type = "TestPlan"; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityTestProtocol/TestRunnerApiMapper.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityTestProtocol/TestRunnerApiMapper.cs new file mode 100644 index 00000000..d231b742 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityTestProtocol/TestRunnerApiMapper.cs @@ -0,0 +1,98 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Xml; +using UnityEditor.TestTools.TestRunner.Api; + +namespace UnityEditor.TestTools.TestRunner.UnityTestProtocol +{ + internal class TestRunnerApiMapper : ITestRunnerApiMapper + { + public TestPlanMessage MapTestToTestPlanMessage(ITestAdaptor testsToRun) + { + var testsNames = testsToRun != null ? FlattenTestNames(testsToRun) : new List(); + + var msg = new TestPlanMessage + { + tests = testsNames + }; + + return msg; + } + + public TestStartedMessage MapTestToTestStartedMessage(ITestAdaptor test) + { + return new TestStartedMessage + { + name = test.FullName + }; + } + + public TestFinishedMessage TestResultToTestFinishedMessage(ITestResultAdaptor result) + { + return new TestFinishedMessage + { + name = result.Test.FullName, + duration = Convert.ToUInt64(result.Duration * 1000), + durationMicroseconds = Convert.ToUInt64(result.Duration * 1000000), + message = result.Message, + state = GetTestStateFromResult(result) + }; + } + + public string GetRunStateFromResultNunitXml(ITestResultAdaptor result) + { + var doc = new XmlDocument(); + doc.LoadXml(result.ToXml().OuterXml); + return doc.FirstChild.Attributes["runstate"].Value; + } + + public TestState GetTestStateFromResult(ITestResultAdaptor result) + { + var state = TestState.Failure; + + if (result.TestStatus == TestStatus.Passed) + { + state = TestState.Success; + + var runstate = GetRunStateFromResultNunitXml(result); + runstate = runstate ?? String.Empty; + + if (runstate.ToLowerInvariant().Equals("explicit")) + state = TestState.Skipped; + } + else if (result.TestStatus == TestStatus.Skipped) + { + state = TestState.Skipped; + + if (result.ResultState.ToLowerInvariant().EndsWith("ignored")) + state = TestState.Ignored; + } + else + { + if (result.ResultState.ToLowerInvariant().Equals("inconclusive")) + state = TestState.Inconclusive; + + if (result.ResultState.ToLowerInvariant().EndsWith("cancelled") || + result.ResultState.ToLowerInvariant().EndsWith("error")) + state = TestState.Error; + } + + return state; + } + + public List FlattenTestNames(ITestAdaptor test) + { + var results = new List(); + + if (!test.IsSuite) + results.Add(test.FullName); + + if (test.Children != null && test.Children.Any()) + foreach (var child in test.Children) + results.AddRange(FlattenTestNames(child)); + + return results; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityTestProtocol/TestStartedMessage.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityTestProtocol/TestStartedMessage.cs new file mode 100644 index 00000000..c21464fc --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityTestProtocol/TestStartedMessage.cs @@ -0,0 +1,15 @@ +namespace UnityEditor.TestTools.TestRunner.UnityTestProtocol +{ + internal class TestStartedMessage : Message + { + public string name; + public TestState state; + + public TestStartedMessage() + { + type = "TestStatus"; + phase = "Begin"; + state = TestState.Inconclusive; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityTestProtocol/TestState.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityTestProtocol/TestState.cs new file mode 100644 index 00000000..223a73d5 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityTestProtocol/TestState.cs @@ -0,0 +1,13 @@ +namespace UnityEditor.TestTools.TestRunner.UnityTestProtocol +{ + // This matches the state definitions expected by the Perl code, which in turn matches the NUnit 2 values... + internal enum TestState + { + Inconclusive = 0, + Skipped = 2, + Ignored = 3, + Success = 4, + Failure = 5, + Error = 6 + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityTestProtocol/UnityTestProtocolListener.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityTestProtocol/UnityTestProtocolListener.cs new file mode 100644 index 00000000..09daf8dc --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityTestProtocol/UnityTestProtocolListener.cs @@ -0,0 +1,35 @@ +using UnityEditor.TestTools.TestRunner.Api; +using UnityEngine; + +namespace UnityEditor.TestTools.TestRunner.UnityTestProtocol +{ + internal class UnityTestProtocolListener : ScriptableObject, ICallbacks + { + private IUtpMessageReporter m_UtpMessageReporter; + + public UnityTestProtocolListener() + { + m_UtpMessageReporter = new UtpMessageReporter(new UtpDebugLogger()); + } + + public void RunStarted(ITestAdaptor testsToRun) + { + m_UtpMessageReporter.ReportTestRunStarted(testsToRun); + } + + public void RunFinished(ITestResultAdaptor testResults) + { + // Apparently does nothing :) + } + + public void TestStarted(ITestAdaptor test) + { + m_UtpMessageReporter.ReportTestStarted(test); + } + + public void TestFinished(ITestResultAdaptor result) + { + m_UtpMessageReporter.ReportTestFinished(result); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityTestProtocol/UnityTestProtocolStarter.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityTestProtocol/UnityTestProtocolStarter.cs new file mode 100644 index 00000000..cca2fd82 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityTestProtocol/UnityTestProtocolStarter.cs @@ -0,0 +1,37 @@ +using System; +using System.Linq; +using UnityEditor.Compilation; +using UnityEditor.TestTools.TestRunner.Api; +using UnityEngine; +using UnityEngine.TestTools; + +namespace UnityEditor.TestTools.TestRunner.UnityTestProtocol +{ + [InitializeOnLoad] + internal static class UnityTestProtocolStarter + { + static UnityTestProtocolStarter() + { + var commandLineArgs = Environment.GetCommandLineArgs(); + if (commandLineArgs.Contains("-automated") && commandLineArgs.Contains("-runTests")) // wanna have it only for utr run + { + var api = ScriptableObject.CreateInstance(); + var listener = ScriptableObject.CreateInstance(); + api.RegisterCallbacks(listener); + CompilationPipeline.assemblyCompilationFinished += OnAssemblyCompilationFinished; + } + } + + public static void OnAssemblyCompilationFinished(string assembly, CompilerMessage[] messages) + { + bool checkCompileErrors = RecompileScripts.Current == null || RecompileScripts.Current.ExpectScriptCompilationSuccess; + + if (checkCompileErrors && messages.Any(x => x.type == CompilerMessageType.Error)) + { + var compilerErrorMessages = messages.Where(x => x.type == CompilerMessageType.Error); + var utpMessageReporter = new UtpMessageReporter(new UtpDebugLogger()); + utpMessageReporter.ReportAssemblyCompilationErrors(assembly, compilerErrorMessages); + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityTestProtocol/UtpDebuglogger.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityTestProtocol/UtpDebuglogger.cs new file mode 100644 index 00000000..e32f6d28 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityTestProtocol/UtpDebuglogger.cs @@ -0,0 +1,13 @@ +using UnityEngine; + +namespace UnityEditor.TestTools.TestRunner.UnityTestProtocol +{ + class UtpDebugLogger : IUtpLogger + { + public void Log(Message msg) + { + var msgJson = JsonUtility.ToJson(msg); + Debug.LogFormat(LogType.Log, LogOption.NoStacktrace, null, "\n##utp:{0}", msgJson); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityTestProtocol/UtpMessageReporter.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityTestProtocol/UtpMessageReporter.cs new file mode 100644 index 00000000..37c4ee7e --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEditor.TestRunner/UnityTestProtocol/UtpMessageReporter.cs @@ -0,0 +1,57 @@ +using System.Collections.Generic; +using System.Linq; +using UnityEditor.Compilation; +using UnityEditor.TestTools.TestRunner.Api; + +namespace UnityEditor.TestTools.TestRunner.UnityTestProtocol +{ + internal class UtpMessageReporter : IUtpMessageReporter + { + public ITestRunnerApiMapper TestRunnerApiMapper; + public IUtpLogger Logger; + + public UtpMessageReporter(IUtpLogger utpLogger) + { + TestRunnerApiMapper = new TestRunnerApiMapper(); + Logger = utpLogger; + } + + public void ReportAssemblyCompilationErrors(string assembly, IEnumerable errorCompilerMessages) + { + var compilationErrorMessage = new AssemblyCompilationErrorsMessage + { + assembly = assembly, + errors = errorCompilerMessages.Select(x => x.message).ToArray() + }; + + Logger.Log(compilationErrorMessage); + } + + public void ReportTestRunStarted(ITestAdaptor testsToRun) + { + var msg = TestRunnerApiMapper.MapTestToTestPlanMessage(testsToRun); + + Logger.Log(msg); + } + + public void ReportTestStarted(ITestAdaptor test) + { + if (test.IsSuite) + return; + + var msg = TestRunnerApiMapper.MapTestToTestStartedMessage(test); + + Logger.Log(msg); + } + + public void ReportTestFinished(ITestResultAdaptor result) + { + if (result.Test.IsSuite) + return; + + var msg = TestRunnerApiMapper.TestResultToTestFinishedMessage(result); + + Logger.Log(msg); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/AssemblyInfo.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/AssemblyInfo.cs new file mode 100644 index 00000000..41496773 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/AssemblyInfo.cs @@ -0,0 +1,16 @@ +using System.Reflection; +using System.Runtime.CompilerServices; + +[assembly: AssemblyTitle("UnityEngine.TestRunner")] + +[assembly: InternalsVisibleTo("UnityEditor.TestRunner")] +[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] +[assembly: InternalsVisibleTo("Unity.PerformanceTesting")] +[assembly: InternalsVisibleTo("Unity.PerformanceTesting.Editor")] +[assembly: InternalsVisibleTo("Assembly-CSharp-testable")] +[assembly: InternalsVisibleTo("Assembly-CSharp-Editor-testable")] +[assembly: InternalsVisibleTo("UnityEngine.TestRunner.Tests")] +[assembly: InternalsVisibleTo("UnityEditor.TestRunner.Tests")] +[assembly: InternalsVisibleTo("Unity.PackageManagerUI.Editor")] + +[assembly: AssemblyVersion("1.0.0")] diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Assertions/AllocatingGCMemoryConstraint.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Assertions/AllocatingGCMemoryConstraint.cs new file mode 100644 index 00000000..339a090e --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Assertions/AllocatingGCMemoryConstraint.cs @@ -0,0 +1,83 @@ +using System; +using NUnit.Framework; +using NUnit.Framework.Constraints; +using UnityEngine.Profiling; + +namespace UnityEngine.TestTools.Constraints +{ + public class AllocatingGCMemoryConstraint : Constraint + { + private class AllocatingGCMemoryResult : ConstraintResult + { + private readonly int diff; + public AllocatingGCMemoryResult(IConstraint constraint, object actualValue, int diff) : base(constraint, actualValue, diff > 0) + { + this.diff = diff; + } + + public override void WriteMessageTo(MessageWriter writer) + { + if (diff == 0) + writer.WriteMessageLine("The provided delegate did not make any GC allocations."); + else + writer.WriteMessageLine("The provided delegate made {0} GC allocation(s).", diff); + } + } + + private ConstraintResult ApplyTo(Action action, object original) + { + var recorder = Recorder.Get("GC.Alloc"); + + // The recorder was created enabled, which means it captured the creation of the Recorder object itself, etc. + // Disabling it flushes its data, so that we can retrieve the sample block count and have it correctly account + // for these initial allocations. + recorder.enabled = false; + +#if !UNITY_WEBGL + recorder.FilterToCurrentThread(); +#endif + + recorder.enabled = true; + + try + { + action(); + } + finally + { + recorder.enabled = false; +#if !UNITY_WEBGL + recorder.CollectFromAllThreads(); +#endif + } + + return new AllocatingGCMemoryResult(this, original, recorder.sampleBlockCount); + } + + public override ConstraintResult ApplyTo(object obj) + { + if (obj == null) + throw new ArgumentNullException(); + + TestDelegate d = obj as TestDelegate; + if (d == null) + throw new ArgumentException(string.Format("The actual value must be a TestDelegate but was {0}", + obj.GetType())); + + return ApplyTo(() => d.Invoke(), obj); + } + + public override ConstraintResult ApplyTo(ActualValueDelegate del) + { + if (del == null) + throw new ArgumentNullException(); + + return ApplyTo(() => del.Invoke(), del); + } + + public override string Description + { + get { return "allocates GC memory"; } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Assertions/ConstraintsExtensions.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Assertions/ConstraintsExtensions.cs new file mode 100644 index 00000000..812b1f06 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Assertions/ConstraintsExtensions.cs @@ -0,0 +1,14 @@ +using NUnit.Framework.Constraints; + +namespace UnityEngine.TestTools.Constraints +{ + public static class ConstraintExtensions + { + public static AllocatingGCMemoryConstraint AllocatingGCMemory(this ConstraintExpression chain) + { + var constraint = new AllocatingGCMemoryConstraint(); + chain.Append(constraint); + return constraint; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Assertions/InvalidSignatureException.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Assertions/InvalidSignatureException.cs new file mode 100644 index 00000000..ab4ff8e3 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Assertions/InvalidSignatureException.cs @@ -0,0 +1,18 @@ +using NUnit.Framework; +using NUnit.Framework.Interfaces; + +namespace UnityEngine.TestTools.TestRunner +{ + internal class InvalidSignatureException : ResultStateException + { + public InvalidSignatureException(string message) + : base(message) + { + } + + public override ResultState ResultState + { + get { return ResultState.NotRunnable; } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Assertions/Is.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Assertions/Is.cs new file mode 100644 index 00000000..c0871ef2 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Assertions/Is.cs @@ -0,0 +1,10 @@ +namespace UnityEngine.TestTools.Constraints +{ + public class Is : NUnit.Framework.Is + { + public static AllocatingGCMemoryConstraint AllocatingGCMemory() + { + return new AllocatingGCMemoryConstraint(); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Assertions/LogAssert.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Assertions/LogAssert.cs new file mode 100644 index 00000000..19ecd1c8 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Assertions/LogAssert.cs @@ -0,0 +1,43 @@ +using System.Text.RegularExpressions; +using UnityEngine.TestTools.Logging; +using UnityEngine.TestTools.TestRunner; + +namespace UnityEngine.TestTools +{ + public static class LogAssert + { + public static void Expect(LogType type, string message) + { + LogScope.Current.ExpectedLogs.Enqueue(new LogMatch() { LogType = type, Message = message }); + } + + public static void Expect(LogType type, Regex message) + { + LogScope.Current.ExpectedLogs.Enqueue(new LogMatch() { LogType = type, MessageRegex = message }); + } + + public static void NoUnexpectedReceived() + { + LogScope.Current.ProcessExpectedLogs(); + var isAllLogsHandled = LogScope.Current.IsAllLogsHandled(); + if (isAllLogsHandled) + { + return; + } + var unhandledLog = LogScope.Current.GetUnhandledLog(); + throw new UnhandledLogMessageException(unhandledLog); + } + + public static bool ignoreFailingMessages + { + get + { + return LogScope.Current.IgnoreFailingMessages; + } + set + { + LogScope.Current.IgnoreFailingMessages = value; + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Assertions/LogScope/ILogScope.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Assertions/LogScope/ILogScope.cs new file mode 100644 index 00000000..750d2b59 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Assertions/LogScope/ILogScope.cs @@ -0,0 +1,10 @@ +using System; +using System.Collections.Generic; + +namespace UnityEngine.TestTools.Logging +{ + internal interface ILogScope : IDisposable + { + List LogEvents { get; } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Assertions/LogScope/LogEvent.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Assertions/LogScope/LogEvent.cs new file mode 100644 index 00000000..bbc805e8 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Assertions/LogScope/LogEvent.cs @@ -0,0 +1,18 @@ +namespace UnityEngine.TestTools.Logging +{ + internal class LogEvent + { + public string Message { get; set; } + + public string StackTrace { get; set; } + + public LogType LogType { get; set; } + + public bool IsHandled { get; set; } + + public override string ToString() + { + return string.Format("[{0}] {1}", LogType, Message); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Assertions/LogScope/LogMatch.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Assertions/LogScope/LogMatch.cs new file mode 100644 index 00000000..9b862d92 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Assertions/LogScope/LogMatch.cs @@ -0,0 +1,103 @@ +using System; +using System.Text.RegularExpressions; + +namespace UnityEngine.TestTools.Logging +{ + [Serializable] + internal class LogMatch + { + [SerializeField] + private bool m_UseRegex; + [SerializeField] + private string m_Message; + [SerializeField] + private string m_MessageRegex; + [SerializeField] + private string m_LogType; + + public string Message + { + get { return m_Message; } + set + { + m_Message = value; + m_UseRegex = false; + } + } + + public Regex MessageRegex + { + get + { + if (!m_UseRegex) + { + return null; + } + + return new Regex(m_MessageRegex); + } + set + { + if (value != null) + { + m_MessageRegex = value.ToString(); + m_UseRegex = true; + } + else + { + m_MessageRegex = null; + m_UseRegex = false; + } + } + } + + public LogType? LogType + { + get + { + if (!string.IsNullOrEmpty(m_LogType)) + { + return Enum.Parse(typeof(LogType), m_LogType) as LogType ? ; + } + + return null; + } + set + { + if (value != null) + { + m_LogType = value.Value.ToString(); + } + else + { + m_LogType = null; + } + } + } + + public bool Matches(LogEvent log) + { + if (LogType != null && LogType != log.LogType) + { + return false; + } + + if (m_UseRegex) + { + return MessageRegex.IsMatch(log.Message); + } + else + { + return Message.Equals(log.Message); + } + } + + public override string ToString() + { + if (m_UseRegex) + return string.Format("[{0}] Regex: {1}", LogType, MessageRegex); + else + return string.Format("[{0}] {1}", LogType, Message); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Assertions/LogScope/LogScope.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Assertions/LogScope/LogScope.cs new file mode 100644 index 00000000..c5bf0976 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Assertions/LogScope/LogScope.cs @@ -0,0 +1,224 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace UnityEngine.TestTools.Logging +{ + internal class LogScope : IDisposable + { + private bool m_Disposed; + private readonly object _lock = new object(); + + public Queue ExpectedLogs { get; set; } + public List AllLogs { get; } + public List FailingLogs { get; } + public bool IgnoreFailingMessages { get; set; } + public bool IsNUnitException { get; private set; } + public bool IsNUnitSuccessException { get; private set; } + public bool IsNUnitInconclusiveException { get; private set; } + public bool IsNUnitIgnoreException { get; private set; } + public string NUnitExceptionMessage { get; private set; } + + private bool m_NeedToProcessLogs; + private static List s_ActiveScopes = new List(); + + internal static LogScope Current + { + get + { + if (s_ActiveScopes.Count == 0) + throw new InvalidOperationException("No log scope is available"); + return s_ActiveScopes[0]; + } + } + + internal static bool HasCurrentLogScope() + { + return s_ActiveScopes.Count > 0; + } + + public LogScope() + { + AllLogs = new List(); + FailingLogs = new List(); + ExpectedLogs = new Queue(); + IgnoreFailingMessages = false; + Activate(); + } + + private void Activate() + { + s_ActiveScopes.Insert(0, this); + RegisterScope(this); + Application.logMessageReceivedThreaded -= AddLog; + Application.logMessageReceivedThreaded += AddLog; + } + + private void Deactivate() + { + Application.logMessageReceivedThreaded -= AddLog; + s_ActiveScopes.Remove(this); + UnregisterScope(this); + } + + private static void RegisterScope(LogScope logScope) + { + Application.logMessageReceivedThreaded += logScope.AddLog; + } + + private static void UnregisterScope(LogScope logScope) + { + Application.logMessageReceivedThreaded -= logScope.AddLog; + } + + public void AddLog(string message, string stacktrace, LogType type) + { + lock (_lock) + { + m_NeedToProcessLogs = true; + var log = new LogEvent + { + LogType = type, + Message = message, + StackTrace = stacktrace, + }; + + AllLogs.Add(log); + + if (IsNUnitResultStateException(stacktrace, type)) + { + if (message.StartsWith("SuccessException")) + { + IsNUnitException = true; + IsNUnitSuccessException = true; + if (message.StartsWith("SuccessException: ")) + { + NUnitExceptionMessage = message.Substring("SuccessException: ".Length); + return; + } + } + else if (message.StartsWith("InconclusiveException")) + { + IsNUnitException = true; + IsNUnitInconclusiveException = true; + if (message.StartsWith("InconclusiveException: ")) + { + NUnitExceptionMessage = message.Substring("InconclusiveException: ".Length); + return; + } + } + else if (message.StartsWith("IgnoreException")) + { + IsNUnitException = true; + IsNUnitIgnoreException = true; + if (message.StartsWith("IgnoreException: ")) + { + NUnitExceptionMessage = message.Substring("IgnoreException: ".Length); + return; + } + } + } + + if (IsFailingLog(type) && !IgnoreFailingMessages) + { + FailingLogs.Add(log); + } + } + } + + public bool IsAllLogsHandled() + { + lock (_lock) + { + return AllLogs.All(x => x.IsHandled); + } + } + + public LogEvent GetUnhandledLog() + { + lock (_lock) + { + return AllLogs.First(x => !x.IsHandled); + } + } + + private static bool IsNUnitResultStateException(string stacktrace, LogType logType) + { + if (logType != LogType.Exception) + return false; + + return string.IsNullOrEmpty(stacktrace) || stacktrace.StartsWith("NUnit.Framework.Assert."); + } + + private static bool IsFailingLog(LogType type) + { + switch (type) + { + case LogType.Assert: + case LogType.Error: + case LogType.Exception: + return true; + default: + return false; + } + } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing) + { + if (m_Disposed) + { + return; + } + + m_Disposed = true; + + if (disposing) + { + Deactivate(); + } + } + + internal bool AnyFailingLogs() + { + ProcessExpectedLogs(); + return FailingLogs.Any(); + } + + internal void ProcessExpectedLogs() + { + lock (_lock) + { + if (!m_NeedToProcessLogs || !ExpectedLogs.Any()) + return; + + LogMatch expectedLog = null; + foreach (var logEvent in AllLogs) + { + if (!ExpectedLogs.Any()) + break; + if (expectedLog == null && ExpectedLogs.Any()) + expectedLog = ExpectedLogs.Peek(); + + if (expectedLog != null && expectedLog.Matches(logEvent)) + { + ExpectedLogs.Dequeue(); + logEvent.IsHandled = true; + if (FailingLogs.Any(expectedLog.Matches)) + { + var failingLog = FailingLogs.First(expectedLog.Matches); + FailingLogs.Remove(failingLog); + } + expectedLog = null; + } + } + m_NeedToProcessLogs = false; + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Assertions/UnexpectedLogMessageException.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Assertions/UnexpectedLogMessageException.cs new file mode 100644 index 00000000..8ad39f44 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Assertions/UnexpectedLogMessageException.cs @@ -0,0 +1,29 @@ +using NUnit.Framework; +using NUnit.Framework.Interfaces; +using UnityEngine.TestTools.Logging; + +namespace UnityEngine.TestTools.TestRunner +{ + internal class UnexpectedLogMessageException : ResultStateException + { + public LogMatch LogEvent; + + public UnexpectedLogMessageException(LogMatch log) + : base(BuildMessage(log)) + { + LogEvent = log; + } + + private static string BuildMessage(LogMatch log) + { + return string.Format("Expected log did not appear: {0}", log); + } + + public override ResultState ResultState + { + get { return ResultState.Failure; } + } + + public override string StackTrace { get { return null; } } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Assertions/UnhandledLogMessageException.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Assertions/UnhandledLogMessageException.cs new file mode 100644 index 00000000..9427cc86 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Assertions/UnhandledLogMessageException.cs @@ -0,0 +1,35 @@ +using NUnit.Framework; +using NUnit.Framework.Interfaces; +using UnityEngine.TestTools.Logging; +using UnityEngine.TestTools.Utils; + +namespace UnityEngine.TestTools.TestRunner +{ + internal class UnhandledLogMessageException : ResultStateException + { + public LogEvent LogEvent; + private readonly string m_CustomStackTrace; + + public UnhandledLogMessageException(LogEvent log) + : base(BuildMessage(log)) + { + LogEvent = log; + m_CustomStackTrace = StackTraceFilter.Filter(log.StackTrace); + } + + private static string BuildMessage(LogEvent log) + { + return string.Format("Unhandled log message: '{0}'. Use UnityEngine.TestTools.LogAssert.Expect", log); + } + + public override ResultState ResultState + { + get { return ResultState.Failure; } + } + + public override string StackTrace + { + get { return m_CustomStackTrace; } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Assertions/UnityTestTimeoutException.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Assertions/UnityTestTimeoutException.cs new file mode 100644 index 00000000..6ba39c26 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Assertions/UnityTestTimeoutException.cs @@ -0,0 +1,28 @@ +using NUnit.Framework; +using NUnit.Framework.Interfaces; + +namespace UnityEngine.TestTools.TestRunner +{ + internal class UnityTestTimeoutException : ResultStateException + { + public UnityTestTimeoutException(int timeout) + : base(BuildMessage(timeout)) + { + } + + private static string BuildMessage(int timeout) + { + return string.Format("UnityTest exceeded Timeout value of {0}ms", timeout); + } + + public override ResultState ResultState + { + get { return ResultState.Failure; } + } + + public override string StackTrace + { + get { return ""; } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/ActionDelegator.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/ActionDelegator.cs new file mode 100644 index 00000000..ed8d8963 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/ActionDelegator.cs @@ -0,0 +1,79 @@ +using System; +using System.Linq; +using UnityEngine.TestRunner.NUnitExtensions.Runner; +using UnityEngine.TestTools.Logging; +using UnityEngine.TestTools.TestRunner; + +namespace UnityEngine.TestTools.NUnitExtensions +{ + /// + /// This class delegates actions from the NUnit thread that should be executed on the main thread. + /// NUnit thread calls Delegate which blocks the execution on the thread until the action is executed. + /// The main thread will poll for awaiting actions (HasAction) and invoke them (Execute). + /// Once the action is executed, the main thread releases the lock and executino on the NUnit thread is continued. + /// + internal class ActionDelegator : BaseDelegator + { + private Func m_Action; + public object Delegate(Action action) + { + return Delegate(() => { action(); return null; }); + } + + public object Delegate(Func action) + { + if (m_Aborted) + { + return null; + } + + AssertState(); + m_Context = UnityTestExecutionContext.CurrentContext; + + m_Signal.Reset(); + m_Action = action; + + WaitForSignal(); + + return HandleResult(); + } + + private void AssertState() + { + if (m_Action != null) + { + throw new Exception("Action not executed yet"); + } + } + + public bool HasAction() + { + return m_Action != null; + } + + public void Execute(LogScope logScope) + { + try + { + SetCurrentTestContext(); + m_Result = m_Action(); + if (logScope.AnyFailingLogs()) + { + var failingLog = logScope.FailingLogs.First(); + throw new UnhandledLogMessageException(failingLog); + } + if (logScope.ExpectedLogs.Any()) + throw new UnexpectedLogMessageException(LogScope.Current.ExpectedLogs.Peek()); + } + catch (Exception e) + { + m_Exception = e; + } + finally + { + m_Action = null; + m_Signal.Set(); + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Attributes/TestEnumerator.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Attributes/TestEnumerator.cs new file mode 100644 index 00000000..89c5f76b --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Attributes/TestEnumerator.cs @@ -0,0 +1,52 @@ +using System; +using System.Collections; +using NUnit.Framework; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; + +namespace UnityEngine.TestTools +{ + internal class TestEnumerator + { + private readonly ITestExecutionContext m_Context; + private static IEnumerator m_TestEnumerator; + + public static IEnumerator Enumerator { get { return m_TestEnumerator; } } + + public TestEnumerator(ITestExecutionContext context, IEnumerator testEnumerator) + { + m_Context = context; + m_TestEnumerator = testEnumerator; + } + + public IEnumerator Execute() + { + m_Context.CurrentResult.SetResult(ResultState.Success); + + while (true) + { + object current = null; + try + { + if (!m_TestEnumerator.MoveNext()) + { + yield break; + } + + if (!m_Context.CurrentResult.ResultState.Equals(ResultState.Success)) + { + yield break; + } + + current = m_TestEnumerator.Current; + } + catch (Exception exception) + { + m_Context.CurrentResult.RecordException(exception); + yield break; + } + yield return current; + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Attributes/UnityCombinatorialStrategy.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Attributes/UnityCombinatorialStrategy.cs new file mode 100644 index 00000000..84f8d845 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Attributes/UnityCombinatorialStrategy.cs @@ -0,0 +1,20 @@ +using System.Collections; +using System.Collections.Generic; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal.Builders; + +namespace UnityEngine.TestTools +{ + internal class UnityCombinatorialStrategy : CombinatorialStrategy, ICombiningStrategy + { + public new IEnumerable GetTestCases(IEnumerable[] sources) + { + var testCases = base.GetTestCases(sources); + foreach (var testCase in testCases) + { + testCase.GetType().GetProperty("ExpectedResult").SetValue(testCase, new object(), null); + } + return testCases; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Attributes/UnityPlatformAttribute.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Attributes/UnityPlatformAttribute.cs new file mode 100644 index 00000000..ff538ea1 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Attributes/UnityPlatformAttribute.cs @@ -0,0 +1,56 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using NUnit.Framework; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; + +namespace UnityEngine.TestTools +{ + [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = false)] + public class UnityPlatformAttribute : NUnitAttribute, IApplyToTest + { + public RuntimePlatform[] include { get; set; } + public RuntimePlatform[] exclude { get; set; } + + private string m_skippedReason; + + public UnityPlatformAttribute() + { + include = new List().ToArray(); + exclude = new List().ToArray(); + } + + public UnityPlatformAttribute(params RuntimePlatform[] include) + : this() + { + this.include = include; + } + + public void ApplyToTest(Test test) + { + if (test.RunState == RunState.NotRunnable || test.RunState == RunState.Ignored || IsPlatformSupported(Application.platform)) + { + return; + } + test.RunState = RunState.Skipped; + test.Properties.Add("_SKIPREASON", m_skippedReason); + } + + internal bool IsPlatformSupported(RuntimePlatform testTargetPlatform) + { + if (include.Any() && !include.Any(x => x == testTargetPlatform)) + { + m_skippedReason = string.Format("Only supported on {0}", string.Join(", ", include.Select(x => x.ToString()).ToArray())); + return false; + } + + if (exclude.Any(x => x == testTargetPlatform)) + { + m_skippedReason = string.Format("Not supported on {0}", string.Join(", ", include.Select(x => x.ToString()).ToArray())); + return false; + } + return true; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Attributes/UnitySetUpAttribute.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Attributes/UnitySetUpAttribute.cs new file mode 100644 index 00000000..f51da12e --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Attributes/UnitySetUpAttribute.cs @@ -0,0 +1,10 @@ +using System; +using NUnit.Framework; + +namespace UnityEngine.TestTools +{ + [AttributeUsage(AttributeTargets.Method)] + public class UnitySetUpAttribute : NUnitAttribute + { + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Attributes/UnityTearDownAttribute.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Attributes/UnityTearDownAttribute.cs new file mode 100644 index 00000000..dec605c1 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Attributes/UnityTearDownAttribute.cs @@ -0,0 +1,10 @@ +using System; +using NUnit.Framework; + +namespace UnityEngine.TestTools +{ + [AttributeUsage(AttributeTargets.Method)] + public class UnityTearDownAttribute : NUnitAttribute + { + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Attributes/UnityTestAttribute.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Attributes/UnityTestAttribute.cs new file mode 100644 index 00000000..06cdd6ba --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Attributes/UnityTestAttribute.cs @@ -0,0 +1,43 @@ +using System; +using NUnit.Framework; +using NUnit.Framework.Internal.Commands; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; +using NUnit.Framework.Internal.Builders; +using UnityEngine.TestRunner.NUnitExtensions.Runner; + +namespace UnityEngine.TestTools +{ + [AttributeUsage(AttributeTargets.Method)] + public class UnityTestAttribute : CombiningStrategyAttribute, IWrapSetUpTearDown, ISimpleTestBuilder, IImplyFixture + { + public UnityTestAttribute() : base(new UnityCombinatorialStrategy(), new ParameterDataSourceProvider()) {} + + private readonly NUnitTestCaseBuilder _builder = new NUnitTestCaseBuilder(); + + TestMethod ISimpleTestBuilder.BuildFrom(IMethodInfo method, Test suite) + { + TestCaseParameters parms = new TestCaseParameters + { + ExpectedResult = new object(), + HasExpectedResult = true + }; + + var t = _builder.BuildTestMethod(method, suite, parms); + + if (t.parms != null) + t.parms.HasExpectedResult = false; + return t; + } + + public TestCommand Wrap(TestCommand command) + { + return new OuterUnityTestActionCommand( + new EnumerableSetUpTearDownCommand( + new SetUpTearDownCommand( + new TestActionCommand( + new UnityLogCheckDelegatingCommand( + new EnumerableTestMethodCommand((TestMethod)command.Test)))))); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/BaseDelegator.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/BaseDelegator.cs new file mode 100644 index 00000000..65bcbbaa --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/BaseDelegator.cs @@ -0,0 +1,58 @@ +using System; +using System.Threading; +using NUnit.Framework.Internal; + +namespace UnityEngine.TestTools.NUnitExtensions +{ + internal abstract class BaseDelegator + { + protected ManualResetEvent m_Signal = new ManualResetEvent(false); + + protected object m_Result; + protected Exception m_Exception; + protected ITestExecutionContext m_Context; + + protected bool m_Aborted; + + protected object HandleResult() + { + SetCurrentTestContext(); + if (m_Exception != null) + { + var temp = m_Exception; + m_Exception = null; + throw temp; + } + var tempResult = m_Result; + m_Result = null; + return tempResult; + } + + protected void WaitForSignal() + { + while (!m_Signal.WaitOne(100)) + { + if (m_Aborted) + { + m_Aborted = false; + Reflect.MethodCallWrapper = null; + throw new Exception(); + } + } + } + + public void Abort() + { + m_Aborted = true; + } + + protected void SetCurrentTestContext() + { + var prop = typeof(TestExecutionContext).GetProperty("CurrentContext"); + if (prop != null) + { + prop.SetValue(null, m_Context, null); + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Commands/BeforeAfterTestCommandBase.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Commands/BeforeAfterTestCommandBase.cs new file mode 100644 index 00000000..af350f12 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Commands/BeforeAfterTestCommandBase.cs @@ -0,0 +1,196 @@ +using System; +using System.Collections; +using System.Linq; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; +using NUnit.Framework.Internal.Commands; +using UnityEngine.TestRunner.NUnitExtensions; +using UnityEngine.TestRunner.NUnitExtensions.Runner; +using UnityEngine.TestTools.Logging; +using UnityEngine.TestTools.TestRunner; + +namespace UnityEngine.TestTools +{ + internal abstract class BeforeAfterTestCommandBase : DelegatingTestCommand, IEnumerableTestMethodCommand + { + private string m_BeforeErrorPrefix; + private string m_AfterErrorPrefix; + private bool m_SkipYieldAfterActions; + protected BeforeAfterTestCommandBase(TestCommand innerCommand, string beforeErrorPrefix, string afterErrorPrefix, bool skipYieldAfterActions = false) + : base(innerCommand) + { + m_BeforeErrorPrefix = beforeErrorPrefix; + m_AfterErrorPrefix = afterErrorPrefix; + m_SkipYieldAfterActions = skipYieldAfterActions; + } + + protected T[] BeforeActions = new T[0]; + + protected T[] AfterActions = new T[0]; + + protected abstract IEnumerator InvokeBefore(T action, Test test, UnityTestExecutionContext context); + + protected abstract IEnumerator InvokeAfter(T action, Test test, UnityTestExecutionContext context); + + protected abstract BeforeAfterTestCommandState GetState(UnityTestExecutionContext context); + + public IEnumerable ExecuteEnumerable(ITestExecutionContext context) + { + var unityContext = (UnityTestExecutionContext)context; + var state = GetState(unityContext); + + if (state == null) + { + // We do not expect a state to exist in playmode + state = ScriptableObject.CreateInstance(); + } + + state.ApplyTestResult(context.CurrentResult); + + while (state.NextBeforeStepIndex < BeforeActions.Length) + { + var action = BeforeActions[state.NextBeforeStepIndex]; + var enumerator = InvokeBefore(action, Test, unityContext); + ActivePcHelper.SetEnumeratorPC(enumerator, state.NextBeforeStepPc); + + using (var logScope = new LogScope()) + { + while (true) + { + try + { + if (!enumerator.MoveNext()) + { + break; + } + } + catch (Exception ex) + { + state.TestHasRun = true; + context.CurrentResult.RecordPrefixedException(m_BeforeErrorPrefix, ex); + state.StoreTestResult(context.CurrentResult); + break; + } + + state.NextBeforeStepPc = ActivePcHelper.GetEnumeratorPC(enumerator); + state.StoreTestResult(context.CurrentResult); + if (m_SkipYieldAfterActions) + { + break; + } + else + { + yield return enumerator.Current; + } + } + + if (logScope.AnyFailingLogs()) + { + state.TestHasRun = true; + context.CurrentResult.RecordPrefixedError(m_BeforeErrorPrefix, new UnhandledLogMessageException(logScope.FailingLogs.First()).Message); + state.StoreTestResult(context.CurrentResult); + } + } + + state.NextBeforeStepIndex++; + state.NextBeforeStepPc = 0; + } + + if (!state.TestHasRun) + { + if (innerCommand is IEnumerableTestMethodCommand) + { + var executeEnumerable = ((IEnumerableTestMethodCommand)innerCommand).ExecuteEnumerable(context); + foreach (var iterator in executeEnumerable) + { + state.StoreTestResult(context.CurrentResult); + yield return iterator; + } + } + else + { + context.CurrentResult = innerCommand.Execute(context); + state.StoreTestResult(context.CurrentResult); + } + + state.TestHasRun = true; + } + + while (state.NextAfterStepIndex < AfterActions.Length) + { + state.TestAfterStarted = true; + var action = AfterActions[state.NextAfterStepIndex]; + var enumerator = InvokeAfter(action, Test, unityContext); + ActivePcHelper.SetEnumeratorPC(enumerator, state.NextAfterStepPc); + + using (var logScope = new LogScope()) + { + while (true) + { + try + { + if (!enumerator.MoveNext()) + { + break; + } + } + catch (Exception ex) + { + context.CurrentResult.RecordPrefixedException(m_AfterErrorPrefix, ex); + state.StoreTestResult(context.CurrentResult); + break; + } + + state.NextAfterStepPc = ActivePcHelper.GetEnumeratorPC(enumerator); + state.StoreTestResult(context.CurrentResult); + + if (m_SkipYieldAfterActions) + { + break; + } + else + { + yield return enumerator.Current; + } + } + + if (logScope.AnyFailingLogs()) + { + state.TestHasRun = true; + context.CurrentResult.RecordPrefixedError(m_AfterErrorPrefix, new UnhandledLogMessageException(logScope.FailingLogs.First()).Message); + state.StoreTestResult(context.CurrentResult); + } + } + + state.NextAfterStepIndex++; + state.NextAfterStepPc = 0; + } + + state.Reset(); + } + + public override TestResult Execute(ITestExecutionContext context) + { + throw new NotImplementedException("Use ExecuteEnumerable"); + } + + private static TestCommandPcHelper pcHelper; + + internal static TestCommandPcHelper ActivePcHelper + { + get + { + if (pcHelper == null) + { + pcHelper = new TestCommandPcHelper(); + } + + return pcHelper; + } + set + { + pcHelper = value; + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Commands/BeforeAfterTestCommandState.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Commands/BeforeAfterTestCommandState.cs new file mode 100644 index 00000000..273b61ca --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Commands/BeforeAfterTestCommandState.cs @@ -0,0 +1,49 @@ +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; + +namespace UnityEngine.TestTools +{ + internal class BeforeAfterTestCommandState : ScriptableObject + { + public int NextBeforeStepIndex; + public int NextBeforeStepPc; + public int NextAfterStepIndex; + public int NextAfterStepPc; + public bool TestHasRun; + public TestStatus CurrentTestResultStatus; + public string CurrentTestResultLabel; + public FailureSite CurrentTestResultSite; + public string CurrentTestMessage; + public string CurrentTestStrackTrace; + public bool TestAfterStarted; + + public void Reset() + { + NextBeforeStepIndex = 0; + NextBeforeStepPc = 0; + NextAfterStepIndex = 0; + NextAfterStepPc = 0; + TestHasRun = false; + CurrentTestResultStatus = TestStatus.Inconclusive; + CurrentTestResultLabel = null; + CurrentTestResultSite = default(FailureSite); + CurrentTestMessage = null; + CurrentTestStrackTrace = null; + TestAfterStarted = false; + } + + public void StoreTestResult(TestResult result) + { + CurrentTestResultStatus = result.ResultState.Status; + CurrentTestResultLabel = result.ResultState.Label; + CurrentTestResultSite = result.ResultState.Site; + CurrentTestMessage = result.Message; + CurrentTestStrackTrace = result.StackTrace; + } + + public void ApplyTestResult(TestResult result) + { + result.SetResult(new ResultState(CurrentTestResultStatus, CurrentTestResultLabel, CurrentTestResultSite), CurrentTestMessage, CurrentTestStrackTrace); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Commands/EnumerableApplyChangesToContextCommand.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Commands/EnumerableApplyChangesToContextCommand.cs new file mode 100644 index 00000000..d452f248 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Commands/EnumerableApplyChangesToContextCommand.cs @@ -0,0 +1,34 @@ + +using System.Collections; +using System.Collections.Generic; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; +using NUnit.Framework.Internal.Commands; +using UnityEngine.TestRunner.NUnitExtensions.Runner; + +namespace UnityEngine.TestTools +{ + internal class EnumerableApplyChangesToContextCommand : ApplyChangesToContextCommand, IEnumerableTestMethodCommand + { + public EnumerableApplyChangesToContextCommand(TestCommand innerCommand, IEnumerable changes) + : base(innerCommand, changes) { } + + public IEnumerable ExecuteEnumerable(ITestExecutionContext context) + { + ApplyChanges(context); + + if (innerCommand is IEnumerableTestMethodCommand) + { + var executeEnumerable = ((IEnumerableTestMethodCommand)innerCommand).ExecuteEnumerable(context); + foreach (var iterator in executeEnumerable) + { + yield return iterator; + } + } + else + { + context.CurrentResult = innerCommand.Execute(context); + } + } + } +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Commands/EnumerableSetUpTearDownCommand.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Commands/EnumerableSetUpTearDownCommand.cs new file mode 100644 index 00000000..e5bf7b81 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Commands/EnumerableSetUpTearDownCommand.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections; +using System.Linq; +using System.Reflection; +using NUnit.Framework.Internal; +using NUnit.Framework.Internal.Commands; +using UnityEngine.TestRunner.NUnitExtensions.Runner; + +namespace UnityEngine.TestTools +{ + internal class EnumerableSetUpTearDownCommand : BeforeAfterTestCommandBase + { + public EnumerableSetUpTearDownCommand(TestCommand innerCommand) + : base(innerCommand, "SetUp", "TearDown") + { + if (Test.TypeInfo.Type != null) + { + BeforeActions = GetMethodsWithAttributeFromFixture(Test.TypeInfo.Type, typeof(UnitySetUpAttribute)); + AfterActions = GetMethodsWithAttributeFromFixture(Test.TypeInfo.Type, typeof(UnityTearDownAttribute)).Reverse().ToArray(); + } + } + + private static MethodInfo[] GetMethodsWithAttributeFromFixture(Type fixtureType, Type setUpType) + { + MethodInfo[] methodsWithAttribute = Reflect.GetMethodsWithAttribute(fixtureType, setUpType, true); + return methodsWithAttribute.Where(x => x.ReturnType == typeof(IEnumerator)).ToArray(); + } + + protected override IEnumerator InvokeBefore(MethodInfo action, Test test, UnityTestExecutionContext context) + { + return (IEnumerator)Reflect.InvokeMethod(action, context.TestObject); + } + + protected override IEnumerator InvokeAfter(MethodInfo action, Test test, UnityTestExecutionContext context) + { + return (IEnumerator)Reflect.InvokeMethod(action, context.TestObject); + } + + protected override BeforeAfterTestCommandState GetState(UnityTestExecutionContext context) + { + return context.SetUpTearDownState; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Commands/EnumerableTestMethodCommand.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Commands/EnumerableTestMethodCommand.cs new file mode 100644 index 00000000..7a548ecf --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Commands/EnumerableTestMethodCommand.cs @@ -0,0 +1,86 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using NUnit.Framework; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; +using NUnit.Framework.Internal.Commands; +using NUnit.Framework.Internal.Execution; +using UnityEngine.TestRunner.NUnitExtensions.Runner; +using UnityEngine.TestTools.TestRunner; + +namespace UnityEngine.TestTools +{ + internal class EnumerableTestMethodCommand : TestCommand, IEnumerableTestMethodCommand + { + private readonly TestMethod testMethod; + + public EnumerableTestMethodCommand(TestMethod testMethod) + : base(testMethod) + { + this.testMethod = testMethod; + } + + public IEnumerable ExecuteEnumerable(ITestExecutionContext context) + { + yield return null; + + var currentExecutingTestEnumerator = new TestEnumeratorWrapper(testMethod).GetEnumerator(context); + if (currentExecutingTestEnumerator != null) + { + var testEnumeraterYieldInstruction = new TestEnumerator(context, currentExecutingTestEnumerator); + + yield return testEnumeraterYieldInstruction; + + var enumerator = testEnumeraterYieldInstruction.Execute(); + + var executingEnumerator = ExecuteEnumerableAndRecordExceptions(enumerator, context); + while (executingEnumerator.MoveNext()) + { + yield return executingEnumerator.Current; + } + } + else + { + if (context.CurrentResult.ResultState != ResultState.Ignored) + { + context.CurrentResult.SetResult(ResultState.Success); + } + } + } + + private static IEnumerator ExecuteEnumerableAndRecordExceptions(IEnumerator enumerator, ITestExecutionContext context) + { + while (true) + { + try + { + if (!enumerator.MoveNext()) + { + break; + } + } + catch (Exception ex) + { + context.CurrentResult.RecordException(ex); + break; + } + + if (enumerator.Current is IEnumerator) + { + var current = (IEnumerator)enumerator.Current; + yield return ExecuteEnumerableAndRecordExceptions(current, context); + } + else + { + yield return enumerator.Current; + } + } + } + + public override TestResult Execute(ITestExecutionContext context) + { + throw new NotImplementedException("Use ExecuteEnumerable"); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Commands/ImmediateEnumerableCommand.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Commands/ImmediateEnumerableCommand.cs new file mode 100644 index 00000000..ae1b7b7e --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Commands/ImmediateEnumerableCommand.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections; +using NUnit.Framework.Internal; +using NUnit.Framework.Internal.Commands; +using UnityEngine.TestRunner.NUnitExtensions.Runner; + +namespace UnityEngine.TestTools +{ + internal class ImmediateEnumerableCommand : DelegatingTestCommand + { + public ImmediateEnumerableCommand(TestCommand innerCommand) + : base(innerCommand) { } + + public override TestResult Execute(ITestExecutionContext context) + { + if (innerCommand is IEnumerableTestMethodCommand) + { + var executeEnumerable = ((IEnumerableTestMethodCommand)innerCommand).ExecuteEnumerable(context); + foreach (var iterator in executeEnumerable) + { + if (iterator != null) + { + throw new Exception("Only null can be yielded at this point."); + } + } + return context.CurrentResult; + } + + return innerCommand.Execute(context); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Commands/OuterUnityTestActionCommand.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Commands/OuterUnityTestActionCommand.cs new file mode 100644 index 00000000..a0646f13 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Commands/OuterUnityTestActionCommand.cs @@ -0,0 +1,49 @@ +using System.Collections; +using System.Collections.Generic; +using System.Reflection; +using NUnit.Framework.Internal; +using NUnit.Framework.Internal.Commands; +using UnityEngine.TestRunner.NUnitExtensions.Runner; + +namespace UnityEngine.TestTools +{ + internal class OuterUnityTestActionCommand : BeforeAfterTestCommandBase + { + public OuterUnityTestActionCommand(TestCommand innerCommand) + : base(innerCommand, "BeforeTest", "AfterTest") + { + if (Test.TypeInfo.Type != null) + { + BeforeActions = GetUnityTestActionsFromMethod(Test.Method.MethodInfo); + AfterActions = BeforeActions; + } + } + + private static IOuterUnityTestAction[] GetUnityTestActionsFromMethod(MethodInfo method) + { + var attributes = method.GetCustomAttributes(false); + List actions = new List(); + foreach (var attribute in attributes) + { + if (attribute is IOuterUnityTestAction) + actions.Add(attribute as IOuterUnityTestAction); + } + return actions.ToArray(); + } + + protected override IEnumerator InvokeBefore(IOuterUnityTestAction action, Test test, UnityTestExecutionContext context) + { + return action.BeforeTest(test); + } + + protected override IEnumerator InvokeAfter(IOuterUnityTestAction action, Test test, UnityTestExecutionContext context) + { + return action.AfterTest(test); + } + + protected override BeforeAfterTestCommandState GetState(UnityTestExecutionContext context) + { + return context.OuterUnityTestActionState; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Commands/SetUpTearDownCommand.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Commands/SetUpTearDownCommand.cs new file mode 100644 index 00000000..c6ff0d9c --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Commands/SetUpTearDownCommand.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections; +using System.Linq; +using System.Reflection; +using NUnit.Framework; +using NUnit.Framework.Internal; +using NUnit.Framework.Internal.Commands; +using NUnit.Framework.Internal.Execution; +using UnityEngine.TestRunner.NUnitExtensions.Runner; + +namespace UnityEngine.TestTools +{ + internal class SetUpTearDownCommand : BeforeAfterTestCommandBase + { + public SetUpTearDownCommand(TestCommand innerCommand) + : base(innerCommand, "SetUp", "TearDown", true) + { + if (Test.TypeInfo.Type != null) + { + BeforeActions = GetMethodsWithAttributeFromFixture(Test.TypeInfo.Type, typeof(SetUpAttribute)); + AfterActions = GetMethodsWithAttributeFromFixture(Test.TypeInfo.Type, typeof(TearDownAttribute)).Reverse().ToArray(); + } + } + + private static MethodInfo[] GetMethodsWithAttributeFromFixture(Type fixtureType, Type setUpType) + { + MethodInfo[] methodsWithAttribute = Reflect.GetMethodsWithAttribute(fixtureType, setUpType, true); + return methodsWithAttribute.Where(x => x.ReturnType == typeof(void)).ToArray(); + } + + protected override IEnumerator InvokeBefore(MethodInfo action, Test test, UnityTestExecutionContext context) + { + Reflect.InvokeMethod(action, context.TestObject); + yield return null; + } + + protected override IEnumerator InvokeAfter(MethodInfo action, Test test, UnityTestExecutionContext context) + { + Reflect.InvokeMethod(action, context.TestObject); + yield return null; + } + + protected override BeforeAfterTestCommandState GetState(UnityTestExecutionContext context) + { + return null; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Commands/TestActionCommand.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Commands/TestActionCommand.cs new file mode 100644 index 00000000..9b99dd0d --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Commands/TestActionCommand.cs @@ -0,0 +1,53 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Reflection; +using NUnit.Framework; +using NUnit.Framework.Internal; +using NUnit.Framework.Internal.Commands; +using UnityEngine.TestRunner.NUnitExtensions.Runner; + +namespace UnityEngine.TestTools +{ + internal class TestActionCommand : BeforeAfterTestCommandBase + { + public TestActionCommand(TestCommand innerCommand) + : base(innerCommand, "BeforeTest", "AfterTest", true) + { + if (Test.TypeInfo.Type != null) + { + BeforeActions = GetTestActionsFromMethod(Test.Method.MethodInfo); + AfterActions = BeforeActions; + } + } + + private static ITestAction[] GetTestActionsFromMethod(MethodInfo method) + { + var attributes = method.GetCustomAttributes(false); + List actions = new List(); + foreach (var attribute in attributes) + { + if (attribute is ITestAction) + actions.Add(attribute as ITestAction); + } + return actions.ToArray(); + } + + protected override IEnumerator InvokeBefore(ITestAction action, Test test, UnityTestExecutionContext context) + { + action.BeforeTest(test); + yield return null; + } + + protected override IEnumerator InvokeAfter(ITestAction action, Test test, UnityTestExecutionContext context) + { + action.AfterTest(test); + yield return null; + } + + protected override BeforeAfterTestCommandState GetState(UnityTestExecutionContext context) + { + return null; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Commands/TestCommandPcHelper.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Commands/TestCommandPcHelper.cs new file mode 100644 index 00000000..26eb4b03 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Commands/TestCommandPcHelper.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections; + +namespace UnityEngine.TestTools +{ + internal class TestCommandPcHelper + { + public virtual void SetEnumeratorPC(IEnumerator enumerator, int pc) + { + // Noop implementation used in playmode. + } + + public virtual int GetEnumeratorPC(IEnumerator enumerator) + { + return 0; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/ConstructDelegator.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/ConstructDelegator.cs new file mode 100644 index 00000000..dd7fbc29 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/ConstructDelegator.cs @@ -0,0 +1,141 @@ +using System; +using System.Linq; +using NUnit.Framework.Internal; +using UnityEngine.TestRunner.NUnitExtensions.Runner; +using UnityEngine.TestTools.Logging; +using UnityEngine.TestTools.TestRunner; + +namespace UnityEngine.TestTools.NUnitExtensions +{ + /// + /// Specialization of BaseDelegator that makes sure objects are created on the MainThread. + /// It also deals with ScriptableObjects so that tests can survive assembly reload. + /// + internal class ConstructDelegator + { + private Type m_RequestedType; + private object[] m_Arguments; + + private ScriptableObject m_CurrentRunningTest; + private readonly IStateSerializer m_StateSerializer; + + protected Exception m_Exception; + protected object m_Result; + protected ITestExecutionContext m_Context; + + public ConstructDelegator(IStateSerializer stateSerializer) + { + m_StateSerializer = stateSerializer; + } + + protected object HandleResult() + { + SetCurrentTestContext(); + if (m_Exception != null) + { + var temp = m_Exception; + m_Exception = null; + throw temp; + } + var tempResult = m_Result; + m_Result = null; + return tempResult; + } + + protected void SetCurrentTestContext() + { + var prop = typeof(UnityTestExecutionContext).GetProperty("CurrentContext"); + if (prop != null) + { + prop.SetValue(null, m_Context, null); + } + } + + public object Delegate(Type type, object[] arguments) + { + AssertState(); + m_Context = UnityTestExecutionContext.CurrentContext; + + m_RequestedType = type; + m_Arguments = arguments; + + using (var logScope = new LogScope()) + { + Execute(logScope); + } + + return HandleResult(); + } + + private void AssertState() + { + if (m_RequestedType != null) + { + throw new Exception("Constructor not executed yet"); + } + } + + public bool HasAction() + { + return m_RequestedType != null; + } + + public void Execute(LogScope logScope) + { + try + { + if (typeof(ScriptableObject).IsAssignableFrom(m_RequestedType)) + { + if (m_CurrentRunningTest != null && m_RequestedType != m_CurrentRunningTest.GetType()) + { + DestroyCurrentTestObjectIfExists(); + } + if (m_CurrentRunningTest == null) + { + if (m_StateSerializer.CanRestoreFromScriptableObject(m_RequestedType)) + { + m_CurrentRunningTest = m_StateSerializer.RestoreScriptableObjectInstance(); + } + else + { + m_CurrentRunningTest = ScriptableObject.CreateInstance(m_RequestedType); + } + } + m_Result = m_CurrentRunningTest; + } + else + { + DestroyCurrentTestObjectIfExists(); + m_Result = Activator.CreateInstance(m_RequestedType, m_Arguments); + if (m_StateSerializer.CanRestoreFromJson(m_RequestedType)) + { + m_StateSerializer.RestoreClassFromJson(ref m_Result); + } + } + if (logScope.AnyFailingLogs()) + { + var failingLog = logScope.FailingLogs.First(); + throw new UnhandledLogMessageException(failingLog); + } + if (logScope.ExpectedLogs.Any()) + throw new UnexpectedLogMessageException(LogScope.Current.ExpectedLogs.Peek()); + } + catch (Exception e) + { + m_Exception = e; + } + finally + { + m_RequestedType = null; + m_Arguments = null; + } + } + + public void DestroyCurrentTestObjectIfExists() + { + if (m_CurrentRunningTest == null) + return; + Object.DestroyImmediate(m_CurrentRunningTest); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Filters/AssemblyNameFilter.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Filters/AssemblyNameFilter.cs new file mode 100644 index 00000000..d53a2d0f --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Filters/AssemblyNameFilter.cs @@ -0,0 +1,25 @@ +using System; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal.Filters; + +namespace UnityEngine.TestRunner.NUnitExtensions.Filters +{ + internal class AssemblyNameFilter : ValueMatchFilter + { + public AssemblyNameFilter(string assemblyName) : base(assemblyName) {} + + public override bool Match(ITest test) + { + string assemblyName = string.Empty; + //Assembly fullname is in the format "Assembly-name, meta data ...", so extract the name by looking for the comma + if (test.TypeInfo != null && test.TypeInfo.Assembly != null && test.TypeInfo.FullName != null) + assemblyName = test.TypeInfo.Assembly.FullName.Substring(0, test.TypeInfo.Assembly.FullName.IndexOf(',')).TrimEnd(','); + return ExpectedValue.Equals(assemblyName, StringComparison.OrdinalIgnoreCase); + } + + protected override string ElementName + { + get { return "id"; } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Filters/CategoryFilterExtended.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Filters/CategoryFilterExtended.cs new file mode 100644 index 00000000..58430e8c --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Filters/CategoryFilterExtended.cs @@ -0,0 +1,36 @@ +using System.Collections; +using System.Linq; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; +using NUnit.Framework.Internal.Filters; + +namespace UnityEngine.TestRunner.NUnitExtensions.Filters +{ + internal class CategoryFilterExtended : CategoryFilter + { + public static string k_DefaultCategory = "Uncategorized"; + + public CategoryFilterExtended(string name) : base(name) + { + } + + public override bool Match(ITest test) + { + IList testCategories = test.Properties[PropertyNames.Category].Cast().ToList(); + + if (test is TestMethod) + { + // Do not count tests with no attribute as Uncategorized if test fixture class has at least one attribute + // The test inherits the attribute from the test fixture + IList fixtureCategories = test.Parent.Properties[PropertyNames.Category].Cast().ToList(); + if (fixtureCategories.Count > 0) + return false; + } + + if (testCategories.Count == 0 && ExpectedValue == k_DefaultCategory && test is TestMethod) + return true; + + return base.Match(test); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/IStateSerializer.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/IStateSerializer.cs new file mode 100644 index 00000000..951d079e --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/IStateSerializer.cs @@ -0,0 +1,12 @@ +using System; + +namespace UnityEngine.TestTools.NUnitExtensions +{ + internal interface IStateSerializer + { + ScriptableObject RestoreScriptableObjectInstance(); + void RestoreClassFromJson(ref object instance); + bool CanRestoreFromJson(Type requestedType); + bool CanRestoreFromScriptableObject(Type requestedType); + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Runner/CompositeWorkItem.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Runner/CompositeWorkItem.cs new file mode 100644 index 00000000..260e3cf8 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Runner/CompositeWorkItem.cs @@ -0,0 +1,342 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using NUnit.Framework; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; +using NUnit.Framework.Internal.Commands; +using NUnit.Framework.Internal.Execution; +using UnityEngine.TestTools.Logging; +using UnityEngine.TestTools.TestRunner; + +namespace UnityEngine.TestRunner.NUnitExtensions.Runner +{ + internal class CompositeWorkItem : UnityWorkItem + { + private readonly TestSuite _suite; + private readonly TestSuiteResult _suiteResult; + private readonly ITestFilter _childFilter; + private TestCommand _setupCommand; + private TestCommand _teardownCommand; + + public List Children { get; private set; } + + private int _countOrder; + + private CountdownEvent _childTestCountdown; + + public CompositeWorkItem(TestSuite suite, ITestFilter childFilter, WorkItemFactory factory) + : base(suite, factory) + { + _suite = suite; + _suiteResult = Result as TestSuiteResult; + _childFilter = childFilter; + _countOrder = 0; + } + + protected override IEnumerable PerformWork() + { + InitializeSetUpAndTearDownCommands(); + + if (UnityTestExecutionContext.CurrentContext != null && m_DontRunRestoringResult && EditModeTestCallbacks.RestoringTestContext != null) + { + EditModeTestCallbacks.RestoringTestContext(); + } + + if (!CheckForCancellation()) + if (Test.RunState == RunState.Explicit && !_childFilter.IsExplicitMatch(Test)) + SkipFixture(ResultState.Explicit, GetSkipReason(), null); + else + switch (Test.RunState) + { + default: + case RunState.Runnable: + case RunState.Explicit: + Result.SetResult(ResultState.Success); + + CreateChildWorkItems(); + + if (Children.Count > 0) + { + if (!m_DontRunRestoringResult) + { + //This is needed to give the editor a chance to go out of playmode if needed before creating objects. + //If we do not, the objects could be automatically destroyed when exiting playmode and could result in errors later on + yield return null; + PerformOneTimeSetUp(); + } + + if (!CheckForCancellation()) + { + switch (Result.ResultState.Status) + { + case TestStatus.Passed: + foreach (var child in RunChildren()) + { + if (CheckForCancellation()) + { + yield break; + } + + yield return child; + } + break; + case TestStatus.Skipped: + case TestStatus.Inconclusive: + case TestStatus.Failed: + SkipChildren(_suite, Result.ResultState.WithSite(FailureSite.Parent), "OneTimeSetUp: " + Result.Message); + break; + } + } + + if (Context.ExecutionStatus != TestExecutionStatus.AbortRequested && !m_DontRunRestoringResult) + { + PerformOneTimeTearDown(); + } + } + break; + + case RunState.Skipped: + SkipFixture(ResultState.Skipped, GetSkipReason(), null); + break; + + case RunState.Ignored: + SkipFixture(ResultState.Ignored, GetSkipReason(), null); + break; + + case RunState.NotRunnable: + SkipFixture(ResultState.NotRunnable, GetSkipReason(), GetProviderStackTrace()); + break; + } + if (!ResultedInDomainReload) + { + WorkItemComplete(); + } + } + + private bool CheckForCancellation() + { + if (Context.ExecutionStatus != TestExecutionStatus.Running) + { + Result.SetResult(ResultState.Cancelled, "Test cancelled by user"); + return true; + } + + return false; + } + + private void InitializeSetUpAndTearDownCommands() + { + List setUpTearDownItems = _suite.TypeInfo != null + ? CommandBuilder.BuildSetUpTearDownList(_suite.TypeInfo.Type, typeof(OneTimeSetUpAttribute), typeof(OneTimeTearDownAttribute)) + : new List(); + + var actionItems = new List(); + foreach (ITestAction action in Actions) + { + bool applyToSuite = (action.Targets & ActionTargets.Suite) == ActionTargets.Suite + || action.Targets == ActionTargets.Default && !(Test is ParameterizedMethodSuite); + + bool applyToTest = (action.Targets & ActionTargets.Test) == ActionTargets.Test + && !(Test is ParameterizedMethodSuite); + + if (applyToSuite) + actionItems.Add(new TestActionItem(action)); + + if (applyToTest) + Context.UpstreamActions.Add(action); + } + + _setupCommand = CommandBuilder.MakeOneTimeSetUpCommand(_suite, setUpTearDownItems, actionItems); + _teardownCommand = CommandBuilder.MakeOneTimeTearDownCommand(_suite, setUpTearDownItems, actionItems); + } + + private void PerformOneTimeSetUp() + { + var logScope = new LogScope(); + try + { + _setupCommand.Execute(Context); + } + catch (Exception ex) + { + if (ex is NUnitException || ex is TargetInvocationException) + ex = ex.InnerException; + + Result.RecordException(ex, FailureSite.SetUp); + } + + if (logScope.AnyFailingLogs()) + { + Result.RecordException(new UnhandledLogMessageException(logScope.FailingLogs.First())); + } + logScope.Dispose(); + } + + private IEnumerable RunChildren() + { + int childCount = Children.Count; + if (childCount == 0) + throw new InvalidOperationException("RunChildren called but item has no children"); + + _childTestCountdown = new CountdownEvent(childCount); + + foreach (UnityWorkItem child in Children) + { + if (CheckForCancellation()) + { + yield break; + } + + var unityTestExecutionContext = new UnityTestExecutionContext(Context); + child.InitializeContext(unityTestExecutionContext); + + var enumerable = child.Execute().GetEnumerator(); + + while (true) + { + if (!enumerable.MoveNext()) + { + break; + } + ResultedInDomainReload |= child.ResultedInDomainReload; + yield return enumerable.Current; + } + + _suiteResult.AddResult(child.Result); + childCount--; + } + + if (childCount > 0) + { + while (childCount-- > 0) + CountDownChildTest(); + } + } + + private void CreateChildWorkItems() + { + Children = new List(); + var testSuite = _suite; + + foreach (ITest test in testSuite.Tests) + { + if (_childFilter.Pass(test)) + { + var child = m_Factory.Create(test, _childFilter); + + if (test.Properties.ContainsKey(PropertyNames.Order)) + { + Children.Insert(0, child); + _countOrder++; + } + else + { + Children.Add(child); + } + } + } + + if (_countOrder != 0) SortChildren(); + } + + private class UnityWorkItemOrderComparer : IComparer + { + public int Compare(UnityWorkItem x, UnityWorkItem y) + { + var xKey = int.MaxValue; + var yKey = int.MaxValue; + + if (x.Test.Properties.ContainsKey(PropertyNames.Order)) + xKey = (int)x.Test.Properties[PropertyNames.Order][0]; + + if (y.Test.Properties.ContainsKey(PropertyNames.Order)) + yKey = (int)y.Test.Properties[PropertyNames.Order][0]; + + return xKey.CompareTo(yKey); + } + } + + private void SortChildren() + { + Children.Sort(0, _countOrder, new UnityWorkItemOrderComparer()); + } + + private void SkipFixture(ResultState resultState, string message, string stackTrace) + { + Result.SetResult(resultState.WithSite(FailureSite.SetUp), message, StackFilter.Filter(stackTrace)); + SkipChildren(_suite, resultState.WithSite(FailureSite.Parent), "OneTimeSetUp: " + message); + } + + private void SkipChildren(TestSuite suite, ResultState resultState, string message) + { + foreach (Test child in suite.Tests) + { + if (_childFilter.Pass(child)) + { + Context.Listener.TestStarted(child); + TestResult childResult = child.MakeTestResult(); + childResult.SetResult(resultState, message); + _suiteResult.AddResult(childResult); + + if (child.IsSuite) + SkipChildren((TestSuite)child, resultState, message); + + Context.Listener.TestFinished(childResult); + } + } + } + + private void PerformOneTimeTearDown() + { + _teardownCommand.Execute(Context); + } + + private string GetSkipReason() + { + return (string)Test.Properties.Get(PropertyNames.SkipReason); + } + + private string GetProviderStackTrace() + { + return (string)Test.Properties.Get(PropertyNames.ProviderStackTrace); + } + + private void CountDownChildTest() + { + _childTestCountdown.Signal(); + if (_childTestCountdown.CurrentCount == 0) + { + if (Context.ExecutionStatus != TestExecutionStatus.AbortRequested) + PerformOneTimeTearDown(); + + foreach (var childResult in _suiteResult.Children) + if (childResult.ResultState == ResultState.Cancelled) + { + this.Result.SetResult(ResultState.Cancelled, "Cancelled by user"); + break; + } + + WorkItemComplete(); + } + } + + public override void Cancel(bool force) + { + if (Children == null) + return; + + foreach (var child in Children) + { + var ctx = child.Context; + if (ctx != null) + ctx.ExecutionStatus = force ? TestExecutionStatus.AbortRequested : TestExecutionStatus.StopRequested; + + if (child.State == WorkItemState.Running) + child.Cancel(force); + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Runner/CoroutineTestWorkItem.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Runner/CoroutineTestWorkItem.cs new file mode 100644 index 00000000..3ec037b6 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Runner/CoroutineTestWorkItem.cs @@ -0,0 +1,77 @@ +using System; +using System.Collections; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; +using NUnit.Framework.Internal.Commands; +using NUnit.Framework.Internal.Execution; +using UnityEngine.TestTools.Utils; + +namespace UnityEngine.TestRunner.NUnitExtensions.Runner +{ + internal class CoroutineTestWorkItem : UnityWorkItem + { + private static MonoBehaviour m_MonoBehaviourCoroutineRunner; + private TestCommand m_Command; + + public static MonoBehaviour monoBehaviourCoroutineRunner + { + get + { + if (m_MonoBehaviourCoroutineRunner == null) + { + throw new NullReferenceException("MonoBehaviour coroutine runner not set"); + } + return m_MonoBehaviourCoroutineRunner; + } + set { m_MonoBehaviourCoroutineRunner = value; } + } + + public CoroutineTestWorkItem(TestMethod test, ITestFilter filter) + : base(test, null) + { + m_Command = test.RunState == RunState.Runnable || test.RunState == RunState.Explicit && filter.IsExplicitMatch(test) + ? CommandBuilder.MakeTestCommand(test) + : CommandBuilder.MakeSkipCommand(test); + } + + protected override IEnumerable PerformWork() + { + if (m_Command is SkipCommand) + { + m_Command.Execute(Context); + Result = Context.CurrentResult; + WorkItemComplete(); + yield break; + } + + if (m_Command is ApplyChangesToContextCommand) + { + var applyChangesToContextCommand = (ApplyChangesToContextCommand)m_Command; + applyChangesToContextCommand.ApplyChanges(Context); + m_Command = applyChangesToContextCommand.GetInnerCommand(); + } + + var enumerableTestMethodCommand = (IEnumerableTestMethodCommand)m_Command; + try + { + var executeEnumerable = enumerableTestMethodCommand.ExecuteEnumerable(Context).GetEnumerator(); + + var coroutineRunner = new CoroutineRunner(monoBehaviourCoroutineRunner, Context); + yield return coroutineRunner.HandleEnumerableTest(executeEnumerable); + + if (coroutineRunner.HasFailedWithTimeout()) + { + Context.CurrentResult.SetResult(ResultState.Failure, string.Format("Test exceeded Timeout value of {0}ms", Context.TestCaseTimeout)); + } + + while (executeEnumerable.MoveNext()) {} + + Result = Context.CurrentResult; + } + finally + { + WorkItemComplete(); + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Runner/DefaultTestWorkItem.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Runner/DefaultTestWorkItem.cs new file mode 100644 index 00000000..36dfb1ae --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Runner/DefaultTestWorkItem.cs @@ -0,0 +1,137 @@ +using System; +using System.Collections; +using System.Linq; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; +using NUnit.Framework.Internal.Commands; +using NUnit.Framework.Internal.Execution; +using UnityEngine.TestTools; +using SetUpTearDownCommand = NUnit.Framework.Internal.Commands.SetUpTearDownCommand; +using TestActionCommand = NUnit.Framework.Internal.Commands.TestActionCommand; + +namespace UnityEngine.TestRunner.NUnitExtensions.Runner +{ + internal class EditModeTestCallbacks + { + public static Action RestoringTestContext { get; set; } + } + + internal class DefaultTestWorkItem : UnityWorkItem + { + private TestCommand _command; + + public DefaultTestWorkItem(TestMethod test, ITestFilter filter) + : base(test, null) + { + _command = test.RunState == RunState.Runnable || test.RunState == RunState.Explicit && filter.IsExplicitMatch(test) + ? BuildTestCommand(test) + : new SkipCommand(test); + } + + private static TestCommand BuildTestCommand(TestMethod test) + { + var command = (TestCommand)new TestMethodCommand(test); + command = new UnityLogCheckDelegatingCommand(command); + foreach (var wrapper in test.Method.GetCustomAttributes(true)) + { + command = wrapper.Wrap(command); + if (command == null) + { + var message = string.Format("IWrapTestMethod implementation '{0}' returned null as command.", wrapper.GetType().FullName); + return new FailCommand(test, ResultState.Failure, message); + } + } + + command = new TestTools.TestActionCommand(command); + command = new TestTools.SetUpTearDownCommand(command); + command = new ImmediateEnumerableCommand(command); + foreach (var wrapper in test.Method.GetCustomAttributes(true)) + { + command = wrapper.Wrap(command); + if (command == null) + { + var message = string.Format("IWrapSetUpTearDown implementation '{0}' returned null as command.", wrapper.GetType().FullName); + return new FailCommand(test, ResultState.Failure, message); + } + } + + command = new EnumerableSetUpTearDownCommand(command); + command = new OuterUnityTestActionCommand(command); + + IApplyToContext[] changes = test.Method.GetCustomAttributes(true); + if (changes.Length > 0) + { + command = new EnumerableApplyChangesToContextCommand(command, changes); + } + + return command; + } + + protected override IEnumerable PerformWork() + { + if (m_DontRunRestoringResult && EditModeTestCallbacks.RestoringTestContext != null) + { + EditModeTestCallbacks.RestoringTestContext(); + Result = Context.CurrentResult; + yield break; + } + + try + { + if (_command is SkipCommand || _command is FailCommand) + { + Result = _command.Execute(Context); + yield break; + } + + if (!(_command is IEnumerableTestMethodCommand)) + { + Debug.LogError("Cannot perform work on " + _command.GetType().Name); + yield break; + } + + foreach (var workItemStep in ((IEnumerableTestMethodCommand)_command).ExecuteEnumerable(Context)) + { + ResultedInDomainReload = false; + + if (workItemStep is IEditModeTestYieldInstruction) + { + var editModeTestYieldInstruction = (IEditModeTestYieldInstruction)workItemStep; + yield return editModeTestYieldInstruction; + var enumerator = editModeTestYieldInstruction.Perform(); + while (true) + { + bool moveNext; + try + { + moveNext = enumerator.MoveNext(); + } + catch (Exception e) + { + Context.CurrentResult.RecordException(e); + break; + } + + if (!moveNext) + { + break; + } + + yield return null; + } + } + else + { + yield return workItemStep; + } + } + + Result = Context.CurrentResult; + } + finally + { + WorkItemComplete(); + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Runner/FailCommand.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Runner/FailCommand.cs new file mode 100644 index 00000000..f710da02 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Runner/FailCommand.cs @@ -0,0 +1,27 @@ + +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; +using NUnit.Framework.Internal.Commands; + +namespace UnityEngine.TestRunner.NUnitExtensions.Runner +{ + internal class FailCommand : TestCommand + { + private ResultState m_ResultState; + private string m_Message; + + public FailCommand(Test test, ResultState resultState, string message) + : base(test) + { + m_ResultState = resultState; + m_Message = message; + } + + public override TestResult Execute(ITestExecutionContext context) + { + context.CurrentResult.SetResult(m_ResultState, m_Message); + return context.CurrentResult; + } + } + +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Runner/IEnumerableTestMethodCommand.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Runner/IEnumerableTestMethodCommand.cs new file mode 100644 index 00000000..758e2956 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Runner/IEnumerableTestMethodCommand.cs @@ -0,0 +1,10 @@ +using System.Collections; +using NUnit.Framework.Internal; + +namespace UnityEngine.TestRunner.NUnitExtensions.Runner +{ + internal interface IEnumerableTestMethodCommand + { + IEnumerable ExecuteEnumerable(ITestExecutionContext context); + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Runner/PlaymodeWorkItemFactory.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Runner/PlaymodeWorkItemFactory.cs new file mode 100644 index 00000000..5d32f268 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Runner/PlaymodeWorkItemFactory.cs @@ -0,0 +1,13 @@ +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; + +namespace UnityEngine.TestRunner.NUnitExtensions.Runner +{ + internal class PlaymodeWorkItemFactory : WorkItemFactory + { + protected override UnityWorkItem Create(TestMethod method, ITestFilter filter, ITest loadedTest) + { + return new CoroutineTestWorkItem(method, filter); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Runner/RestoreTestContextAfterDomainReload.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Runner/RestoreTestContextAfterDomainReload.cs new file mode 100644 index 00000000..e05910ab --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Runner/RestoreTestContextAfterDomainReload.cs @@ -0,0 +1,4 @@ +namespace UnityEngine.TestRunner.NUnitExtensions.Runner +{ + internal class RestoreTestContextAfterDomainReload {} +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Runner/UnityLogCheckDelegatingCommand.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Runner/UnityLogCheckDelegatingCommand.cs new file mode 100644 index 00000000..7e6ac655 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Runner/UnityLogCheckDelegatingCommand.cs @@ -0,0 +1,106 @@ +using System; +using System.Collections; +using System.Linq; +using NUnit.Framework.Internal; +using NUnit.Framework.Internal.Commands; +using UnityEngine.TestTools.Logging; +using UnityEngine.TestTools.TestRunner; + +namespace UnityEngine.TestRunner.NUnitExtensions.Runner +{ + internal class UnityLogCheckDelegatingCommand : DelegatingTestCommand, IEnumerableTestMethodCommand + { + public UnityLogCheckDelegatingCommand(TestCommand innerCommand) + : base(innerCommand) {} + + public override TestResult Execute(ITestExecutionContext context) + { + var logCollector = new LogScope(); + + try + { + innerCommand.Execute(context); + + if (logCollector.AnyFailingLogs()) + { + var failingLog = logCollector.FailingLogs.First(); + throw new UnhandledLogMessageException(failingLog); + } + + if (logCollector.ExpectedLogs.Any()) + { + throw new UnexpectedLogMessageException(logCollector.ExpectedLogs.Peek()); + } + } + catch (Exception exception) + { + context.CurrentResult.RecordException(exception); + } + logCollector.Dispose(); + return context.CurrentResult; + } + + public IEnumerable ExecuteEnumerable(ITestExecutionContext context) + { + var logCollector = new LogScope(); + + if (!(innerCommand is IEnumerableTestMethodCommand)) + { + Execute(context); + yield break; + } + + var enumerableTestMethodCommand = (IEnumerableTestMethodCommand)innerCommand; + + IEnumerable executeEnumerable; + + try + { + executeEnumerable = enumerableTestMethodCommand.ExecuteEnumerable(context); + } + catch (Exception e) + { + context.CurrentResult.RecordException(e); + yield break; + } + + foreach (var step in executeEnumerable) + { + try + { + if (logCollector.AnyFailingLogs()) + { + var failingLog = logCollector.FailingLogs.First(); + throw new UnhandledLogMessageException(failingLog); + } + } + catch (Exception e) + { + context.CurrentResult.RecordException(e); + break; + } + yield return step; + } + + try + { + if (logCollector.AnyFailingLogs()) + { + var failingLog = logCollector.FailingLogs.First(); + throw new UnhandledLogMessageException(failingLog); + } + + logCollector.ProcessExpectedLogs(); + if (logCollector.ExpectedLogs.Any()) + { + throw new UnexpectedLogMessageException(LogScope.Current.ExpectedLogs.Peek()); + } + } + catch (Exception exception) + { + context.CurrentResult.RecordException(exception); + } + logCollector.Dispose(); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Runner/UnityTestAssemblyRunner.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Runner/UnityTestAssemblyRunner.cs new file mode 100644 index 00000000..8c9339aa --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Runner/UnityTestAssemblyRunner.cs @@ -0,0 +1,96 @@ +using System.Collections; +using System.Collections.Generic; +using System.Reflection; +using NUnit; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; +using UnityEngine.TestTools.NUnitExtensions; + +namespace UnityEngine.TestRunner.NUnitExtensions.Runner +{ + internal interface IUnityTestAssemblyRunner + { + ITest LoadedTest { get; } + ITestResult Result { get; } + bool IsTestLoaded { get; } + bool IsTestRunning { get; } + bool IsTestComplete { get; } + UnityWorkItem TopLevelWorkItem { get; set; } + UnityTestExecutionContext GetCurrentContext(); + ITest Load(Assembly[] assemblies, IDictionary settings); + IEnumerable Run(ITestListener listener, ITestFilter filter); + void StopRun(); + } + + internal class UnityTestAssemblyRunner : IUnityTestAssemblyRunner + { + private readonly UnityTestAssemblyBuilder unityBuilder; + private readonly WorkItemFactory m_Factory; + + protected UnityTestExecutionContext Context { get; set; } + + public UnityTestExecutionContext GetCurrentContext() + { + return UnityTestExecutionContext.CurrentContext; + } + + protected IDictionary Settings { get; set; } + public ITest LoadedTest { get; protected set; } + + public ITestResult Result + { + get { return TopLevelWorkItem == null ? null : TopLevelWorkItem.Result; } + } + + public bool IsTestLoaded + { + get { return LoadedTest != null; } + } + + public bool IsTestRunning + { + get { return TopLevelWorkItem != null && TopLevelWorkItem.State == NUnit.Framework.Internal.Execution.WorkItemState.Running; } + } + public bool IsTestComplete + { + get { return TopLevelWorkItem != null && TopLevelWorkItem.State == NUnit.Framework.Internal.Execution.WorkItemState.Complete; } + } + + public UnityTestAssemblyRunner(UnityTestAssemblyBuilder builder, WorkItemFactory factory) + { + unityBuilder = builder; + m_Factory = factory; + Context = new UnityTestExecutionContext(); + } + + public ITest Load(Assembly[] assemblies, IDictionary settings) + { + Settings = settings; + + if (settings.ContainsKey(FrameworkPackageSettings.RandomSeed)) + Randomizer.InitialSeed = (int)settings[FrameworkPackageSettings.RandomSeed]; + + return LoadedTest = unityBuilder.Build(assemblies, settings); + } + + public IEnumerable Run(ITestListener listener, ITestFilter filter) + { + TopLevelWorkItem = m_Factory.Create(LoadedTest, filter); + TopLevelWorkItem.InitializeContext(Context); + UnityTestExecutionContext.CurrentContext = Context; + Context.Listener = listener; + + return TopLevelWorkItem.Execute(); + } + + public UnityWorkItem TopLevelWorkItem { get; set; } + + public void StopRun() + { + if (IsTestRunning) + { + TopLevelWorkItem.Cancel(false); + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Runner/UnityTestExecutionContext.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Runner/UnityTestExecutionContext.cs new file mode 100644 index 00000000..dd58c14a --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Runner/UnityTestExecutionContext.cs @@ -0,0 +1,128 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using NUnit.Framework; +using NUnit.Framework.Constraints; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; +using NUnit.Framework.Internal.Execution; +using UnityEngine.TestTools; + +namespace UnityEngine.TestRunner.NUnitExtensions.Runner +{ + internal class UnityTestExecutionContext : ITestExecutionContext + { + private readonly UnityTestExecutionContext _priorContext; + private TestResult _currentResult; + private int _assertCount; + + public static UnityTestExecutionContext CurrentContext { get; set; } + + public UnityTestExecutionContext Context { get; private set; } + + public Test CurrentTest { get; set; } + public DateTime StartTime { get; set; } + public long StartTicks { get; set; } + public TestResult CurrentResult + { + get { return _currentResult; } + set + { + _currentResult = value; + if (value != null) + OutWriter = value.OutWriter; + } + } + + public object TestObject { get; set; } + public string WorkDirectory { get; set; } + + + private TestExecutionStatus _executionStatus; + public TestExecutionStatus ExecutionStatus + { + get + { + // ExecutionStatus may have been set to StopRequested or AbortRequested + // in a prior context. If so, reflect the same setting in this context. + if (_executionStatus == TestExecutionStatus.Running && _priorContext != null) + _executionStatus = _priorContext.ExecutionStatus; + + return _executionStatus; + } + set + { + _executionStatus = value; + + // Push the same setting up to all prior contexts + if (_priorContext != null) + _priorContext.ExecutionStatus = value; + } + } + + public List UpstreamActions { get; private set; } + public int TestCaseTimeout { get; set; } + public CultureInfo CurrentCulture { get; set; } + public CultureInfo CurrentUICulture { get; set; } + public ITestListener Listener { get; set; } + + public UnityTestExecutionContext() + { + UpstreamActions = new List(); + CurrentContext = this; + } + + public UnityTestExecutionContext(UnityTestExecutionContext other) + { + _priorContext = other; + + CurrentTest = other.CurrentTest; + CurrentResult = other.CurrentResult; + TestObject = other.TestObject; + WorkDirectory = other.WorkDirectory; + Listener = other.Listener; + TestCaseTimeout = other.TestCaseTimeout; + UpstreamActions = new List(other.UpstreamActions); + SetUpTearDownState = other.SetUpTearDownState; + OuterUnityTestActionState = other.OuterUnityTestActionState; + + TestContext.CurrentTestExecutionContext = this; + + CurrentCulture = other.CurrentCulture; + CurrentUICulture = other.CurrentUICulture; + CurrentContext = this; + } + + public TextWriter OutWriter { get; private set; } + public bool StopOnError { get; set; } + + public IWorkItemDispatcher Dispatcher { get; set; } + + public ParallelScope ParallelScope { get; set; } + public string WorkerId { get; private set; } + public Randomizer RandomGenerator { get; private set; } + public ValueFormatter CurrentValueFormatter { get; private set; } + public bool IsSingleThreaded { get; set; } + public BeforeAfterTestCommandState SetUpTearDownState { get; set; } + public BeforeAfterTestCommandState OuterUnityTestActionState { get; set; } + + internal int AssertCount + { + get + { + return _assertCount; + } + } + + public void IncrementAssertCount() + { + _assertCount += 1; + } + + public void AddFormatter(ValueFormatterFactory formatterFactory) + { + throw new NotImplementedException(); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Runner/UnityWorkItem.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Runner/UnityWorkItem.cs new file mode 100644 index 00000000..71bddbd6 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Runner/UnityWorkItem.cs @@ -0,0 +1,112 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using NUnit.Framework; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; +using NUnit.Framework.Internal.Execution; + +namespace UnityEngine.TestRunner.NUnitExtensions.Runner +{ + internal abstract class UnityWorkItem + { + protected readonly WorkItemFactory m_Factory; + protected bool m_ExecuteTestStartEvent; + protected bool m_DontRunRestoringResult; + public event EventHandler Completed; + + public bool ResultedInDomainReload { get; internal set; } + + public UnityTestExecutionContext Context { get; private set; } + + public Test Test { get; private set; } + + public TestResult Result { get; protected set; } + + public WorkItemState State { get; private set; } + + public List Actions { get; private set; } + + protected UnityWorkItem(Test test, WorkItemFactory factory) + { + m_Factory = factory; + Test = test; + Actions = new List(); + Result = test.MakeTestResult(); + State = WorkItemState.Ready; + m_ExecuteTestStartEvent = ShouldExecuteStartEvent(); + m_DontRunRestoringResult = ShouldRestore(test); + } + + protected static bool ShouldRestore(ITest loadedTest) + { + return UnityWorkItemDataHolder.alreadyExecutedTests != null && UnityWorkItemDataHolder.alreadyExecutedTests.Contains(loadedTest.FullName); + } + + protected bool ShouldExecuteStartEvent() + { + return UnityWorkItemDataHolder.alreadyStartedTests != null && UnityWorkItemDataHolder.alreadyStartedTests.All(x => x != Test.FullName) && !ShouldRestore(Test); + } + + protected abstract IEnumerable PerformWork(); + + public void InitializeContext(UnityTestExecutionContext context) + { + Context = context; + + if (Test is TestAssembly) + Actions.AddRange(ActionsHelper.GetActionsFromTestAssembly((TestAssembly)Test)); + else if (Test is ParameterizedMethodSuite) + Actions.AddRange(ActionsHelper.GetActionsFromTestMethodInfo(Test.Method)); + else if (Test.TypeInfo != null) + Actions.AddRange(ActionsHelper.GetActionsFromTypesAttributes(Test.TypeInfo.Type)); + } + + public virtual IEnumerable Execute() + { + Context.CurrentTest = this.Test; + Context.CurrentResult = this.Result; + + if (m_ExecuteTestStartEvent) + { + Context.Listener.TestStarted(Test); + } + + Context.StartTime = DateTime.UtcNow; + Context.StartTicks = Stopwatch.GetTimestamp(); + + State = WorkItemState.Running; + + return PerformWork(); + } + + protected void WorkItemComplete() + { + State = WorkItemState.Complete; + + Result.StartTime = Context.StartTime; + Result.EndTime = DateTime.UtcNow; + + long tickCount = Stopwatch.GetTimestamp() - Context.StartTicks; + double seconds = (double)tickCount / Stopwatch.Frequency; + Result.Duration = seconds; + + //Result.AssertCount += Context.AssertCount; + + Context.Listener.TestFinished(Result); + + if (Completed != null) + Completed(this, EventArgs.Empty); + + Context.TestObject = null; + Test.Fixture = null; + } + + public virtual void Cancel(bool force) + { + Context.Listener.TestFinished(Result); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Runner/UnityWorkItemDataHolder.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Runner/UnityWorkItemDataHolder.cs new file mode 100644 index 00000000..d9fb7004 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Runner/UnityWorkItemDataHolder.cs @@ -0,0 +1,10 @@ +using System.Collections.Generic; + +namespace UnityEngine.TestRunner.NUnitExtensions.Runner +{ + internal class UnityWorkItemDataHolder + { + public static List alreadyStartedTests = new List(); + public static List alreadyExecutedTests; + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Runner/WorkItemFactory.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Runner/WorkItemFactory.cs new file mode 100644 index 00000000..94d9c0fe --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/Runner/WorkItemFactory.cs @@ -0,0 +1,28 @@ +using System.Collections; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; + +namespace UnityEngine.TestRunner.NUnitExtensions.Runner +{ + internal abstract class WorkItemFactory + { + public UnityWorkItem Create(ITest loadedTest, ITestFilter filter) + { + TestSuite suite = loadedTest as TestSuite; + if (suite != null) + { + return new CompositeWorkItem(suite, filter, this); + } + + var testMethod = (TestMethod)loadedTest; + if (testMethod.Method.ReturnType.Type != typeof(IEnumerator)) + { + return new DefaultTestWorkItem(testMethod, filter); + } + + return Create(testMethod, filter, loadedTest); + } + + protected abstract UnityWorkItem Create(TestMethod method, ITestFilter filter, ITest loadedTest); + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/TestExtensions.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/TestExtensions.cs new file mode 100644 index 00000000..5d353074 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/TestExtensions.cs @@ -0,0 +1,138 @@ +using System.Collections.Generic; +using System.Linq; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; +using UnityEngine.TestRunner.NUnitExtensions.Filters; + +namespace UnityEngine.TestRunner.NUnitExtensions +{ + internal static class TestExtensions + { + private static IEnumerable GetTestCategories(this ITest test) + { + var categories = test.Properties[PropertyNames.Category].Cast().ToList(); + if (categories.Count == 0 && test is TestMethod) + { + // only mark tests as Uncategorized if the test fixture doesn't have a category, + // otherwise the test inherits the Fixture category + var fixtureCategories = test.Parent.Properties[PropertyNames.Category].Cast().ToList(); + if (fixtureCategories.Count == 0) + categories.Add(CategoryFilterExtended.k_DefaultCategory); + } + return categories; + } + + public static bool HasCategory(this ITest test, string[] categoryFilter) + { + var categories = test.GetAllCategoriesFromTest().Distinct(); + return categoryFilter.Any(c => categories.Any(r => r == c)); + } + + public static List GetAllCategoriesFromTest(this ITest test) + { + if (test.Parent == null) + return test.GetTestCategories().ToList(); + + var categories = GetAllCategoriesFromTest(test.Parent); + categories.AddRange(test.GetTestCategories()); + return categories; + } + + public static void ParseForNameDuplicates(this ITest test) + { + var duplicates = new Dictionary(); + for (var i = 0; i < test.Tests.Count; i++) + { + var child = test.Tests[i]; + int count; + if (duplicates.TryGetValue(child.FullName, out count)) + { + count++; + child.Properties.Add("childIndex", count); + duplicates[child.FullName] = count; + } + else + { + duplicates.Add(child.FullName, 1); + } + ParseForNameDuplicates(child); + } + } + + public static int GetChildIndex(this ITest test) + { + var index = test.Properties["childIndex"]; + return (int)index[0]; + } + + public static bool HasChildIndex(this ITest test) + { + var index = test.Properties["childIndex"]; + return index.Count > 0; + } + + static string GetAncestorPath(ITest test) + { + var path = ""; + var testParent = test.Parent; + + while (testParent != null && testParent.Parent != null && !string.IsNullOrEmpty(testParent.Name)) + { + path = testParent.Name + "/" + path; + testParent = testParent.Parent; + } + + return path; + } + + public static string GetUniqueName(this ITest test) + { + var id = GetAncestorPath(test) + GetFullName(test); + if (test.HasChildIndex()) + { + var index = test.GetChildIndex(); + if (index >= 0) + id += index; + } + if (test.IsSuite) + { + id += "[suite]"; + } + return id; + } + + public static string GetFullName(ITest test) + { + if (test.TypeInfo == null && (test.Parent == null || test.Parent.TypeInfo == null)) + { + return "[" + test.FullName + "]"; + } + var assemblyId = test.TypeInfo == null ? test.Parent.TypeInfo.Assembly.GetName().Name : test.TypeInfo.Assembly.GetName().Name; + return string.Format("[{0}][{1}]", assemblyId, test.FullName); + } + + public static string GetSkipReason(this ITest test) + { + if (test.Properties.ContainsKey(PropertyNames.SkipReason)) + return (string)test.Properties.Get(PropertyNames.SkipReason); + + return null; + } + + public static string GetParentId(this ITest test) + { + if (test.Parent != null) + return test.Parent.Id; + + return null; + } + + public static string GetParentUniqueName(this ITest test) + { + if (test.Parent != null) + return GetUniqueName(test.Parent); + + return null; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/TestResultExtensions.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/TestResultExtensions.cs new file mode 100644 index 00000000..d79072b0 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/TestResultExtensions.cs @@ -0,0 +1,77 @@ +using System; +using NUnit.Framework; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; + +namespace UnityEngine.TestRunner.NUnitExtensions +{ + internal static class TestResultExtensions + { + public static void RecordPrefixedException(this TestResult testResult, string prefix, Exception ex, ResultState resultState = null) + + { + if (ex is NUnitException) + { + ex = ex.InnerException; + } + + if (resultState == null) + { + resultState = testResult.ResultState == ResultState.Cancelled + ? ResultState.Cancelled + : ResultState.Error; + } + + var exceptionMessage = ExceptionHelper.BuildMessage(ex); + string stackTrace = "--" + prefix + NUnit.Env.NewLine + ExceptionHelper.BuildStackTrace(ex); + if (testResult.StackTrace != null) + { + stackTrace = testResult.StackTrace + NUnit.Env.NewLine + stackTrace; + } + + if (testResult.Test.IsSuite) + { + resultState = resultState.WithSite(FailureSite.TearDown); + } + + if (ex is ResultStateException) + { + exceptionMessage = ex.Message; + resultState = ((ResultStateException)ex).ResultState; + stackTrace = StackFilter.Filter(ex.StackTrace); + } + + string message = (string.IsNullOrEmpty(prefix) ? "" : (prefix + " : ")) + exceptionMessage; + if (testResult.Message != null) + { + message = testResult.Message + NUnit.Env.NewLine + message; + } + + testResult.SetResult(resultState, message, stackTrace); + } + + public static void RecordPrefixedError(this TestResult testResult, string prefix, string error, ResultState resultState = null) + + { + if (resultState == null) + { + resultState = testResult.ResultState == ResultState.Cancelled + ? ResultState.Cancelled + : ResultState.Error; + } + + if (testResult.Test.IsSuite) + { + resultState = resultState.WithSite(FailureSite.TearDown); + } + + string message = (string.IsNullOrEmpty(prefix) ? "" : (prefix + " : ")) + error; + if (testResult.Message != null) + { + message = testResult.Message + NUnit.Env.NewLine + message; + } + + testResult.SetResult(resultState, message); + } + } +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/UnityTestAssemblyBuilder.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/UnityTestAssemblyBuilder.cs new file mode 100644 index 00000000..f16a9f38 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/NUnitExtensions/UnityTestAssemblyBuilder.cs @@ -0,0 +1,52 @@ +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using NUnit; +using NUnit.Framework.Api; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; + +namespace UnityEngine.TestTools.NUnitExtensions +{ + internal class UnityTestAssemblyBuilder : DefaultTestAssemblyBuilder + { + private readonly string m_ProductName; + public UnityTestAssemblyBuilder() + { + m_ProductName = Application.productName; + } + + public ITest Build(Assembly[] assemblies, IDictionary options) + { + var test = BuildAsync(assemblies, options); + while (test.MoveNext()) + { + } + + return test.Current; + } + + public IEnumerator BuildAsync(Assembly[] assemblies, IDictionary options) + { + var productName = string.Join("_", m_ProductName.Split(Path.GetInvalidFileNameChars())); + var suite = new TestSuite(productName); + foreach (var assembly in assemblies) + { + var assemblySuite = Build(assembly, options) as TestSuite; + if (assemblySuite != null && assemblySuite.HasChildren) + { + suite.Add(assemblySuite); + } + yield return null; + } + yield return suite; + } + + public static Dictionary GetNUnitTestBuilderSettings(TestPlatform testPlatform) + { + var emptySettings = new Dictionary(); + emptySettings.Add(FrameworkPackageSettings.TestParameters, "platform=" + testPlatform); + return emptySettings; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/Callbacks/PlayModeRunnerCallback.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/Callbacks/PlayModeRunnerCallback.cs new file mode 100644 index 00000000..d7926873 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/Callbacks/PlayModeRunnerCallback.cs @@ -0,0 +1,47 @@ +using NUnit.Framework; +using NUnit.Framework.Interfaces; + +namespace UnityEngine.TestTools.TestRunner.Callbacks +{ + [AddComponentMenu("")] + internal class PlayModeRunnerCallback : MonoBehaviour, ITestRunnerListener + { + private TestResultRenderer m_ResultRenderer; + + public void RunFinished(ITestResult testResults) + { + Application.logMessageReceivedThreaded -= LogRecieved; + if (Camera.main == null) + { + gameObject.AddComponent(); + } + m_ResultRenderer = new TestResultRenderer(testResults); + m_ResultRenderer.ShowResults(); + } + + public void TestFinished(ITestResult result) + { + } + + public void OnGUI() + { + if (m_ResultRenderer != null) + m_ResultRenderer.Draw(); + } + + public void RunStarted(ITest testsToRun) + { + Application.logMessageReceivedThreaded += LogRecieved; + } + + public void TestStarted(ITest test) + { + } + + private void LogRecieved(string message, string stacktrace, LogType type) + { + if (TestContext.Out != null) + TestContext.Out.WriteLine(message); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/Callbacks/RemoteTestResultSender.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/Callbacks/RemoteTestResultSender.cs new file mode 100644 index 00000000..20928504 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/Callbacks/RemoteTestResultSender.cs @@ -0,0 +1,130 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using NUnit.Framework.Interfaces; +using UnityEngine.Networking.PlayerConnection; +using UnityEngine.TestRunner.TestLaunchers; + +namespace UnityEngine.TestTools.TestRunner.Callbacks +{ + [AddComponentMenu("")] + internal class RemoteTestResultSender : MonoBehaviour, ITestRunnerListener + { + private class QueueData + { + public Guid id { get; set; } + public byte[] data { get; set; } + } + + private readonly Queue m_SendQueue = new Queue(); + private readonly object m_LockQueue = new object(); + private readonly IRemoteTestResultDataFactory m_TestResultDataFactory = new RemoteTestResultDataFactory(); + + public void Start() + { + PlayerConnection.instance.Register(PlayerConnectionMessageIds.runFinishedMessageId, EditorProccessedTheResult); + StartCoroutine(SendDataRoutine()); + } + + private void EditorProccessedTheResult(MessageEventArgs arg0) + { + if (arg0.data != null) + { + return; + } + + //Some platforms don't quit, so we need to disconnect to make sure they will not connect to another editor instance automatically. + PlayerConnection.instance.DisconnectAll(); + + //XBOX has an error when quitting + if (Application.platform == RuntimePlatform.XboxOne) + { + return; + } + Application.Quit(); + } + + private byte[] SerializeObject(object objectToSerialize) + { + return Encoding.UTF8.GetBytes(JsonUtility.ToJson(objectToSerialize)); + } + + public void RunStarted(ITest testsToRun) + { + var data = SerializeObject(m_TestResultDataFactory.CreateFromTest(testsToRun)); + lock (m_LockQueue) + { + m_SendQueue.Enqueue(new QueueData + { + id = PlayerConnectionMessageIds.runStartedMessageId, + data = data + }); + } + } + + public void RunFinished(ITestResult testResults) + { + var data = SerializeObject(m_TestResultDataFactory.CreateFromTestResult(testResults)); + lock (m_LockQueue) + { + m_SendQueue.Enqueue(new QueueData { id = PlayerConnectionMessageIds.runFinishedMessageId, data = data, }); + } + } + + public void TestStarted(ITest test) + { + var data = SerializeObject(m_TestResultDataFactory.CreateFromTest(test)); + lock (m_LockQueue) + { + m_SendQueue.Enqueue(new QueueData + { + id = PlayerConnectionMessageIds.testStartedMessageId, + data = data + }); + } + } + + public void TestFinished(ITestResult result) + { + var testRunnerResultForApi = m_TestResultDataFactory.CreateFromTestResult(result); + var resultData = SerializeObject(testRunnerResultForApi); + lock (m_LockQueue) + { + m_SendQueue.Enqueue(new QueueData + { + id = PlayerConnectionMessageIds.testFinishedMessageId, + data = resultData, + }); + } + } + + public IEnumerator SendDataRoutine() + { + while (!PlayerConnection.instance.isConnected) + { + yield return new WaitForSeconds(1); + } + + while (true) + { + lock (m_LockQueue) + { + if (PlayerConnection.instance.isConnected && m_SendQueue.Count > 0) + { + var queueData = m_SendQueue.Dequeue(); + PlayerConnection.instance.Send(queueData.id, queueData.data); + yield return null; + } + + //This is needed so we dont stall the player totally + if (!m_SendQueue.Any()) + { + yield return new WaitForSeconds(0.02f); + } + } + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/Callbacks/TestResultRenderer.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/Callbacks/TestResultRenderer.cs new file mode 100644 index 00000000..280c6c43 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/Callbacks/TestResultRenderer.cs @@ -0,0 +1,97 @@ +using System.Collections.Generic; +using System.Linq; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; + +namespace UnityEngine.TestTools.TestRunner.Callbacks +{ + internal class TestResultRenderer + { + private static class Styles + { + public static readonly GUIStyle SucceedLabelStyle; + public static readonly GUIStyle FailedLabelStyle; + public static readonly GUIStyle FailedMessagesStyle; + + static Styles() + { + SucceedLabelStyle = new GUIStyle("label"); + SucceedLabelStyle.normal.textColor = Color.green; + SucceedLabelStyle.fontSize = 48; + + FailedLabelStyle = new GUIStyle("label"); + FailedLabelStyle.normal.textColor = Color.red; + FailedLabelStyle.fontSize = 32; + + FailedMessagesStyle = new GUIStyle("label"); + FailedMessagesStyle.wordWrap = false; + FailedMessagesStyle.richText = true; + } + } + + private readonly List m_FailedTestCollection; + + private bool m_ShowResults; + private Vector2 m_ScrollPosition; + + public TestResultRenderer(ITestResult testResults) + { + m_FailedTestCollection = new List(); + GetFailedTests(testResults); + } + + private void GetFailedTests(ITestResult testResults) + { + if (testResults is TestCaseResult) + { + if (testResults.ResultState.Status == TestStatus.Failed) + m_FailedTestCollection.Add(testResults); + } + else if (testResults.HasChildren) + { + foreach (var testResultsChild in testResults.Children) + { + GetFailedTests(testResultsChild); + } + } + } + + private const int k_MaxStringLength = 15000; + + public void ShowResults() + { + m_ShowResults = true; + Cursor.visible = true; + } + + public void Draw() + { + if (!m_ShowResults) return; + if (m_FailedTestCollection.Count == 0) + { + GUILayout.Label("All test succeeded", Styles.SucceedLabelStyle, GUILayout.Width(600)); + } + else + { + int count = m_FailedTestCollection.Count; + GUILayout.Label(count + " tests failed!", Styles.FailedLabelStyle); + + m_ScrollPosition = GUILayout.BeginScrollView(m_ScrollPosition, GUILayout.ExpandWidth(true)); + var text = ""; + + text += "Code-based tests\n"; + text += string.Join("\n", m_FailedTestCollection + .Select(result => result.Name + " " + result.ResultState + "\n" + result.Message) + .ToArray()); + + if (text.Length > k_MaxStringLength) + text = text.Substring(0, k_MaxStringLength); + + GUILayout.TextArea(text, Styles.FailedMessagesStyle); + GUILayout.EndScrollView(); + } + if (GUILayout.Button("Close")) + Application.Quit(); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/Callbacks/TestResultRendererCallback.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/Callbacks/TestResultRendererCallback.cs new file mode 100644 index 00000000..b5d23f7f --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/Callbacks/TestResultRendererCallback.cs @@ -0,0 +1,36 @@ +using NUnit.Framework.Interfaces; + +namespace UnityEngine.TestTools.TestRunner.Callbacks +{ + internal class TestResultRendererCallback : MonoBehaviour, ITestRunnerListener + { + private TestResultRenderer m_ResultRenderer; + public void RunStarted(ITest testsToRun) + { + } + + public void RunFinished(ITestResult testResults) + { + if (Camera.main == null) + { + gameObject.AddComponent(); + } + m_ResultRenderer = new TestResultRenderer(testResults); + m_ResultRenderer.ShowResults(); + } + + public void OnGUI() + { + if (m_ResultRenderer != null) + m_ResultRenderer.Draw(); + } + + public void TestStarted(ITest test) + { + } + + public void TestFinished(ITestResult result) + { + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/ITestRunnerListener.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/ITestRunnerListener.cs new file mode 100644 index 00000000..6a2fa5b2 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/ITestRunnerListener.cs @@ -0,0 +1,26 @@ +using System; +using NUnit.Framework.Interfaces; +using UnityEngine.Events; + +namespace UnityEngine.TestTools.TestRunner +{ + internal interface ITestRunnerListener + { + void RunStarted(ITest testsToRun); + void RunFinished(ITestResult testResults); + void TestStarted(ITest test); + void TestFinished(ITestResult result); + } + + [Serializable] + internal class TestFinishedEvent : UnityEvent {} + + [Serializable] + internal class TestStartedEvent : UnityEvent {} + + [Serializable] + internal class RunFinishedEvent : UnityEvent {} + + [Serializable] + internal class RunStartedEvent : UnityEvent {} +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/Messages/IEditModeTestYieldInstruction.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/Messages/IEditModeTestYieldInstruction.cs new file mode 100644 index 00000000..df7acb23 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/Messages/IEditModeTestYieldInstruction.cs @@ -0,0 +1,12 @@ +using System.Collections; + +namespace UnityEngine.TestTools +{ + public interface IEditModeTestYieldInstruction + { + bool ExpectDomainReload { get; } + bool ExpectedPlaymodeState { get; } + + IEnumerator Perform(); + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/PlaymodeTestsController.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/PlaymodeTestsController.cs new file mode 100644 index 00000000..3efa3d3f --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/PlaymodeTestsController.cs @@ -0,0 +1,129 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using UnityEngine.SceneManagement; +using UnityEngine.TestRunner.NUnitExtensions; +using UnityEngine.TestRunner.NUnitExtensions.Runner; +using UnityEngine.TestTools.NUnitExtensions; +using UnityEngine.TestTools.Utils; + +namespace UnityEngine.TestTools.TestRunner +{ + [Serializable] + [AddComponentMenu("")] + internal class PlaymodeTestsController : MonoBehaviour + { + private IEnumerator m_TestSteps; + + [SerializeField] + private List m_AssembliesWithTests; + public List AssembliesWithTests + { + get + { + return m_AssembliesWithTests; + } + set + { + m_AssembliesWithTests = value; + } + } + + [SerializeField] + internal TestStartedEvent testStartedEvent = new TestStartedEvent(); + [SerializeField] + internal TestFinishedEvent testFinishedEvent = new TestFinishedEvent(); + [SerializeField] + internal RunStartedEvent runStartedEvent = new RunStartedEvent(); + [SerializeField] + internal RunFinishedEvent runFinishedEvent = new RunFinishedEvent(); + + internal const string kPlaymodeTestControllerName = "Code-based tests runner"; + + [SerializeField] + public PlaymodeTestsControllerSettings settings = new PlaymodeTestsControllerSettings(); + + internal UnityTestAssemblyRunner m_Runner; + + public IEnumerator Start() + { + //Skip 2 frame because Unity. + yield return null; + yield return null; + StartCoroutine(Run()); + } + + internal static bool IsControllerOnScene() + { + return GameObject.Find(kPlaymodeTestControllerName) != null; + } + + internal static PlaymodeTestsController GetController() + { + return GameObject.Find(kPlaymodeTestControllerName).GetComponent(); + } + + public IEnumerator TestRunnerCorotine() + { + while (m_TestSteps.MoveNext()) + { + yield return m_TestSteps.Current; + } + + if (m_Runner.IsTestComplete) + { + runFinishedEvent.Invoke(m_Runner.Result); + Cleanup(); + + yield return null; + } + } + + public IEnumerator Run() + { + CoroutineTestWorkItem.monoBehaviourCoroutineRunner = this; + gameObject.hideFlags |= HideFlags.DontSave; + + if (settings.sceneBased) + { + SceneManager.LoadScene(1, LoadSceneMode.Additive); + yield return null; + } + + var testListUtil = new PlayerTestAssemblyProvider(new AssemblyLoadProxy(), m_AssembliesWithTests); + m_Runner = new UnityTestAssemblyRunner(new UnityTestAssemblyBuilder(), new PlaymodeWorkItemFactory()); + + var loadedTests = m_Runner.Load(testListUtil.GetUserAssemblies().Select(a => a.Assembly).ToArray(), UnityTestAssemblyBuilder.GetNUnitTestBuilderSettings(TestPlatform.PlayMode)); + loadedTests.ParseForNameDuplicates(); + runStartedEvent.Invoke(m_Runner.LoadedTest); + + var testListenerWrapper = new TestListenerWrapper(testStartedEvent, testFinishedEvent); + m_TestSteps = m_Runner.Run(testListenerWrapper, settings.filter.BuildNUnitFilter()).GetEnumerator(); + + yield return TestRunnerCorotine(); + } + + public void Cleanup() + { + if (m_Runner != null) + { + m_Runner.StopRun(); + m_Runner = null; + } + if (Application.isEditor) + { + Destroy(gameObject); + } + } + + public static void TryCleanup() + { + var controller = GetController(); + if (controller != null) + { + controller.Cleanup(); + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/PlaymodeTestsControllerSettings.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/PlaymodeTestsControllerSettings.cs new file mode 100644 index 00000000..f52b3b87 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/PlaymodeTestsControllerSettings.cs @@ -0,0 +1,28 @@ +using System; +using UnityEngine.SceneManagement; +using UnityEngine.TestTools.TestRunner.GUI; + +namespace UnityEngine.TestTools.TestRunner +{ + [Serializable] + internal class PlaymodeTestsControllerSettings + { + [SerializeField] + public TestRunnerFilter filter; + public bool sceneBased; + public string originalScene; + public string bootstrapScene; + + public static PlaymodeTestsControllerSettings CreateRunnerSettings(TestRunnerFilter filter) + { + var settings = new PlaymodeTestsControllerSettings + { + filter = filter, + sceneBased = false, + originalScene = SceneManager.GetActiveScene().path, + bootstrapScene = null + }; + return settings; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/RemoteHelpers/IRemoteTestResultDataFactory.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/RemoteHelpers/IRemoteTestResultDataFactory.cs new file mode 100644 index 00000000..fffba298 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/RemoteHelpers/IRemoteTestResultDataFactory.cs @@ -0,0 +1,11 @@ +using System; +using NUnit.Framework.Interfaces; + +namespace UnityEngine.TestRunner.TestLaunchers +{ + internal interface IRemoteTestResultDataFactory + { + RemoteTestResultDataWithTestData CreateFromTestResult(ITestResult result); + RemoteTestResultDataWithTestData CreateFromTest(ITest test); + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/RemoteHelpers/PlayerConnectionMessageIds.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/RemoteHelpers/PlayerConnectionMessageIds.cs new file mode 100644 index 00000000..3dbfdb4a --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/RemoteHelpers/PlayerConnectionMessageIds.cs @@ -0,0 +1,12 @@ +using System; + +namespace UnityEngine.TestRunner.TestLaunchers +{ + internal static class PlayerConnectionMessageIds + { + public static Guid runStartedMessageId { get { return new Guid("6a7f53dd-4672-461d-a7b5-9467e9393fd3"); } } + public static Guid runFinishedMessageId { get { return new Guid("ffb622fc-34ad-4901-8d7b-47fb04b0bdd4"); } } + public static Guid testStartedMessageId { get { return new Guid("b54d241e-d88d-4dba-8c8f-ee415d11c030"); } } + public static Guid testFinishedMessageId { get { return new Guid("72f7b7f4-6829-4cd1-afde-78872b9d5adc"); } } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/RemoteHelpers/RemoteTestData.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/RemoteHelpers/RemoteTestData.cs new file mode 100644 index 00000000..b2cf24ed --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/RemoteHelpers/RemoteTestData.cs @@ -0,0 +1,54 @@ +using System; +using System.Linq; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; +using UnityEngine.TestRunner.NUnitExtensions; + +namespace UnityEngine.TestRunner.TestLaunchers +{ + [Serializable] + internal class RemoteTestData + { + public string id; + public string name; + public string fullName; + public int testCaseCount; + public int ChildIndex; + public bool hasChildren; + public bool isSuite; + public string[] childrenIds; + public int testCaseTimeout; + public string[] Categories; + public bool IsTestAssembly; + public RunState RunState; + public string Description; + public string SkipReason; + public string ParentId; + public string UniqueName; + public string ParentUniqueName; + + internal RemoteTestData(ITest test) + { + id = test.Id; + name = test.Name; + fullName = test.FullName; + testCaseCount = test.TestCaseCount; + ChildIndex = -1; + if (test.Properties["childIndex"].Count > 0) + { + ChildIndex = (int)test.Properties["childIndex"][0]; + } + hasChildren = test.HasChildren; + isSuite = test.IsSuite; + childrenIds = test.Tests.Select(t => t.Id).ToArray(); + Categories = test.GetAllCategoriesFromTest().ToArray(); + IsTestAssembly = test is TestAssembly; + RunState = (RunState)Enum.Parse(typeof(RunState), test.RunState.ToString()); + Description = (string)test.Properties.Get(PropertyNames.Description); + SkipReason = test.GetSkipReason(); + ParentId = test.GetParentId(); + UniqueName = test.GetUniqueName(); + ParentUniqueName = test.GetParentUniqueName(); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/RemoteHelpers/RemoteTestResultData.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/RemoteHelpers/RemoteTestResultData.cs new file mode 100644 index 00000000..90f82a42 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/RemoteHelpers/RemoteTestResultData.cs @@ -0,0 +1,54 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using NUnit.Framework.Interfaces; + +namespace UnityEngine.TestRunner.TestLaunchers +{ + [Serializable] + internal class RemoteTestResultData + { + public string testId; + public string name; + public string fullName; + public string resultState; + public TestStatus testStatus; + public double duration; + public DateTime startTime; + public DateTime endTime; + public string message; + public string stackTrace; + public int assertCount; + public int failCount; + public int passCount; + public int skipCount; + public int inconclusiveCount; + public bool hasChildren; + public string output; + public string xml; + public string[] childrenIds; + + internal RemoteTestResultData(ITestResult result) + { + testId = result.Test.Id; + name = result.Name; + fullName = result.FullName; + resultState = result.ResultState.ToString(); + testStatus = result.ResultState.Status; + duration = result.Duration; + startTime = result.StartTime; + endTime = result.EndTime; + message = result.Message; + stackTrace = result.StackTrace; + assertCount = result.AssertCount; + failCount = result.FailCount; + passCount = result.PassCount; + skipCount = result.SkipCount; + inconclusiveCount = result.InconclusiveCount; + hasChildren = result.HasChildren; + output = result.Output; + xml = result.ToXml(true).OuterXml; + childrenIds = result.Children.Select(child => child.Test.Id).ToArray(); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/RemoteHelpers/RemoteTestResultDataFactory.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/RemoteHelpers/RemoteTestResultDataFactory.cs new file mode 100644 index 00000000..0b3cd035 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/RemoteHelpers/RemoteTestResultDataFactory.cs @@ -0,0 +1,51 @@ +using System.Collections.Generic; +using System.Linq; +using NUnit.Framework.Interfaces; +using UnityEngine.TestRunner.NUnitExtensions.Runner; + +namespace UnityEngine.TestRunner.TestLaunchers +{ + internal class RemoteTestResultDataFactory : IRemoteTestResultDataFactory + { + public RemoteTestResultDataWithTestData CreateFromTestResult(ITestResult result) + { + var tests = CreateTestDataList(result.Test); + tests.First().testCaseTimeout = UnityTestExecutionContext.CurrentContext.TestCaseTimeout; + return new RemoteTestResultDataWithTestData() + { + results = CreateTestResultDataList(result), + tests = tests + }; + } + + public RemoteTestResultDataWithTestData CreateFromTest(ITest test) + { + var tests = CreateTestDataList(test); + if (UnityTestExecutionContext.CurrentContext != null) + { + tests.First().testCaseTimeout = UnityTestExecutionContext.CurrentContext.TestCaseTimeout; + } + + return new RemoteTestResultDataWithTestData() + { + tests = tests + }; + } + + private RemoteTestData[] CreateTestDataList(ITest test) + { + var list = new List(); + list.Add(new RemoteTestData(test)); + list.AddRange(test.Tests.SelectMany(CreateTestDataList)); + return list.ToArray(); + } + + private static RemoteTestResultData[] CreateTestResultDataList(ITestResult result) + { + var list = new List(); + list.Add(new RemoteTestResultData(result)); + list.AddRange(result.Children.SelectMany(CreateTestResultDataList)); + return list.ToArray(); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/RemoteHelpers/RemoteTestResultDataWithTestData.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/RemoteHelpers/RemoteTestResultDataWithTestData.cs new file mode 100644 index 00000000..36124cc7 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/RemoteHelpers/RemoteTestResultDataWithTestData.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using NUnit.Framework.Interfaces; +using UnityEngine.TestRunner.NUnitExtensions.Runner; + +namespace UnityEngine.TestRunner.TestLaunchers +{ + [Serializable] + internal class RemoteTestResultDataWithTestData + { + public RemoteTestResultData[] results; + public RemoteTestData[] tests; + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/TestEnumeratorWrapper.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/TestEnumeratorWrapper.cs new file mode 100644 index 00000000..5ed2ec84 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/TestEnumeratorWrapper.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections; +using System.Reflection; +using NUnit.Framework; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; + +namespace UnityEngine.TestTools.TestRunner +{ + internal class TestEnumeratorWrapper + { + private readonly TestMethod m_TestMethod; + + public TestEnumeratorWrapper(TestMethod testMethod) + { + m_TestMethod = testMethod; + } + + public IEnumerator GetEnumerator(ITestExecutionContext context) + { + if (m_TestMethod.Method.ReturnType.Type == typeof(IEnumerator)) + { + return HandleEnumerableTest(context); + } + var message = string.Format("Return type {0} of {1} in {2} is not supported.", + m_TestMethod.Method.ReturnType, m_TestMethod.Method.Name, m_TestMethod.Method.TypeInfo.FullName); + if (m_TestMethod.Method.ReturnType.Type == typeof(IEnumerable)) + { + message += "\nDid you mean IEnumerator?"; + } + throw new InvalidSignatureException(message); + } + + private IEnumerator HandleEnumerableTest(ITestExecutionContext context) + { + try + { + return m_TestMethod.Method.MethodInfo.Invoke(context.TestObject, m_TestMethod.parms != null ? m_TestMethod.parms.OriginalArguments : null) as IEnumerator; + } + catch (TargetInvocationException e) + { + if (e.InnerException is IgnoreException) + { + context.CurrentResult.SetResult(ResultState.Ignored, e.InnerException.Message); + return null; + } + throw; + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/TestListenerWrapper.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/TestListenerWrapper.cs new file mode 100644 index 00000000..ffa23de5 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/TestListenerWrapper.cs @@ -0,0 +1,30 @@ +using NUnit.Framework.Interfaces; + +namespace UnityEngine.TestTools.TestRunner +{ + internal class TestListenerWrapper : ITestListener + { + private readonly TestFinishedEvent m_TestFinishedEvent; + private readonly TestStartedEvent m_TestStartedEvent; + + public TestListenerWrapper(TestStartedEvent testStartedEvent, TestFinishedEvent testFinishedEvent) + { + m_TestStartedEvent = testStartedEvent; + m_TestFinishedEvent = testFinishedEvent; + } + + public void TestStarted(ITest test) + { + m_TestStartedEvent.Invoke(test); + } + + public void TestFinished(ITestResult result) + { + m_TestFinishedEvent.Invoke(result); + } + + public void TestOutput(TestOutput output) + { + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/TestPlatform.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/TestPlatform.cs new file mode 100644 index 00000000..21a6ec2b --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/TestPlatform.cs @@ -0,0 +1,21 @@ +using System; + +namespace UnityEngine.TestTools +{ + [Flags] + [Serializable] + public enum TestPlatform : byte + { + All = 0xFF, + EditMode = 1 << 1, + PlayMode = 1 << 2 + } + + internal static class TestPlatformEnumExtensions + { + public static bool IsFlagIncluded(this TestPlatform flags, TestPlatform flag) + { + return (flags & flag) == flag; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/TestRunnerFilter.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/TestRunnerFilter.cs new file mode 100644 index 00000000..b0bd4614 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/TestRunner/TestRunnerFilter.cs @@ -0,0 +1,197 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.RegularExpressions; +using System.IO; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; +using NUnit.Framework.Internal.Filters; +using UnityEngine.TestRunner.NUnitExtensions.Filters; + +namespace UnityEngine.TestTools.TestRunner.GUI +{ + [Serializable] + internal class TestRunnerFilter + { +#pragma warning disable 649 + public string[] assemblyNames; + public string[] groupNames; + public string[] categoryNames; + public static TestRunnerFilter empty = new TestRunnerFilter(); + public string[] testNames; + public int testRepetitions = 1; + + public static string AssemblyNameFromPath(string path) + { + string output = Path.GetFileName(path); + if (output != null && output.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) + return output.Substring(0, output.Length - 4); + return output; + } + + private bool CategoryMatches(IEnumerable categories) + { + if (categoryNames == null || categoryNames.Length == 0) + return true; + + foreach (string category in categories) + { + if (categoryNames.Contains(category)) + return true; + } + + return false; + } + + private bool IDMatchesAssembly(string id) + { + if (AreOptionalFiltersEmpty()) + return true; + + if (assemblyNames == null) + return false; + + int openingBracket = id.IndexOf('['); + int closingBracket = id.IndexOf(']'); + if (openingBracket >= 0 && openingBracket < id.Length && closingBracket > openingBracket && openingBracket < id.Length) + { + //Some assemblies are absolute and explicitly part of the test ID e.g. + //"[/path/to/assembly-name.dll][rest of ID ...]" + //While some are minimal assembly names e.g. + //"[assembly-name][rest of ID ...]" + //Strip them down to just the assembly name + string assemblyNameFromID = AssemblyNameFromPath(id.Substring(openingBracket + 1, closingBracket - openingBracket - 1)); + foreach (string assemblyName in assemblyNames) + { + if (assemblyName.Equals(assemblyNameFromID, StringComparison.OrdinalIgnoreCase)) + return true; + } + } + return false; + } + + private bool NameMatches(string name) + { + if (AreOptionalFiltersEmpty()) + return true; + + if (groupNames == null) + return false; + + foreach (var nameFromFilter in groupNames) + { + //Strict regex match for test group name on its own + if (Regex.IsMatch(name, nameFromFilter)) + return true; + //Match test names that end with parametrized test values and full nunit generated test names that have . separators + var regex = nameFromFilter.TrimEnd('$') + @"[\.|\(.*\)]"; + if (Regex.IsMatch(name, regex)) + return true; + } + return false; + } + + private bool AreOptionalFiltersEmpty() + { + if (assemblyNames != null && assemblyNames.Length != 0) + return false; + if (groupNames != null && groupNames.Length != 0) + return false; + if (testNames != null && testNames.Length != 0) + return false; + return true; + } + + private bool NameMatchesExactly(string name) + { + if (AreOptionalFiltersEmpty()) + return true; + + if (testNames == null) + return false; + + foreach (var exactName in testNames) + { + if (name == exactName) + return true; + } + return false; + } + + private static void ClearAncestors(IEnumerable newResultList, string parentID) + { + if (string.IsNullOrEmpty(parentID)) + return; + foreach (var result in newResultList) + { + if (result.Id == parentID) + { + result.Clear(); + ClearAncestors(newResultList, result.ParentId); + break; + } + } + } + + public void ClearResults(List newResultList) + { + foreach (var result in newResultList) + { + if (!result.IsSuite && CategoryMatches(result.Categories)) + { + if (IDMatchesAssembly(result.Id) || NameMatches(result.FullName) || NameMatchesExactly(result.FullName)) + { + result.Clear(); + ClearAncestors(newResultList, result.ParentId); + } + } + } + } + + public ITestFilter BuildNUnitFilter() + { + var filters = new List(); + + if (testNames != null && testNames.Length != 0) + { + var nameFilter = new OrFilter(testNames.Select(n => new FullNameFilter(n)).ToArray()); + filters.Add(nameFilter); + } + + if (groupNames != null && groupNames.Length != 0) + { + var exactNamesFilter = new OrFilter(groupNames.Select(n => + { + var f = new FullNameFilter(n); + f.IsRegex = true; + return f; + }).ToArray()); + filters.Add(exactNamesFilter); + } + + if (assemblyNames != null && assemblyNames.Length != 0) + { + var assemblyFilter = new OrFilter(assemblyNames.Select(c => new AssemblyNameFilter(c)).ToArray()); + filters.Add(assemblyFilter); + } + + if (categoryNames != null && categoryNames.Length != 0) + { + var categoryFilter = new OrFilter(categoryNames.Select(c => new CategoryFilterExtended(c) {IsRegex = true}).ToArray()); + filters.Add(categoryFilter); + } + + return filters.Count == 0 ? TestFilter.Empty : new AndFilter(filters.ToArray()); + } + + internal interface IClearableResult + { + string Id { get; } + string FullName { get; } + string ParentId { get; } + bool IsSuite { get; } + List Categories { get; } + void Clear(); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/UnityEngine.TestRunner.asmdef b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/UnityEngine.TestRunner.asmdef new file mode 100644 index 00000000..6dc17daa --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/UnityEngine.TestRunner.asmdef @@ -0,0 +1,13 @@ +{ + "name": "UnityEngine.TestRunner", + "references": [], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": true, + "precompiledReferences": [ + "nunit.framework.dll" + ], + "autoReferenced": false, + "defineConstraints": [] +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/AssemblyProvider/AssemblyLoadProxy.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/AssemblyProvider/AssemblyLoadProxy.cs new file mode 100644 index 00000000..9edc5171 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/AssemblyProvider/AssemblyLoadProxy.cs @@ -0,0 +1,12 @@ +using System.Reflection; + +namespace UnityEngine.TestTools.Utils +{ + internal class AssemblyLoadProxy : IAssemblyLoadProxy + { + public IAssemblyWrapper Load(string assemblyString) + { + return new AssemblyWrapper(Assembly.Load(assemblyString)); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/AssemblyProvider/AssemblyWrapper.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/AssemblyProvider/AssemblyWrapper.cs new file mode 100644 index 00000000..cb46f1b6 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/AssemblyProvider/AssemblyWrapper.cs @@ -0,0 +1,30 @@ +using System; +using System.Reflection; + +namespace UnityEngine.TestTools.Utils +{ + internal class AssemblyWrapper : IAssemblyWrapper + { + public AssemblyWrapper(Assembly assembly) + { + Assembly = assembly; + } + + public Assembly Assembly { get; } + + public virtual string Location + { + get + { + //Some platforms dont support this + throw new NotImplementedException(); + } + } + + public virtual AssemblyName[] GetReferencedAssemblies() + { + //Some platforms dont support this + throw new NotImplementedException(); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/AssemblyProvider/IAssemblyLoadProxy.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/AssemblyProvider/IAssemblyLoadProxy.cs new file mode 100644 index 00000000..feffa62e --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/AssemblyProvider/IAssemblyLoadProxy.cs @@ -0,0 +1,7 @@ +namespace UnityEngine.TestTools.Utils +{ + internal interface IAssemblyLoadProxy + { + IAssemblyWrapper Load(string assemblyString); + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/AssemblyProvider/IAssemblyWrapper.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/AssemblyProvider/IAssemblyWrapper.cs new file mode 100644 index 00000000..145c682d --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/AssemblyProvider/IAssemblyWrapper.cs @@ -0,0 +1,11 @@ +using System.Reflection; + +namespace UnityEngine.TestTools.Utils +{ + internal interface IAssemblyWrapper + { + Assembly Assembly { get; } + string Location { get; } + AssemblyName[] GetReferencedAssemblies(); + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/AssemblyProvider/IScriptingRuntimeProxy.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/AssemblyProvider/IScriptingRuntimeProxy.cs new file mode 100644 index 00000000..0dc2b7f3 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/AssemblyProvider/IScriptingRuntimeProxy.cs @@ -0,0 +1,7 @@ +namespace UnityEngine.TestTools.Utils +{ + internal interface IScriptingRuntimeProxy + { + string[] GetAllUserAssemblies(); + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/AssemblyProvider/ITestAssemblyProvider.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/AssemblyProvider/ITestAssemblyProvider.cs new file mode 100644 index 00000000..74f27692 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/AssemblyProvider/ITestAssemblyProvider.cs @@ -0,0 +1,10 @@ +using NUnit.Framework.Interfaces; + +namespace UnityEngine.TestTools.Utils +{ + internal interface ITestAssemblyProvider + { + ITest GetTestsWithNUnit(); + IAssemblyWrapper[] GetUserAssemblies(); + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/AssemblyProvider/PlayerTestAssemblyProvider.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/AssemblyProvider/PlayerTestAssemblyProvider.cs new file mode 100644 index 00000000..04cd11b1 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/AssemblyProvider/PlayerTestAssemblyProvider.cs @@ -0,0 +1,66 @@ +using System.Collections.Generic; +using System.IO; +using System.Linq; +using NUnit.Framework.Interfaces; +using UnityEngine.TestTools.NUnitExtensions; + +namespace UnityEngine.TestTools.Utils +{ + internal class PlayerTestAssemblyProvider + { + private IAssemblyLoadProxy m_AssemblyLoadProxy; + private readonly List m_AssembliesToLoad; + + //Cached until domain reload + private static List m_LoadedAssemblies; + + internal PlayerTestAssemblyProvider(IAssemblyLoadProxy assemblyLoadProxy, List assembliesToLoad) + { + m_AssemblyLoadProxy = assemblyLoadProxy; + m_AssembliesToLoad = assembliesToLoad; + LoadAssemblies(); + } + + public ITest GetTestsWithNUnit() + { + return BuildTests(TestPlatform.PlayMode, m_LoadedAssemblies.ToArray()); + } + + public List GetUserAssemblies() + { + return m_LoadedAssemblies; + } + + protected static ITest BuildTests(TestPlatform testPlatform, IAssemblyWrapper[] assemblies) + { + var settings = UnityTestAssemblyBuilder.GetNUnitTestBuilderSettings(testPlatform); + var builder = new UnityTestAssemblyBuilder(); + return builder.Build(assemblies.Select(a => a.Assembly).ToArray(), settings); + } + + private void LoadAssemblies() + { + if (m_LoadedAssemblies != null) + { + return; + } + + m_LoadedAssemblies = new List(); + + foreach (var userAssembly in m_AssembliesToLoad) + { + IAssemblyWrapper a; + try + { + a = m_AssemblyLoadProxy.Load(userAssembly); + } + catch (FileNotFoundException) + { + continue; + } + if (a != null) + m_LoadedAssemblies.Add(a); + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/AssemblyProvider/ScriptingRuntimeProxy.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/AssemblyProvider/ScriptingRuntimeProxy.cs new file mode 100644 index 00000000..0f1eb2bc --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/AssemblyProvider/ScriptingRuntimeProxy.cs @@ -0,0 +1,10 @@ +namespace UnityEngine.TestTools.Utils +{ + internal class ScriptingRuntimeProxy : IScriptingRuntimeProxy + { + public string[] GetAllUserAssemblies() + { + return ScriptingRuntime.GetAllUserAssemblies(); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/AttributeHelper.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/AttributeHelper.cs new file mode 100644 index 00000000..7d710cb8 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/AttributeHelper.cs @@ -0,0 +1,45 @@ +using System; +using System.IO; +using System.Linq; + +namespace UnityEngine.TestTools +{ + internal static class AttributeHelper + { + internal static Type GetTargetClassFromName(string targetClassName, Type attributeInterface) + { + Type targetClass = null; + foreach (var assemblyName in ScriptingRuntime.GetAllUserAssemblies()) + { + // we need to pass the assembly name without the .dll extension, so removing that first + var name = Path.GetFileNameWithoutExtension(assemblyName); + targetClass = Type.GetType(targetClassName + "," + name); + if (targetClass != null) + break; + } + + if (targetClass == null) + { + Debug.LogWarningFormat("Class type not found: " + targetClassName); + return null; + } + + ValidateTargetClass(targetClass, attributeInterface); + return targetClass; + } + + private static void ValidateTargetClass(Type targetClass, Type attributeInterface) + { + var constructorInfos = targetClass.GetConstructors(); + if (constructorInfos.All(constructor => constructor.GetParameters().Length != 0)) + { + Debug.LogWarningFormat("{0} does not implement default constructor", targetClass.Name); + } + + if (!attributeInterface.IsAssignableFrom(targetClass)) + { + Debug.LogWarningFormat("{0} does not implement {1}", targetClass.Name, attributeInterface.Name); + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/ColorEqualityComparer.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/ColorEqualityComparer.cs new file mode 100644 index 00000000..073aa086 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/ColorEqualityComparer.cs @@ -0,0 +1,36 @@ +using System.Collections.Generic; + +namespace UnityEngine.TestTools.Utils +{ + public class ColorEqualityComparer : IEqualityComparer + { + private const float k_DefaultError = 0.01f; + private readonly float AllowedError; + + + private static readonly ColorEqualityComparer m_Instance = new ColorEqualityComparer(); + public static ColorEqualityComparer Instance { get { return m_Instance; } } + + private ColorEqualityComparer() : this(k_DefaultError) + { + } + + public ColorEqualityComparer(float error) + { + this.AllowedError = error; + } + + public bool Equals(Color expected, Color actual) + { + return Utils.AreFloatsEqualAbsoluteError(expected.r, actual.r, AllowedError) && + Utils.AreFloatsEqualAbsoluteError(expected.g, actual.g, AllowedError) && + Utils.AreFloatsEqualAbsoluteError(expected.b, actual.b, AllowedError) && + Utils.AreFloatsEqualAbsoluteError(expected.a, actual.a, AllowedError); + } + + public int GetHashCode(Color color) + { + return 0; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/CoroutineRunner.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/CoroutineRunner.cs new file mode 100644 index 00000000..db4d769e --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/CoroutineRunner.cs @@ -0,0 +1,103 @@ +using System; +using System.Collections; +using NUnit.Framework.Internal; +using UnityEngine.TestRunner.NUnitExtensions.Runner; + +namespace UnityEngine.TestTools.Utils +{ + internal class CoroutineRunner + { + private bool m_Running; + private bool m_TestFailed; + private bool m_Timeout; + private readonly MonoBehaviour m_Controller; + private readonly UnityTestExecutionContext m_Context; + private Coroutine m_TimeOutCoroutine; + private IEnumerator m_TestCoroutine; + + internal const int k_DefaultTimeout = 1000 * 180; + + public CoroutineRunner(MonoBehaviour playmodeTestsController, UnityTestExecutionContext context) + { + m_Controller = playmodeTestsController; + m_Context = context; + } + + public IEnumerator HandleEnumerableTest(IEnumerator testEnumerator) + { + if (m_Context.TestCaseTimeout == 0) + { + m_Context.TestCaseTimeout = k_DefaultTimeout; + } + do + { + if (!m_Running) + { + m_Running = true; + m_TestCoroutine = ExMethod(testEnumerator, m_Context.TestCaseTimeout); + m_Controller.StartCoroutine(m_TestCoroutine); + } + if (m_TestFailed) + { + StopAllRunningCoroutines(); + yield break; + } + + if (m_Context.ExecutionStatus == TestExecutionStatus.StopRequested || m_Context.ExecutionStatus == TestExecutionStatus.AbortRequested) + { + StopAllRunningCoroutines(); + yield break; + } + yield return null; + } + while (m_Running); + } + + private void StopAllRunningCoroutines() + { + if (m_TimeOutCoroutine != null) + { + m_Controller.StopCoroutine(m_TimeOutCoroutine); + } + + if (m_TestCoroutine != null) + { + m_Controller.StopCoroutine(m_TestCoroutine); + } + } + + private IEnumerator ExMethod(IEnumerator e, int timeout) + { + m_TimeOutCoroutine = m_Controller.StartCoroutine(StartTimer(e, timeout, + () => + { + m_TestFailed = true; + m_Timeout = true; + m_Running = false; + })); + + yield return m_Controller.StartCoroutine(e); + m_Controller.StopCoroutine(m_TimeOutCoroutine); + m_Running = false; + } + + private IEnumerator StartTimer(IEnumerator coroutineToBeKilled, int timeout, Action onTimeout) + { + yield return new WaitForSecondsRealtime(timeout / 1000f); + if (coroutineToBeKilled != null) + m_Controller.StopCoroutine(coroutineToBeKilled); + if (onTimeout != null) + onTimeout(); + } + + public bool HasFailedWithTimeout() + { + return m_Timeout; + } + + public int GetDefaultTimeout() + { + return k_DefaultTimeout; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/FloatEqualityComparer.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/FloatEqualityComparer.cs new file mode 100644 index 00000000..58438a7e --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/FloatEqualityComparer.cs @@ -0,0 +1,30 @@ +using System.Collections.Generic; + +namespace UnityEngine.TestTools.Utils +{ + public class FloatEqualityComparer : IEqualityComparer + { + private const float k_DefaultError = 0.0001f; + private readonly float AllowedError; + + private static readonly FloatEqualityComparer m_Instance = new FloatEqualityComparer(); + public static FloatEqualityComparer Instance { get { return m_Instance; } } + + private FloatEqualityComparer() : this(k_DefaultError) {} + + public FloatEqualityComparer(float allowedError) + { + this.AllowedError = allowedError; + } + + public bool Equals(float expected, float actual) + { + return Utils.AreFloatsEqual(expected, actual, AllowedError); + } + + public int GetHashCode(float value) + { + return 0; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/IOuterUnityTestAction.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/IOuterUnityTestAction.cs new file mode 100644 index 00000000..ff0fe77d --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/IOuterUnityTestAction.cs @@ -0,0 +1,19 @@ +using System.Collections; +using NUnit.Framework.Interfaces; + +namespace UnityEngine.TestTools +{ + /// + /// When implemented by an attribute, this interface implemented to provide actions to execute before setup and after teardown of tests. + /// + public interface IOuterUnityTestAction + { + /// Executed before each test is run + /// The test that is going to be run. + IEnumerator BeforeTest(ITest test); + + /// Executed after each test is run + /// The test that has just been run. + IEnumerator AfterTest(ITest test); + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/IPostBuildCleanup.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/IPostBuildCleanup.cs new file mode 100644 index 00000000..489357c3 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/IPostBuildCleanup.cs @@ -0,0 +1,7 @@ +namespace UnityEngine.TestTools +{ + public interface IPostBuildCleanup + { + void Cleanup(); + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/IPrebuildSceneSetup.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/IPrebuildSceneSetup.cs new file mode 100644 index 00000000..3920b0bb --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/IPrebuildSceneSetup.cs @@ -0,0 +1,7 @@ +namespace UnityEngine.TestTools +{ + public interface IPrebuildSetup + { + void Setup(); + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/MonoBehaviourTest/IMonoBehaviourTest.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/MonoBehaviourTest/IMonoBehaviourTest.cs new file mode 100644 index 00000000..334da4c3 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/MonoBehaviourTest/IMonoBehaviourTest.cs @@ -0,0 +1,7 @@ +namespace UnityEngine.TestTools +{ + public interface IMonoBehaviourTest + { + bool IsTestFinished {get; } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/MonoBehaviourTest/MonoBehaviourTest.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/MonoBehaviourTest/MonoBehaviourTest.cs new file mode 100644 index 00000000..e0b6372c --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/MonoBehaviourTest/MonoBehaviourTest.cs @@ -0,0 +1,23 @@ +namespace UnityEngine.TestTools +{ + public class MonoBehaviourTest : CustomYieldInstruction where T : MonoBehaviour, IMonoBehaviourTest + { + public T component { get; } + public GameObject gameObject { get { return component.gameObject; } } + + public MonoBehaviourTest(bool dontDestroyOnLoad = true) + { + var go = new GameObject("MonoBehaviourTest: " + typeof(T).FullName); + component = go.AddComponent(); + if (dontDestroyOnLoad) + { + Object.DontDestroyOnLoad(go); + } + } + + public override bool keepWaiting + { + get { return !component.IsTestFinished; } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/PostBuildCleanupAttribute.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/PostBuildCleanupAttribute.cs new file mode 100644 index 00000000..ba7cea7a --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/PostBuildCleanupAttribute.cs @@ -0,0 +1,20 @@ +using System; + +namespace UnityEngine.TestTools +{ + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] + public class PostBuildCleanupAttribute : Attribute + { + public PostBuildCleanupAttribute(Type targetClass) + { + TargetClass = targetClass; + } + + public PostBuildCleanupAttribute(string targetClassName) + { + TargetClass = AttributeHelper.GetTargetClassFromName(targetClassName, typeof(IPostBuildCleanup)); + } + + internal Type TargetClass { get; private set; } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/PrebuildSceneSetupAttribute.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/PrebuildSceneSetupAttribute.cs new file mode 100644 index 00000000..cb7d8e21 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/PrebuildSceneSetupAttribute.cs @@ -0,0 +1,20 @@ +using System; + +namespace UnityEngine.TestTools +{ + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] + public class PrebuildSetupAttribute : Attribute + { + public PrebuildSetupAttribute(Type targetClass) + { + TargetClass = targetClass; + } + + public PrebuildSetupAttribute(string targetClassName) + { + TargetClass = AttributeHelper.GetTargetClassFromName(targetClassName, typeof(IPrebuildSetup)); + } + + internal Type TargetClass { get; private set; } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/QuaternionEqualityComparer.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/QuaternionEqualityComparer.cs new file mode 100644 index 00000000..220f1aa9 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/QuaternionEqualityComparer.cs @@ -0,0 +1,31 @@ +using System.Collections.Generic; + +namespace UnityEngine.TestTools.Utils +{ + public class QuaternionEqualityComparer : IEqualityComparer + { + private const float k_DefaultError = 0.00001f; + private readonly float AllowedError; + + private static readonly QuaternionEqualityComparer m_Instance = new QuaternionEqualityComparer(); + public static QuaternionEqualityComparer Instance { get { return m_Instance; } } + + + private QuaternionEqualityComparer() : this(k_DefaultError) {} + + public QuaternionEqualityComparer(float allowedError) + { + AllowedError = allowedError; + } + + public bool Equals(Quaternion expected, Quaternion actual) + { + return Mathf.Abs(Quaternion.Dot(expected, actual)) > (1.0f - AllowedError); + } + + public int GetHashCode(Quaternion quaternion) + { + return 0; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/StacktraceFilter.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/StacktraceFilter.cs new file mode 100644 index 00000000..af431f33 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/StacktraceFilter.cs @@ -0,0 +1,43 @@ +using System.Linq; +using System.Text; + +namespace UnityEngine.TestTools.Utils +{ + internal static class StackTraceFilter + { + private static readonly string[] s_FilteredLogMessages = + { + @"UnityEngine.DebugLogHandler:Internal_Log", + @"UnityEngine.DebugLogHandler:Log", + @"UnityEngine.Logger:Log", + @"UnityEngine.Debug" + }; + + private static readonly string[] s_LastMessages = + { + @"System.Reflection.MonoMethod:InternalInvoke(Object, Object[], Exception&)", + @"UnityEditor.TestTools.TestRunner.EditModeRunner:InvokeDelegator" + }; + + public static string Filter(string inputStackTrace) + { + int idx; + foreach (var lastMessage in s_LastMessages) + { + idx = inputStackTrace.IndexOf(lastMessage); + if (idx != -1) + inputStackTrace = inputStackTrace.Substring(0, idx); + } + + var inputStackTraceLines = inputStackTrace.Split('\n'); + var result = new StringBuilder(); + foreach (var line in inputStackTraceLines) + { + if (s_FilteredLogMessages.Any(s => line.StartsWith(s))) + continue; + result.AppendLine(line); + } + return result.ToString(); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/Utils.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/Utils.cs new file mode 100644 index 00000000..bc8b6171 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/Utils.cs @@ -0,0 +1,40 @@ +using System; + +namespace UnityEngine.TestTools.Utils +{ + public static class Utils + { + public static bool AreFloatsEqual(float expected, float actual, float epsilon) + { + // special case for infinity + if (expected == Mathf.Infinity || actual == Mathf.Infinity || expected == Mathf.NegativeInfinity || actual == Mathf.NegativeInfinity) + return expected == actual; + + // we cover both relative and absolute tolerance with this check + // which is better than just relative in case of small (in abs value) args + // please note that "usually" approximation is used [i.e. abs(x)+abs(y)+1] + // but we speak about test code so we dont care that much about performance + // but we do care about checks being more precise + return Math.Abs(actual - expected) <= epsilon * Mathf.Max(Mathf.Max(Mathf.Abs(actual), Mathf.Abs(expected)), 1.0f); + } + + public static bool AreFloatsEqualAbsoluteError(float expected, float actual, float allowedAbsoluteError) + { + return Math.Abs(actual - expected) <= allowedAbsoluteError; + } + + /// + /// Analogous to GameObject.CreatePrimitive, but creates a primitive mesh renderer with fast shader instead of a default builtin shader. + /// Optimized for testing performance. + /// + /// A GameObject with primitive mesh renderer and collider. + public static GameObject CreatePrimitive(PrimitiveType type) + { + var prim = GameObject.CreatePrimitive(type); + var renderer = prim.GetComponent(); + if (renderer) + renderer.sharedMaterial = new Material(Shader.Find("VertexLit")); + return prim; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/Vector2ComparerWithEqualsOperator.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/Vector2ComparerWithEqualsOperator.cs new file mode 100644 index 00000000..081a8bbd --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/Vector2ComparerWithEqualsOperator.cs @@ -0,0 +1,22 @@ +using System.Collections.Generic; + +namespace UnityEngine.TestTools.Utils +{ + public class Vector2ComparerWithEqualsOperator : IEqualityComparer + { + private static readonly Vector2ComparerWithEqualsOperator m_Instance = new Vector2ComparerWithEqualsOperator(); + public static Vector2ComparerWithEqualsOperator Instance { get { return m_Instance; } } + + private Vector2ComparerWithEqualsOperator() {} + + public bool Equals(Vector2 expected, Vector2 actual) + { + return expected == actual; + } + + public int GetHashCode(Vector2 vec2) + { + return 0; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/Vector2EqualityComparer.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/Vector2EqualityComparer.cs new file mode 100644 index 00000000..c0cca3f2 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/Vector2EqualityComparer.cs @@ -0,0 +1,33 @@ +using System.Collections.Generic; + +namespace UnityEngine.TestTools.Utils +{ + public class Vector2EqualityComparer : IEqualityComparer + { + private const float k_DefaultError = 0.0001f; + private readonly float AllowedError; + + private static readonly Vector2EqualityComparer m_Instance = new Vector2EqualityComparer(); + public static Vector2EqualityComparer Instance { get { return m_Instance; } } + + private Vector2EqualityComparer() : this(k_DefaultError) + { + } + + public Vector2EqualityComparer(float error) + { + this.AllowedError = error; + } + + public bool Equals(Vector2 expected, Vector2 actual) + { + return Utils.AreFloatsEqual(expected.x, actual.x, AllowedError) && + Utils.AreFloatsEqual(expected.y, actual.y, AllowedError); + } + + public int GetHashCode(Vector2 vec2) + { + return 0; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/Vector3ComparerWithEqualsOperator.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/Vector3ComparerWithEqualsOperator.cs new file mode 100644 index 00000000..ed665c04 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/Vector3ComparerWithEqualsOperator.cs @@ -0,0 +1,22 @@ +using System.Collections.Generic; + +namespace UnityEngine.TestTools.Utils +{ + public class Vector3ComparerWithEqualsOperator : IEqualityComparer + { + private static readonly Vector3ComparerWithEqualsOperator m_Instance = new Vector3ComparerWithEqualsOperator(); + public static Vector3ComparerWithEqualsOperator Instance { get { return m_Instance; } } + + private Vector3ComparerWithEqualsOperator() {} + + public bool Equals(Vector3 expected, Vector3 actual) + { + return expected == actual; + } + + public int GetHashCode(Vector3 vec3) + { + return 0; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/Vector3EqualityComparer.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/Vector3EqualityComparer.cs new file mode 100644 index 00000000..47fac4be --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/Vector3EqualityComparer.cs @@ -0,0 +1,32 @@ +using System.Collections.Generic; + + +namespace UnityEngine.TestTools.Utils +{ + public class Vector3EqualityComparer : IEqualityComparer + { + private const float k_DefaultError = 0.0001f; + private readonly float AllowedError; + + private static readonly Vector3EqualityComparer m_Instance = new Vector3EqualityComparer(); + public static Vector3EqualityComparer Instance { get { return m_Instance; } } + + private Vector3EqualityComparer() : this(k_DefaultError) {} + public Vector3EqualityComparer(float allowedError) + { + this.AllowedError = allowedError; + } + + public bool Equals(Vector3 expected, Vector3 actual) + { + return Utils.AreFloatsEqual(expected.x, actual.x, AllowedError) && + Utils.AreFloatsEqual(expected.y, actual.y, AllowedError) && + Utils.AreFloatsEqual(expected.z, actual.z, AllowedError); + } + + public int GetHashCode(Vector3 vec3) + { + return 0; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/Vector4ComparerWithEqualsOperator.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/Vector4ComparerWithEqualsOperator.cs new file mode 100644 index 00000000..1f8d1066 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/Vector4ComparerWithEqualsOperator.cs @@ -0,0 +1,22 @@ +using System.Collections.Generic; + +namespace UnityEngine.TestTools.Utils +{ + public class Vector4ComparerWithEqualsOperator : IEqualityComparer + { + private static readonly Vector4ComparerWithEqualsOperator m_Instance = new Vector4ComparerWithEqualsOperator(); + public static Vector4ComparerWithEqualsOperator Instance { get { return m_Instance; } } + + private Vector4ComparerWithEqualsOperator() {} + + public bool Equals(Vector4 expected, Vector4 actual) + { + return expected == actual; + } + + public int GetHashCode(Vector4 vec4) + { + return 0; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/Vector4EqualityComparer.cs b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/Vector4EqualityComparer.cs new file mode 100644 index 00000000..70472421 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/Vector4EqualityComparer.cs @@ -0,0 +1,32 @@ +using System.Collections.Generic; + +namespace UnityEngine.TestTools.Utils +{ + public class Vector4EqualityComparer : IEqualityComparer + { + private const float k_DefaultError = 0.0001f; + private readonly float AllowedError; + + private static readonly Vector4EqualityComparer m_Instance = new Vector4EqualityComparer(); + public static Vector4EqualityComparer Instance { get { return m_Instance; } } + + private Vector4EqualityComparer() : this(k_DefaultError) {} + public Vector4EqualityComparer(float allowedError) + { + this.AllowedError = allowedError; + } + + public bool Equals(Vector4 expected, Vector4 actual) + { + return Utils.AreFloatsEqual(expected.x, actual.x, AllowedError) && + Utils.AreFloatsEqual(expected.y, actual.y, AllowedError) && + Utils.AreFloatsEqual(expected.z, actual.z, AllowedError) && + Utils.AreFloatsEqual(expected.w, actual.w, AllowedError); + } + + public int GetHashCode(Vector4 vec4) + { + return 0; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/package.json b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/package.json new file mode 100644 index 00000000..58da1d42 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.test-framework@1.0.13/package.json @@ -0,0 +1,21 @@ +{ + "name": "com.unity.test-framework", + "displayName": "Test Framework", + "version": "1.0.13", + "unity": "2019.2", + "unityRelease": "0a10", + "description": "Test framework for running Edit mode and Play mode test in Unity.", + "keywords": [ "Test", "TestFramework" ], + "category": "Unity Test Framework", + "repository": { + "type": "git", + "url": "git@gitlab.cds.internal.unity3d.com/upm-packages/core/com.unity.test-framework.git", + "revision": "8d09534f1c9f96b37fa38167a8697e5965ab58b8" + }, + "dependencies": { + "com.unity.ext.nunit": "1.0.0" + }, + "relatedPackages": { + "com.unity.test-framework.tests": "1.0.13" + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/.gitlab-ci.yml b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/.gitlab-ci.yml new file mode 100644 index 00000000..45a43a13 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/.gitlab-ci.yml @@ -0,0 +1,12 @@ +image: node:6.10.0 + +stages: + - push_to_packman_staging + +push_to_packman_staging: + stage: push_to_packman_staging + only: + - tags + script: + - curl -u $USER_NAME:$API_KEY https://staging-packages.unity.com/auth > .npmrc + - npm publish diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/CHANGELOG.md b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/CHANGELOG.md new file mode 100644 index 00000000..7b8d9d02 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/CHANGELOG.md @@ -0,0 +1,180 @@ +# Changelog +These are the release notes for the TextMesh Pro UPM package which was first introduced with Unity 2018.1. Please see the following link for the Release Notes for prior versions of TextMesh Pro. http://digitalnativestudios.com/forum/index.php?topic=1363.0 + +## [2.0.1] - 2019-05-08 +### Changes +- See Release 1.4.1 +- Requires .Net 4.x Scripting Runtime. + +## [2.0.0] - 2019-03-01 +### Changes +- Same release as 1.4.0 + +## [1.4.1] - 2019-05-08 +### Changes +- Improved handling of automatic Font Asset upgrade to version 1.1.0 which is required to support the new Dynamic SDF system. See Case #1144858 +- Made release compatible with .Net 3.5 Scripting Runtime. +- Added support for Stereo rendering to the TMP SDF Overlay shaders. +- Fixed Caret positioning issue when using IME. Case #1146626 + +## [1.4.0] - 2019-03-07 +### Changes +- Same release as 1.4.0-preview.3a. + +## [1.4.0-preview.3a] - 2019-02-28 +### Changes +- Improved performance of the Project Files GUID Remapping Tool. +- Fixed an issue with the TMP_FontAsset.TryAddCharacters() functions which was resulting in an error when added characters exceeded the capacity of the atlas texture. +- Updated TMP_FontAsset.TryAddCharacters functions to add new overloads returning list of characters that could not be added. +- Added function in OnEnable of FontAsset Editor's to clean up Fallback list to remove any null / empty entries. +- Added support for Stereo rendering to the TMP Distance Field and Mobile Distance Field shaders. + +## [1.4.0-preview.2a] - 2019-02-14 +### Changes +- Fixed an issue with SDF Scale handling where the text object would not render correctly after the object scale had been set to zero. +- Fixed an issue with the TMP_UpdateManager where text objects were not getting unregistered correctly. +- Any changes to Font Asset Creation Settings' padding, atlas width and / or atlas height will now result in all Material Presets for the given font asset to also be updated. +- Added new section in the TMP Settings related to the new Dynamic Font System. +- Added new property in the Dynamic Font System section to determine if OpenType Font Features will be retrieved from source font files at runtime as new characters are added to font assets. Glyph Adjustment Data (Kerning) is the only feature currently supported. +- Fix an issue where font assets created at runtime were not getting their asset version number set to "1.1.0". +- Improved parsing of the text file used in the Font Asset Creator and "Characters from File" option to handle UTF16 "\u" and UTF32 "\U" escape character sequences. +- Fixed a Null Reference Error (NRE) that could occur when using the <font> tag with an invalid font name followed by the <sprite> tag. +- The Glyph Adjustment Table presentation and internal data structure has been changed to facilitate the future addition of OpenType font features. See https://forum.unity.com/threads/version-1-4-0-preview-with-dynamic-sdf-for-unity-2018-3-now-available.622420/#post-4206595 for more details. +- Fixed an issue with the <rotate> tag incorrectly affecting character spacing. + +## [1.4.0-preview.1] - 2019-01-30 +### Changes +- Renamed TMPro_FontUtilities to TMP_FontAssetCommon to more accurately reflect the content of this file. +- Accessing the TextMesh Pro Settings via the new Edit - Settings menu when TMP Essential Resources have not yet been imported in the project will no longer open a new window to provide the options to import these resources. +- Fixed an issue where using int.MaxValue, int.MinValue, float.MaxValue and float.MinValue in conjunction with SetText() would display incorrect numerical values. Case #1078521. +- Added public setter to the TMP Settings' missingGlyphCharacter to allow changing which character will be used for missing characters via scripting. +- Fixed a potential Null Reference Exception related to loading the Default Style Sheet. +- Added compiler conditional to TMP_UpdateManager.cs to address changes to SRP. +- Improved the <margin> tag to make it possible to define both left and right margin values. Example: <margin left=10% right=10px>. +- Added new menu option to allow the quick creation of a UI Button using TMP. New menu option is located in Create - UI - Button (TextMeshPro). +- Renamed TMP related create menu options. +- Fixed TMP object creation handling when using Prefab isolation mode. Case #1077392 +- Fixed another issue related to Prefabs where some serialized properties of the text object would incorrectly show up in the Overrides prefab options. Case #1093101 +- Fixed issue where changing the Sorting Layer or Sorting Order of a object would not dirty the scene. Case #1069776 +- Fixed a text alignment issue when setting text alignment on disabled text objects. Case #1047771 +- Fixed an issue where text object bounds were not set correctly on newly created text objects or in some cases when setting the text to null or string.empty. Case #1093388 +- Fixed an issue in the IntToString() function that could result in Index Out Of Bounds error. Case #1102007 +- Changed the TMP_InputField IsValidChar function to protected virtual. +- The "Allow Rich Text Editing" property of the TMP_InputField is now set to false by default. +- Added new option to the Sprite Asset context menu to make it easier to update sprite glyphs edited via the Unity Sprite Editor. +- Added new Sharpness slider in the Debug section of the SDF Material inspector. +- Fixed an error that would occur when using the context menu Reset on text component. Case #1044726 +- Fixed issue where CharacterInfo.index would be incorrect as a result of using Surrogate Pairs in the text. Case #1037828 +- The TMP_EditorPanel and TMP_UiEditorPanel now have their "UseForChildren" flag set to true to enable user / custom inspectors to inherit from them. +- Fixed an issue where rich text tags using pixel (px) or font units (em) were not correctly accounting for orthographic camera mode. This change only affects the normal TMP text component. +- Fixed an inspector issue related to changes to the margin in the TMP Extra Settings panel. Case #1114253 +- Added new property to Glyph Adjustment Pairs which determines if Character Spacing Adjustments should affect the given pair. +- Updated the Glyph Adjustment Table where ID now represents the unicode (hex) value for the character instead of its decimal value. +- Added new SetValueWithoutNotify() function to TMP_DropDown and SetTextWithoutNotify() function to TMP_InputField allowing these to be set without triggering OnValueChanged event. +- Geometry buffer deallocation which normally takes place when current allocations exceed those of the new text by more than 256 characters will no longer occur if the new text is set to null or string.empty. +- Fixed a minor issue where the underline SDF scale would be incorrect when the underline text sequence contained normal size characters and ended with a subscript or superscript character. +- Fixed an error that would occur when using the Reset Context menu on a Material using the SDF Surface or Mobile SDF Surface Shaders. Case #1122279 +- Resolved a Null Reference Error that would appear when cycling through the text overflow modes. Case #1121624 + +## [1.3.0] - 2018-08-09 +### Changes +- Revamped UI to conform to Unity Human Interface Guidelines. +- Updated the title text on the Font Asset Creator window tab to "Font Asset Creator". +- Using TMP_Text.SetCharArray() with an empty char[] array will now clear the text. +- Made a small improvement to the TMP Input Field when using nested 2d RectMasks. +- Renamed symbol defines used by TMP to append TMP_ in front of the define to avoid potential conflicts with user defines. +- Improved the Project Files GUID Remapping tool to allow specifying a target folder to scan. +- Added the ability to cancel the scanning process used by the Project Files GUID Remapping tool. +- Moved TMP Settings to universal settings window in 2018.3 and above. +- Changing style sheet in the TMP Settings will now be reflected automatically on existing text objects in the editor. +- Added new function TMP_StyleSheet.UpdateStyleSheet() to update the internal reference to which style sheet text objects should be using in conjunction with the style tag. + +## [1.2.4] - 2018-06-10 +### Changes +- Fixed a minor issue when using Justified and Flush alignment in conjunction with \u00A0. +- The Font Asset creationSettings field is no longer an Editor only serialized field. + +## [1.2.3] - 2018-05-29 +### Changes +- Added new bitmap shader with support for Custom Font Atlas texture. This shader also includes a new property "Padding" to provide control over the geometry padding to closely fit a modified / custom font atlas texture. +- Fixed an issue with ForceMeshUpdate(bool ignoreActiveState) not being handled correctly. +- Cleaned up memory allocations from repeated use of the Font Asset Creator. +- Sprites are now scaled based on the current font instead of the primary font asset assigned to the text object. +- It is now possible to recall the most recent settings used when creating a font asset in the Font Asset Creator. +- Newly created font assets now contain the settings used when they were last created. This will make the process of updating / regenerating font assets much easier. +- New context menu "Update Font Asset" was added to the Font Asset inspector which will open the Font Asset Creator with the most recently used settings for that font asset. +- New Context Menu "Create Font Asset" was added to the Font inspector panel which will open the Font Asset Creator with this source font file already selected. +- Fixed 3 compiler warnings that would appear when using .Net 4.x. +- Modified the TMP Settings to place the Missing Glyph options in their own section. +- Renamed a symbol used for internal debugging to avoid potential conflicts with other user project defines. +- TMP Sprite Importer "Create Sprite Asset" and "Save Sprite Asset" options are disabled unless a Sprite Data Source, Import Format and Sprite Texture Atlas are provided. +- Improved the performance of the Project Files GUID Remapping tool. +- Users will now be prompted to import the TMP Essential Resources when using the Font Asset Creator if such resources have not already been imported. + +## [1.2.2] - 2018-03-28 +### Changes +- Calling SetAllDirty() on a TMP text component will now force a regeneration of the text object including re-parsing of the text. +- Fixed potential Null Reference Exception that could occur when assigning a new fallback font asset. +- Removed public from test classes. +- Fixed an issue where using nested links (which doesn't make sense conceptually) would result in an error. Should accidental use of nested links occurs, the last / most nested ends up being used. +- Fixed a potential text alignment issue where an hyphen at the end of a line followed by a new line containing a single word too long to fit the text container would result in miss alignment of the hyphen. +- Updated package license. +- Non-Breaking Space character (0xA0) will now be excluded from word spacing adjustments when using Justified or Flush text alignment. +- Improved handling of Underline, Strikethrough and Mark tag with regards to vertex color and Color tag alpha. +- Improved TMP_FontAsset.HasCharacter(char character, bool searchFallbacks) to include a recursive search of fallbacks as well as TMP Settings fallback list and default font asset. +- The <gradient> tag will now also apply to sprites provided the sprite tint attribute is set to a value of 1. Ex. <sprite="Sprite Asset" index=0 tint=1>. +- Updated Font Asset Creator Plugin to allow for cancellation of the font asset generation process. +- Added callback to support the Scriptable Render Pipeline (SRP) with the normal TextMeshPro component. +- Improved handling of some non-breaking space characters which should not be ignored at the end of a line. +- Sprite Asset fallbacks will now be searched when using the <sprite> tag and referencing a sprite by Unicode or by Name. +- Updated EmojiOne samples from https://www.emojione.com/ and added attribution. +- Removed the 32bit versions of the TMP Plugins used by the Font Asset Creator since the Unity Editor is now only available as 64bit. +- The isTextTruncated property is now serialized. +- Added new event handler to the TMP_TextEventHandler.cs script included in Example 12a to allow tracking of interactions with Sprites. + +## [1.2.1] - 2018-02-14 +### Changes +- Package is now backwards compatible with Unity 2018.1. +- Renamed Assembly Definitions (.asmdef) to new UPM package conventions. +- Added DisplayName for TMP UPM package. +- Revised Editor and Playmode tests to ignore / skip over the tests if the required resources are not present in the project. +- Revised implementation of Font Asset Creator progress bar to use Unity's EditorGUI.ProgressBar instead of custom texture. +- Fixed an issue where using the material tag in conjunction with fallback font assets was not handled correctly. +- Fixed an issue where changing the fontStyle property in conjunction with using alternative typefaces / font weights would not correctly trigger a regeneration of the text object. + +## [1.2.0] - 2018-01-23 +### Changes +- Package version # increased to 1.2.0 which is the first release for Unity 2018.2. + +## [1.1.0] - 2018-01-23 +### Changes +- Package version # increased to 1.1.0 which is the first release for Unity 2018.1. + +## [1.0.27] - 2018-01-16 +### Changes +- Fixed an issue where setting the TMP_InputField.text property to null would result in an error. +- Fixed issue with Raycast Target state not getting serialized properly when saving / reloading a scene. +- Changed reference to PrefabUtility.GetPrefabParent() to PrefabUtility.GetCorrespondingObjectFromSource() to reflect public API change in 2018.2 +- Option to import package essential resources will only be presented to users when accessing a TMP component or the TMP Settings file via the project menu. + +## [1.0.26] - 2018-01-10 +### Added +- Removed Tizen player references in the TMP_InputField as the Tizen player is no longer supported as of Unity 2018.1. + +## [1.0.25] - 2018-01-05 +### Added +- Fixed a minor issue with PreferredValues calculation in conjunction with using text auto-sizing. +- Improved Kerning handling where it is now possible to define positional adjustments for the first and second glyph in the pair. +- Renamed Kerning Info Table to Glyph Adjustment Table to better reflect the added functionality of this table. +- Added Search toolbar to the Glyph Adjustment Table. +- Fixed incorrect detection / handling of Asset Serialization mode in the Project Conversion Utility. +- Removed SelectionBase attribute from TMP components. +- Revised TMP Shaders to support the new UNITY_UI_CLIP_RECT shader keyword which can provide a performance improvement of up to 30% on some devices. +- Added TMP_PRESENT define as per the request of several third party asset publishers. + +## [1.0.23] - 2017-11-14 +### Added +- New menu option added to Import Examples and additional content like Font Assets, Materials Presets, etc for TextMesh Pro. This new menu option is located in "Window -> TextMeshPro -> Import Examples and Extra Content". +- New menu option added to Convert existing project files and assets created with either the Source Code or DLL only version of TextMesh Pro. Please be sure to backup your project before using this option. The new menu option is located in "Window -> TextMeshPro -> Project Files GUID Remapping Tool". +- Added Assembly Definitions for the TMP Runtime and Editor scripts. +- Added support for the UI DirtyLayoutCallback, DirtyVerticesCallback and DirtyMaterialCallback. \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Gizmos/TMP - Dropdown Icon.psd b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Gizmos/TMP - Dropdown Icon.psd new file mode 100644 index 00000000..93f5a2cb Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Gizmos/TMP - Dropdown Icon.psd differ diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Gizmos/TMP - Font Asset Icon.psd b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Gizmos/TMP - Font Asset Icon.psd new file mode 100644 index 00000000..2fb1164d Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Gizmos/TMP - Font Asset Icon.psd differ diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Gizmos/TMP - Input Field Icon.psd b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Gizmos/TMP - Input Field Icon.psd new file mode 100644 index 00000000..f0360d34 Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Gizmos/TMP - Input Field Icon.psd differ diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Gizmos/TMP - Sprite Asset Icon.psd b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Gizmos/TMP - Sprite Asset Icon.psd new file mode 100644 index 00000000..7036296e Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Gizmos/TMP - Sprite Asset Icon.psd differ diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Gizmos/TMP - Text Component Icon.psd b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Gizmos/TMP - Text Component Icon.psd new file mode 100644 index 00000000..3cc41630 Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Gizmos/TMP - Text Component Icon.psd differ diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Shaders/TMP_Properties.cginc b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Shaders/TMP_Properties.cginc new file mode 100644 index 00000000..2e962588 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Shaders/TMP_Properties.cginc @@ -0,0 +1,85 @@ +// UI Editable properties +uniform sampler2D _FaceTex; // Alpha : Signed Distance +uniform float _FaceUVSpeedX; +uniform float _FaceUVSpeedY; +uniform fixed4 _FaceColor; // RGBA : Color + Opacity +uniform float _FaceDilate; // v[ 0, 1] +uniform float _OutlineSoftness; // v[ 0, 1] + +uniform sampler2D _OutlineTex; // RGBA : Color + Opacity +uniform float _OutlineUVSpeedX; +uniform float _OutlineUVSpeedY; +uniform fixed4 _OutlineColor; // RGBA : Color + Opacity +uniform float _OutlineWidth; // v[ 0, 1] + +uniform float _Bevel; // v[ 0, 1] +uniform float _BevelOffset; // v[-1, 1] +uniform float _BevelWidth; // v[-1, 1] +uniform float _BevelClamp; // v[ 0, 1] +uniform float _BevelRoundness; // v[ 0, 1] + +uniform sampler2D _BumpMap; // Normal map +uniform float _BumpOutline; // v[ 0, 1] +uniform float _BumpFace; // v[ 0, 1] + +uniform samplerCUBE _Cube; // Cube / sphere map +uniform fixed4 _ReflectFaceColor; // RGB intensity +uniform fixed4 _ReflectOutlineColor; +//uniform float _EnvTiltX; // v[-1, 1] +//uniform float _EnvTiltY; // v[-1, 1] +uniform float3 _EnvMatrixRotation; +uniform float4x4 _EnvMatrix; + +uniform fixed4 _SpecularColor; // RGB intensity +uniform float _LightAngle; // v[ 0,Tau] +uniform float _SpecularPower; // v[ 0, 1] +uniform float _Reflectivity; // v[ 5, 15] +uniform float _Diffuse; // v[ 0, 1] +uniform float _Ambient; // v[ 0, 1] + +uniform fixed4 _UnderlayColor; // RGBA : Color + Opacity +uniform float _UnderlayOffsetX; // v[-1, 1] +uniform float _UnderlayOffsetY; // v[-1, 1] +uniform float _UnderlayDilate; // v[-1, 1] +uniform float _UnderlaySoftness; // v[ 0, 1] + +uniform fixed4 _GlowColor; // RGBA : Color + Intesity +uniform float _GlowOffset; // v[-1, 1] +uniform float _GlowOuter; // v[ 0, 1] +uniform float _GlowInner; // v[ 0, 1] +uniform float _GlowPower; // v[ 1, 1/(1+4*4)] + +// API Editable properties +uniform float _ShaderFlags; +uniform float _WeightNormal; +uniform float _WeightBold; + +uniform float _ScaleRatioA; +uniform float _ScaleRatioB; +uniform float _ScaleRatioC; + +uniform float _VertexOffsetX; +uniform float _VertexOffsetY; + +//uniform float _UseClipRect; +uniform float _MaskID; +uniform sampler2D _MaskTex; +uniform float4 _MaskCoord; +uniform float4 _ClipRect; // bottom left(x,y) : top right(z,w) +//uniform float _MaskWipeControl; +//uniform float _MaskEdgeSoftness; +//uniform fixed4 _MaskEdgeColor; +//uniform bool _MaskInverse; + +uniform float _MaskSoftnessX; +uniform float _MaskSoftnessY; + +// Font Atlas properties +uniform sampler2D _MainTex; +uniform float _TextureWidth; +uniform float _TextureHeight; +uniform float _GradientScale; +uniform float _ScaleX; +uniform float _ScaleY; +uniform float _PerspectiveFilter; +uniform float _Sharpness; diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Shaders/TMP_SDF Internal SSD.shader b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Shaders/TMP_SDF Internal SSD.shader new file mode 100644 index 00000000..7e28d745 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Shaders/TMP_SDF Internal SSD.shader @@ -0,0 +1,126 @@ +// Simplified SDF shader: +// - No Shading Option (bevel / bump / env map) +// - No Glow Option +// - Softness is applied on both side of the outline + +Shader "Hidden/TextMeshPro/Internal/Distance Field SSD" { + +Properties { + _FaceColor ("Face Color", Color) = (1,1,1,1) + _FaceDilate ("Face Dilate", Range(-1,1)) = 0 + + _OutlineSoftness ("Outline Softness", Range(0,1)) = 0.02 + + _WeightNormal ("Weight Normal", float) = 0 + _WeightBold ("Weight Bold", float) = .5 + + _MainTex ("Font Atlas", 2D) = "white" {} + _TextureWidth ("Texture Width", float) = 512 + _TextureHeight ("Texture Height", float) = 512 + _GradientScale ("Gradient Scale", float) = 5 + _ScaleX ("Scale X", float) = 1 + _ScaleY ("Scale Y", float) = 1 + _Sharpness ("Sharpness", Range(-1,1)) = 0 + + _VertexOffsetX ("Vertex OffsetX", float) = 0 + _VertexOffsetY ("Vertex OffsetY", float) = 0 + + _ColorMask ("Color Mask", Float) = 15 +} + +SubShader { + Tags + { + "ForceSupported" = "True" + } + + Lighting Off + Blend One OneMinusSrcAlpha + Cull Off + ZWrite Off + ZTest Always + + Pass { + CGPROGRAM + #pragma vertex VertShader + #pragma fragment PixShader + + #include "UnityCG.cginc" + #include "TMP_Properties.cginc" + + sampler2D _GUIClipTexture; + uniform float4x4 unity_GUIClipTextureMatrix; + + struct vertex_t { + float4 vertex : POSITION; + float3 normal : NORMAL; + fixed4 color : COLOR; + float2 texcoord0 : TEXCOORD0; + float2 texcoord1 : TEXCOORD1; + }; + + struct pixel_t { + float4 vertex : SV_POSITION; + fixed4 faceColor : COLOR; + float2 texcoord0 : TEXCOORD0; + float2 clipUV : TEXCOORD1; + }; + + + pixel_t VertShader(vertex_t input) + { + // Does not handle simulated bold correctly. + + float4 vert = input.vertex; + vert.x += _VertexOffsetX; + vert.y += _VertexOffsetY; + float4 vPosition = UnityObjectToClipPos(vert); + + float opacity = input.color.a; + + fixed4 faceColor = fixed4(input.color.rgb, opacity) * _FaceColor; + faceColor.rgb *= faceColor.a; + + // Generate UV for the Clip Texture + float3 eyePos = UnityObjectToViewPos(input.vertex); + float2 clipUV = mul(unity_GUIClipTextureMatrix, float4(eyePos.xy, 0, 1.0)); + + // Structure for pixel shader + pixel_t output = { + vPosition, + faceColor, + float2(input.texcoord0.x, input.texcoord0.y), + clipUV, + }; + + return output; + } + + half transition(half2 range, half distance) + { + return smoothstep(range.x, range.y, distance); + } + + // PIXEL SHADER + fixed4 PixShader(pixel_t input) : SV_Target + { + half distanceSample = tex2D(_MainTex, input.texcoord0).a; + half smoothing = fwidth(distanceSample) * (1 - _Sharpness) + _OutlineSoftness; + half contour = 0.5 - _FaceDilate * 0.5; + half2 edgeRange = half2(contour - smoothing, contour + smoothing); + + half4 c = input.faceColor; + + half edgeTransition = transition(edgeRange, distanceSample); + c *= edgeTransition; + + c *= tex2D(_GUIClipTexture, input.clipUV).a; + + return c; + } + ENDCG + } +} + +CustomEditor "TMPro.EditorUtilities.TMP_SDFShaderGUI" +} diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/SectionHeader_Dark.psd b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/SectionHeader_Dark.psd new file mode 100644 index 00000000..8ebaa27a Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/SectionHeader_Dark.psd differ diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/SectionHeader_Light.psd b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/SectionHeader_Light.psd new file mode 100644 index 00000000..e598e6d9 Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/SectionHeader_Light.psd differ diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignBaseLine.psd b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignBaseLine.psd new file mode 100644 index 00000000..3da358a1 Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignBaseLine.psd differ diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignBaseLine_Light.psd b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignBaseLine_Light.psd new file mode 100644 index 00000000..cf49b6cb Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignBaseLine_Light.psd differ diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignBottom.psd b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignBottom.psd new file mode 100644 index 00000000..1f35779e Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignBottom.psd differ diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignBottom_Light.psd b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignBottom_Light.psd new file mode 100644 index 00000000..d8af55bd Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignBottom_Light.psd differ diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignCapLine.psd b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignCapLine.psd new file mode 100644 index 00000000..7eefe6b2 Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignCapLine.psd differ diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignCapLine_Light.psd b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignCapLine_Light.psd new file mode 100644 index 00000000..f08bb6ce Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignCapLine_Light.psd differ diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignCenter.psd b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignCenter.psd new file mode 100644 index 00000000..939bc6dc Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignCenter.psd differ diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignCenterGeo.psd b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignCenterGeo.psd new file mode 100644 index 00000000..f9ce9a8b Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignCenterGeo.psd differ diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignCenterGeo_Light.psd b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignCenterGeo_Light.psd new file mode 100644 index 00000000..e37b2e25 Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignCenterGeo_Light.psd differ diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignCenter_Light.psd b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignCenter_Light.psd new file mode 100644 index 00000000..7274887f Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignCenter_Light.psd differ diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignFlush.psd b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignFlush.psd new file mode 100644 index 00000000..eeeea67b Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignFlush.psd differ diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignFlush_Light.psd b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignFlush_Light.psd new file mode 100644 index 00000000..b69f6a2e Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignFlush_Light.psd differ diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignJustified.psd b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignJustified.psd new file mode 100644 index 00000000..3ce55c49 Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignJustified.psd differ diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignJustified_Light.psd b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignJustified_Light.psd new file mode 100644 index 00000000..d7fd5c82 Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignJustified_Light.psd differ diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignLeft.psd b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignLeft.psd new file mode 100644 index 00000000..fc7e10b2 Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignLeft.psd differ diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignLeft_Light.psd b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignLeft_Light.psd new file mode 100644 index 00000000..5522c373 Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignLeft_Light.psd differ diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignMidLine.psd b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignMidLine.psd new file mode 100644 index 00000000..14d28a2d Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignMidLine.psd differ diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignMiddle.psd b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignMiddle.psd new file mode 100644 index 00000000..c4483dbd Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignMiddle.psd differ diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignMiddle_Light.psd b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignMiddle_Light.psd new file mode 100644 index 00000000..4263bf9b Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignMiddle_Light.psd differ diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignMidline_Light.psd b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignMidline_Light.psd new file mode 100644 index 00000000..a5bed371 Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignMidline_Light.psd differ diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignRight.psd b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignRight.psd new file mode 100644 index 00000000..4ef1998b Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignRight.psd differ diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignRight_Light.psd b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignRight_Light.psd new file mode 100644 index 00000000..bdeff413 Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignRight_Light.psd differ diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignTop.psd b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignTop.psd new file mode 100644 index 00000000..b00d4585 Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignTop.psd differ diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignTop_Light.psd b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignTop_Light.psd new file mode 100644 index 00000000..84f0e61c Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Editor Resources/Textures/btn_AlignTop_Light.psd differ diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/LICENSE.md b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/LICENSE.md new file mode 100644 index 00000000..37d06155 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/LICENSE.md @@ -0,0 +1,5 @@ +TextMesh Pro copyright © 2014-2019 Unity Technologies ApS + +Licensed under the Unity Companion License for Unity-dependent projects--see [Unity Companion License](http://www.unity3d.com/legal/licenses/Unity_Companion_License). + +Unless expressly provided otherwise, the Software under this license is made available strictly on an “AS IS” BASIS WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED. Please review the license for details on these and other terms and conditions. \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Package Resources/TMP Essential Resources.unitypackage b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Package Resources/TMP Essential Resources.unitypackage new file mode 100644 index 00000000..6c1904f4 Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Package Resources/TMP Essential Resources.unitypackage differ diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Package Resources/TMP Examples & Extras.unitypackage b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Package Resources/TMP Examples & Extras.unitypackage new file mode 100644 index 00000000..975bf1be Binary files /dev/null and b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Package Resources/TMP Examples & Extras.unitypackage differ diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/PackageConversionData.json b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/PackageConversionData.json new file mode 100644 index 00000000..05c193e2 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/PackageConversionData.json @@ -0,0 +1,654 @@ +{ + "assetRecords": [ + { + "referencedResource": "Blue to Purple - Vertical.asset", + "target": "guid: 1e643bbd7e13d46418da3774e72bef60", + "replacement": "guid: 479a66fa4b094512a62b0a8e553ad95a" + }, + { + "referencedResource": "Dark to Light Green - Vertical.asset", + "target": "guid: 90c9133b254e2184b8084dea4f392337", + "replacement": "guid: 4c86a3366cd840348ebe8dc438570ee4" + }, + { + "referencedResource": "Light to Dark Green - Vertical.asset", + "target": "guid: 33c745f0979f3984182a138bcc6e57ec", + "replacement": "guid: 5cf8ae092ca54931b443bec5148f3c59" + }, + { + "referencedResource": "Yellow to Orange - Vertical.asset", + "target": "guid: e002cb2a36d9e4a439a062867fa24e1e", + "replacement": "guid: 69a525efa7e6472eab268f6ea605f06e" + }, + { + "referencedResource": "Crate - Surface Shader Scene.mat", + "target": "guid: e177c46c2a091564d88df2c2ca9dcf97", + "replacement": "guid: e6b9b44320f4448d9d5e0ee634259966" + }, + { + "referencedResource": "Ground - Logo Scene.mat", + "target": "guid: 504ae362e57fc464b847f1e9fd0e4035", + "replacement": "guid: c719e38f25a9480abd2480ab621a2949" + }, + { + "referencedResource": "Ground - Surface Shader Scene.mat", + "target": "guid: 9ed9aa864ec2d7f4dad266b9534c6d85", + "replacement": "guid: aadd5a709a48466c887296bb5b1b8110" + }, + { + "referencedResource": "Small Crate_diffuse.mat", + "target": "guid: 92f161029a6d3c54a92d9d283352a135", + "replacement": "guid: 22262639920f43d6be32430e4e58350d" + }, + { + "referencedResource": "Text Popup.prefab", + "target": "guid: c879e892866c8db4f8930b25672233ac", + "replacement": "guid: b06f0e6c1dfa4356ac918da1bb32c603" + }, + { + "referencedResource": "TextMeshPro - Prefab 1.prefab", + "target": "guid: a6a60659abb4d9d4b934feebd3dcc952", + "replacement": "guid: a6e39ced0ea046bcb636c3f0b2e2a745" + }, + { + "referencedResource": "TextMeshPro - Prefab 2.prefab", + "target": "guid: 1b190e3e0ab4c8e4881656b9160c59c2", + "replacement": "guid: fdad9d952ae84cafb74c63f2e694d042" + }, + { + "referencedResource": "Anton SDF.asset", + "target": "guid: f76ef802b8b940c46a31f9027f2b0158", + "replacement": "guid: 8a89fa14b10d46a99122fd4f73fca9a2" + }, + { + "referencedResource": "Anton SDF - Drop Shadow.mat", + "target": "guid: 250a1a103b3b4914c9707e6a423446d6", + "replacement": "guid: 749b9069dc4742c5bfa5c74644049926" + }, + { + "referencedResource": "Anton SDF - Outline.mat", + "target": "guid: e077dc203e948b740859c1c0ca8b9691", + "replacement": "guid: a00013af81304728b2be1f4309ee2433" + }, + { + "referencedResource": "Bangers SDF.asset", + "target": "guid: 808aa8f1ab804104aa7d0c337a6c1481", + "replacement": "guid: 125cb55b44b24c4393181402bc6200e6" + }, + { + "referencedResource": "Bangers SDF - Drop Shadow.mat", + "target": "guid: c26f698d4eee19e4a8b8f42cd299bab5", + "replacement": "guid: f2dcf029949142e28b974630369c8b4e" + }, + { + "referencedResource": "Bangers SDF - Outline.mat", + "target": "guid: db7f2cfbf23d6d54ca4e74a9abd55326", + "replacement": "guid: f629c6e43dba4bf38cb74d8860150664" + }, + { + "referencedResource": "Bangers SDF Glow.mat", + "target": "guid: 7dd7006c58d8a3148a73aa211d8c13d0", + "replacement": "guid: d75b8f41e959450c84ac6e967084d3e1" + }, + { + "referencedResource": "Bangers SDF Logo.mat", + "target": "guid: 4fb51aa7001a2244395ddf6a15d37389", + "replacement": "guid: f4e195ac1e204eff960149d1cb34e18c" + }, + { + "referencedResource": "Electronic Highway Sign SDF.asset", + "target": "guid: 163292f6f226d954593d45b079f8aae0", + "replacement": "guid: dc36b3fdc14f47ebb36fd484a67e268a" + }, + { + "referencedResource": "LiberationSans SDF - Drop Shadow.mat", + "target": "guid: 33db60c37b63f08448ded4b385e74e38", + "replacement": "guid: e73a58f6e2794ae7b1b7e50b7fb811b0" + }, + { + "referencedResource": "LiberationSans SDF - Metalic Green.mat", + "target": "guid: 4f9843c79516ed1468b9b5a4f32e67e3", + "replacement": "guid: 8b29aaa3eec7468097ff07adfcf29ac9" + }, + { + "referencedResource": "LiberationSans SDF - Outline.mat", + "target": "guid: 83a1b0fe6c3dbac44b66f09c82e1d509", + "replacement": "guid: 79459efec17a4d00a321bdcc27bbc385" + }, + { + "referencedResource": "LiberationSans SDF - Overlay.mat", + "target": "guid: 55eb086ae18c76e4bb6cc7106d0dd6e2", + "replacement": "guid: 9ad269c99dcf42b7aedefd83dd5a7b9d" + }, + { + "referencedResource": "LiberationSans SDF - Soft Mask.mat", + "target": "guid: 74e06d99c1657fc4abd33f20685ea9ff", + "replacement": "guid: 42df1c7856584b6b8db9a509b6b10074" + }, + { + "referencedResource": "Oswald Bold SDF.asset", + "target": "guid: 09641b029dfa78843902b548a9de7553", + "replacement": "guid: 0161d805a3764c089bef00bfe00793f5" + }, + { + "referencedResource": "Roboto-Bold SDF.asset", + "target": "guid: d62a573c923f5cb47b8ff65261033b90", + "replacement": "guid: 5302535af1044152a457ed104f1f4b91" + }, + { + "referencedResource": "Roboto-Bold SDF - Drop Shadow.mat", + "target": "guid: 102e7c5c5e3b1f3468518cb166967d77", + "replacement": "guid: b246c4190f4e46ec9352fe15a7b09ce0" + }, + { + "referencedResource": "Roboto-Bold SDF - Surface.mat", + "target": "guid: e2da38ead8f8238449c54a1ef49e080f", + "replacement": "guid: e6b276ec991f467aa14ef1f3cc665993" + }, + { + "referencedResource": "DropCap Numbers.asset", + "target": "guid: c4fd2a959a50b584b92dedfefec1ffda", + "replacement": "guid: 14aa93acbb234d16aaef0e8b46814db6" + }, + { + "referencedResource": "Benchmark01.cs", + "target": "guid: c5fb1b5c24460f745be29cc0eb06a58c", + "replacement": "guid: f970ea55f9f84bf79b05dab180b8c125" + }, + { + "referencedResource": "Benchmark01_UGUI.cs", + "target": "guid: 5e6abf300e36c0a4eb43969c3f2172f8", + "replacement": "guid: 8ef7be1c625941f7ba8ed7cc71718c0d" + }, + { + "referencedResource": "Benchmark02.cs", + "target": "guid: 3467f4170568a484d8b57e2051a27363", + "replacement": "guid: e8538afcddc14efbb5d9e94b7ae50197" + }, + { + "referencedResource": "Benchmark03.cs", + "target": "guid: e6e9d20624a23da4c8b2b6fb7608bb9a", + "replacement": "guid: a73109742c8d47ac822895a473300c29" + }, + { + "referencedResource": "Benchmark04.cs", + "target": "guid: 481dd67bdedc3104ea2156ed49f3acd5", + "replacement": "guid: dc20866c0d5e413ab7559440e15333ae" + }, + { + "referencedResource": "CameraController.cs", + "target": "guid: a9f0e07aefca0cc459134ff9df622278", + "replacement": "guid: 2d687537154440a3913a9a3c7977978c" + }, + { + "referencedResource": "ChatController.cs", + "target": "guid: eba5a4db2591a5844aea5f6f3ad8548e", + "replacement": "guid: 53d91f98a2664f5cb9af11de72ac54ec" + }, + { + "referencedResource": "EnvMapAnimator.cs", + "target": "guid: 7e69f3f28c520ce4d9ab9964b2895b1a", + "replacement": "guid: a4b6f99e8bc54541bbd149b014ff441c" + }, + { + "referencedResource": "ObjectSpin.cs", + "target": "guid: 5e7872ff51989434dabf7807265ada3c", + "replacement": "guid: 4f19c7f94c794c5097d8bd11e39c750d" + }, + { + "referencedResource": "ShaderPropAnimator.cs", + "target": "guid: c56cf968fb6a5b6488e709242718845d", + "replacement": "guid: 2787a46a4dc848c1b4b7b9307b614bfd" + }, + { + "referencedResource": "SimpleScript.cs", + "target": "guid: c64808ff5137c9044a583750e5b0468a", + "replacement": "guid: 9eff140b25d64601aabc6ba32245d099" + }, + { + "referencedResource": "SkewTextExample.cs", + "target": "guid: 48d40dfeb33b717488f55ddbf676643a", + "replacement": "guid: d412675cfb3441efa3bf8dcd9b7624dc" + }, + { + "referencedResource": "TeleType.cs", + "target": "guid: 9094c5c777af3f14489e8947748e86e6", + "replacement": "guid: e32c266ee6204b21a427753cb0694c81" + }, + { + "referencedResource": "TextConsoleSimulator.cs", + "target": "guid: 45757dcc8f119454dac6365e8fd15e8b", + "replacement": "guid: 43bcd35a1c0c40ccb6d472893fe2093f" + }, + { + "referencedResource": "TextMeshProFloatingText.cs", + "target": "guid: dd0e4b969aa70504382a89d2f208ae6c", + "replacement": "guid: a4d4c76e63944cba8c7d00f56334b98c" + }, + { + "referencedResource": "TextMeshSpawner.cs", + "target": "guid: 385939aed18e82d41894437798c30ed8", + "replacement": "guid: 76c11bbcfddf44e0ba17d6c2751c8d84" + }, + { + "referencedResource": "TMP_ExampleScript_01.cs", + "target": "guid: 36bafabb5572c6347923b971425ab3be", + "replacement": "guid: 6f2c5b59b6874405865e2616e4ec276a" + }, + { + "referencedResource": "TMP_FrameRateCounter.cs", + "target": "guid: c0357609254b68d4881cab18f04dd4dc", + "replacement": "guid: 686ec78b56aa445795335fbadafcfaa4" + }, + { + "referencedResource": "TMP_TextEventCheck.cs", + "target": "guid: ba181bda76b7f6047ba2188e94bf0894", + "replacement": "guid: d736ce056cf444ca96e424f4d9c42b76" + }, + { + "referencedResource": "TMP_TextEventHandler.cs", + "target": "guid: 48a2fdbd95acd794caf78a85a0b6926a", + "replacement": "guid: 1312ae25639a4bae8e25ae223209cc50" + }, + { + "referencedResource": "TMP_TextInfoDebugTool.cs", + "target": "guid: 5eeee4467ee5b6a4884a1ec94812d93e", + "replacement": "guid: 21256c5b62f346f18640dad779911e20" + }, + { + "referencedResource": "TMP_TextSelector_A.cs", + "target": "guid: 68baf2864c88f4a43a50f16709de8717", + "replacement": "guid: 103e0a6a1d404693b9fb1a5173e0e979" + }, + { + "referencedResource": "TMP_TextSelector_B.cs", + "target": "guid: f499ff45b9a3d0840a0df48d01b2877b", + "replacement": "guid: a05dcd8be7ec4ccbb35c26219884aa37" + }, + { + "referencedResource": "TMP_UiFrameRateCounter.cs", + "target": "guid: dc33b7a34d20d5e4e8d54b6867ce81e3", + "replacement": "guid: 24b0dc2d1d494adbbec1f4db26b4cf83" + }, + { + "referencedResource": "TMPro_InstructionOverlay.cs", + "target": "guid: 53b866620ba77504eaf52cab7dbd95c9", + "replacement": "guid: c3c1afeda5e545e0b19add5373896d2e" + }, + { + "referencedResource": "VertexColorCycler.cs", + "target": "guid: c8d54cdd5913d4e4bb7b655d7d16835b", + "replacement": "guid: 91b8ba3d52e041fab2d0e0f169855539" + }, + { + "referencedResource": "VertexJitter.cs", + "target": "guid: e4769cb37968ea948a763a9a89f9e583", + "replacement": "guid: 2ed57967c52645d390a89dcf8f61ba73" + }, + { + "referencedResource": "VertexShakeA.cs", + "target": "guid: eaa12d191e718c945ac55da73fa469db", + "replacement": "guid: f7cfa58e417a46ea8889989684c2522e" + }, + { + "referencedResource": "VertexShakeB.cs", + "target": "guid: 32c83a5d3ba42b84aa26386eac47566b", + "replacement": "guid: e4e0d9ccee5f4950be8979268c9014e0" + }, + { + "referencedResource": "VertexZoom.cs", + "target": "guid: 5305493000edc7d4ea4302757dc19a99", + "replacement": "guid: 52ec835d14bd486f900952b77698b7eb" + }, + { + "referencedResource": "WarpTextExample.cs", + "target": "guid: f3eef864a10f51045a7530e2afe7c179", + "replacement": "guid: 790744c462254b7ba8038e6ed28b3db2" + }, + { + "referencedResource": "DropCap Numbers.psd", + "target": "guid: 28b41fef228d6814f90e541deaf9f262", + "replacement": "guid: fd09957580ac4326916010f1f260975b" + }, + { + "referencedResource": "Brushed Metal 3.jpg", + "target": "guid: c30270e41dccf9441ab56d94261bdcfa", + "replacement": "guid: f88677df267a41d6be1e7a6133e7d227" + }, + { + "referencedResource": "Engraved Wall.jpg", + "target": "guid: 93d6f74f2ef358e41989d4152b195f88", + "replacement": "guid: e0f91e6569da4934a48d85bf8d3063f0" + }, + { + "referencedResource": "Engraved Wall Normal.jpg", + "target": "guid: 1edd0950293e8664094053a041548c23", + "replacement": "guid: 20f91c93e7fb490f9496609c52ef3904" + }, + { + "referencedResource": "Floor Cement.jpg", + "target": "guid: ac5a0a5373b36e049bb7f98f88dbc244", + "replacement": "guid: 283f897e4925411ebbaa758b4cb13fc2" + }, + { + "referencedResource": "Floor Tiles 1 - diffuse.jpg", + "target": "guid: 7bbfb8818476e4641ba3e75f5225eb69", + "replacement": "guid: 85ac55597b97403c82fc6601a93cf241" + }, + { + "referencedResource": "Floor Tiles 1 - normal.jpg", + "target": "guid: e00d5a9a0944134448432ccacf221b95", + "replacement": "guid: c45cd05946364f32aba704f0853a975b" + }, + { + "referencedResource": "Fruit Jelly (B&W).jpg", + "target": "guid: 74d8c208a0193e14ca6916bea88a2c52", + "replacement": "guid: 1cdc5b506b1a4a33a53c30669ced1f51" + }, + { + "referencedResource": "Gradient Diagonal (Color).jpg", + "target": "guid: 2421a4955e71725448211e6bfbc7d7fb", + "replacement": "guid: 2ce5c55e85304b819a1826ecbc839aa5" + }, + { + "referencedResource": "Gradient Horizontal (Color).jpg", + "target": "guid: 0bbb43aff4f7811419ffceb1b16cf3d6", + "replacement": "guid: 6eb184de103d4b3f812b38561065192f" + }, + { + "referencedResource": "Gradient Vertical (Color).jpg", + "target": "guid: 3359915af07779e4e9a966df9eed764f", + "replacement": "guid: 03d0538de6e24c0f819bfc9ce084dfa9" + }, + { + "referencedResource": "Mask Zig-n-Zag.psd", + "target": "guid: 04eb87e72b3c1c648ba47a869ee00505", + "replacement": "guid: bb8dfcd263ad4eb383a33d74a720be6f" + }, + { + "referencedResource": "Sand Normal Map.jpg", + "target": "guid: 89e1b1c005d29cf4598ea861deb35a80", + "replacement": "guid: 8b8c8a10edf94ddc8cc4cc4fcd5696a9" + }, + { + "referencedResource": "Small Crate_diffuse.jpg", + "target": "guid: 64734c9bc6df32149a0c9cb0b18693e1", + "replacement": "guid: 602cb87b6a29443b8636370ea0751574" + }, + { + "referencedResource": "Small Crate_normal.jpg", + "target": "guid: 81b50d9cb6f3104448ec54c00a80101a", + "replacement": "guid: 8878a782f4334ecbbcf683b3ac780966" + }, + { + "referencedResource": "Stainless 03.png", + "target": "guid: 40d7f27f614cc1043a1f7e19074f461c", + "replacement": "guid: 83cb272f9ee046f6ab6636ca38af8db4" + }, + { + "referencedResource": "Text Overflow - Linked Text Image 1.png", + "target": "guid: 1fd8c568b1fcdbe43be65c1619cf3293", + "replacement": "guid: 4ccf43d26c4748c792174516f4a8fcef" + }, + { + "referencedResource": "Text Overflow - Linked Text UI Screenshot.png", + "target": "guid: 7983d2ec0427c114a916ae3c4769dc10", + "replacement": "guid: c76d18757a194d618355f05f815cb0a1" + }, + { + "referencedResource": "Wipe Pattern - Circle.psd", + "target": "guid: 6f5e9497d22a7a84193ec825e2eb41ac", + "replacement": "guid: 10c49fcd9c64421db7c0133e61e55f97" + }, + { + "referencedResource": "Wipe Pattern - Diagonal.psd", + "target": "guid: 8ee4d366b96418044aa9f94b3e2de645", + "replacement": "guid: ed5290d8df18488780e2996b9b882f01" + }, + { + "referencedResource": "Wipe Pattern - Radial Double.psd", + "target": "guid: 3e0e22da7c9570b498205179ef58ef38", + "replacement": "guid: 7631f4eff8f74ed38eb3eb9db17134e1" + }, + { + "referencedResource": "Wipe Pattern - Radial Quad.psd", + "target": "guid: 05ffd580f33f74644a6025ec196860af", + "replacement": "guid: 2b5e9ae96c5644d8bae932f8b4ca68a2" + }, + { + "referencedResource": "LiberationSans SDF.asset", + "target": "guid: 715b80e429c437e40867928a4e1fc975", + "replacement": "guid: 8f586378b4e144a9851e7b34d9b748ee" + }, + { + "referencedResource": "LineBreaking Following Characters.txt", + "target": "guid: 312ba5b9e90627940866e19549a788cf", + "replacement": "guid: fade42e8bc714b018fac513c043d323b" + }, + { + "referencedResource": "LineBreaking Leading Characters.txt", + "target": "guid: 8d713940fcbede142ae4a33ea0062b33", + "replacement": "guid: d82c1b31c7e74239bff1220585707d2b" + }, + { + "referencedResource": "TMP_Bitmap.shader", + "target": "guid: edfcf888cd11d9245b91d2883049a57e", + "replacement": "guid: 128e987d567d4e2c824d754223b3f3b0" + }, + { + "referencedResource": "TMP_Bitmap-Mobile.shader", + "target": "guid: d1cf17907700cb647aa3ea423ba38f2e", + "replacement": "guid: 1e3b057af24249748ff873be7fafee47" + }, + { + "referencedResource": "TMP_SDF.shader", + "target": "guid: dca26082f9cb439469295791d9f76fe5", + "replacement": "guid: 68e6db2ebdc24f95958faec2be5558d6" + }, + { + "referencedResource": "TMP_SDF Overlay.shader", + "target": "guid: 4a7755d6b5b67874f89c85f56f95fe97", + "replacement": "guid: dd89cf5b9246416f84610a006f916af7" + }, + { + "referencedResource": "TMP_SDF-Mobile.shader", + "target": "guid: cafd18099dfc0114896e0a8b277b81b6", + "replacement": "guid: fe393ace9b354375a9cb14cdbbc28be4" + }, + { + "referencedResource": "TMP_SDF-Mobile Masking.shader", + "target": "guid: afc255f7c2be52e41973a3d10a2e632d", + "replacement": "guid: bc1ede39bf3643ee8e493720e4259791" + }, + { + "referencedResource": "TMP_SDF-Mobile Overlay.shader", + "target": "guid: 9ecb3fe313cb5f7478141eba4a2d54ed", + "replacement": "guid: a02a7d8c237544f1962732b55a9aebf1" + }, + { + "referencedResource": "TMP_SDF-Surface.shader", + "target": "guid: 8e6b9842dbb1a5a4887378afab854e63", + "replacement": "guid: f7ada0af4f174f0694ca6a487b8f543d" + }, + { + "referencedResource": "TMP_SDF-Surface-Mobile.shader", + "target": "guid: 3c2ea7753c1425145a74d106ec1cd852", + "replacement": "guid: 85187c2149c549c5b33f0cdb02836b17" + }, + { + "referencedResource": "TMP_Sprite.shader", + "target": "guid: 3a1c68c8292caf046bd21158886c5e40", + "replacement": "guid: cf81c85f95fe47e1a27f6ae460cf182c" + }, + { + "referencedResource": "Default Sprite Asset.asset", + "target": "guid: 273ca6c80b4b5d746b5e548f532bffd8", + "replacement": "guid: fbef3c704dce48f08a44612d6c856c8d" + }, + { + "referencedResource": "EmojiOne.asset", + "target": "guid: 9a952e2781ef26940ae089f1053ef4ef", + "replacement": "guid: c41005c129ba4d66911b75229fd70b45" + }, + { + "referencedResource": "TMP Default Style Sheet.asset", + "target": "guid: 54d1085f9a2fdea4587fcfc7dddcd4bc", + "replacement": "guid: f952c082cb03451daed3ee968ac6c63e" + }, + { + "referencedResource": "TMP Settings.asset", + "target": "guid: 69ed5bac41eebaa4c97e9d2a4168c54f", + "replacement": "guid: 3f5b5dff67a942289a9defa416b206f3" + }, + { + "referencedResource": "TextContainer.cs", + "target": "guid: 3b34fc186f40e8043b977d4fa70db8c5", + "replacement": "guid: 32d40088a6124c578ad6b428df586e2e" + }, + { + "referencedResource": "TextContainer.cs", + "target": "fileID: 311004786, guid: 89f0137620f6af44b9ba852b4190e64e", + "replacement": "fileID: 11500000, guid: 32d40088a6124c578ad6b428df586e2e" + }, + { + "referencedResource": "TextMeshPro.cs", + "target": "guid: 1a1578b9753d2604f98d608cb4239e2f", + "replacement": "guid: 9541d86e2fd84c1d9990edf0852d74ab" + }, + { + "referencedResource": "TextMeshPro.cs", + "target": "fileID: -806885394, guid: 89f0137620f6af44b9ba852b4190e64e", + "replacement": "fileID: 11500000, guid: 9541d86e2fd84c1d9990edf0852d74ab" + }, + { + "referencedResource": "TextMeshProUGUI.cs", + "target": "guid: 496f2e385b0c62542b5c739ccfafd8da", + "replacement": "guid: f4688fdb7df04437aeb418b961361dc5" + }, + { + "referencedResource": "TextMeshProUGUI.cs", + "target": "fileID: 1453722849, guid: 89f0137620f6af44b9ba852b4190e64e", + "replacement": "fileID: 11500000, guid: f4688fdb7df04437aeb418b961361dc5" + }, + { + "referencedResource": "TMP_Asset.cs", + "target": "guid: e2c4405608b405a4680436e183e53c45", + "replacement": "guid: 3bda1886f58f4e0ab1139400b160c3ee" + }, + { + "referencedResource": "TMP_Asset.cs", + "target": "fileID: -659140726, guid: 89f0137620f6af44b9ba852b4190e64e", + "replacement": "fileID: 11500000, guid: 3bda1886f58f4e0ab1139400b160c3ee" + }, + { + "referencedResource": "TMP_ColorGradient.cs", + "target": "guid: e90e18dd4a044ff4394833216e6bf4d2", + "replacement": "guid: 54d21f6ece3b46479f0c328f8c6007e0" + }, + { + "referencedResource": "TMP_ColorGradient.cs", + "target": "fileID: 2108210716, guid: 89f0137620f6af44b9ba852b4190e64e", + "replacement": "fileID: 11500000, guid: 54d21f6ece3b46479f0c328f8c6007e0" + }, + { + "referencedResource": "TMP_Dropdown.cs", + "target": "guid: 44cb1d34ddab9d449a05fc3747876be1", + "replacement": "guid: 7b743370ac3e4ec2a1668f5455a8ef8a" + }, + { + "referencedResource": "TMP_Dropdown.cs", + "target": "fileID: 1148083418, guid: 89f0137620f6af44b9ba852b4190e64e", + "replacement": "fileID: 11500000, guid: 7b743370ac3e4ec2a1668f5455a8ef8a" + }, + { + "referencedResource": "TMP_FontAsset.cs", + "target": "guid: 74dfce233ddb29b4294c3e23c1d3650d", + "replacement": "guid: 71c1514a6bd24e1e882cebbe1904ce04" + }, + { + "referencedResource": "TMP_FontAsset.cs", + "target": "fileID: -667331979, guid: 89f0137620f6af44b9ba852b4190e64e", + "replacement": "fileID: 11500000, guid: 71c1514a6bd24e1e882cebbe1904ce04" + }, + { + "referencedResource": "TMP_InputField.cs", + "target": "guid: 7b85855a3deaa2e44ac6741a6bbc85f6", + "replacement": "guid: 2da0c512f12947e489f739169773d7ca" + }, + { + "referencedResource": "TMP_InputField.cs", + "target": "fileID: -1620774994, guid: 89f0137620f6af44b9ba852b4190e64e", + "replacement": "fileID: 11500000, guid: 2da0c512f12947e489f739169773d7ca" + }, + { + "referencedResource": "TMP_Settings.cs", + "target": "guid: aafc3c7b9e915d64e8ec3d2c88b3a231", + "replacement": "guid: 2705215ac5b84b70bacc50632be6e391" + }, + { + "referencedResource": "TMP_Settings.cs", + "target": "fileID: -395462249, guid: 89f0137620f6af44b9ba852b4190e64e", + "replacement": "fileID: 11500000, guid: 2705215ac5b84b70bacc50632be6e391" + }, + { + "referencedResource": "TMP_SpriteAsset.cs", + "target": "guid: 90940d439ca0ef746af0b48419b92d2e", + "replacement": "guid: 84a92b25f83d49b9bc132d206b370281" + }, + { + "referencedResource": "TMP_SpriteAsset.cs", + "target": "fileID: 2019389346, guid: 89f0137620f6af44b9ba852b4190e64e", + "replacement": "fileID: 11500000, guid: 84a92b25f83d49b9bc132d206b370281" + }, + { + "referencedResource": "TMP_StyleSheet.cs", + "target": "guid: 13259b4ce497b194eb52a33d8eda0bdc", + "replacement": "guid: ab2114bdc8544297b417dfefe9f1e410" + }, + { + "referencedResource": "TMP_StyleSheet.cs", + "target": "fileID: -1936749209, guid: 89f0137620f6af44b9ba852b4190e64e", + "replacement": "fileID: 11500000, guid: ab2114bdc8544297b417dfefe9f1e410" + }, + { + "referencedResource": "TMP_SubMesh.cs", + "target": "guid: bd950677b2d06c74494b1c1118584fff", + "replacement": "guid: 07994bfe8b0e4adb97d706de5dea48d5" + }, + { + "referencedResource": "TMP_SubMesh.cs", + "target": "fileID: 1330537494, guid: 89f0137620f6af44b9ba852b4190e64e", + "replacement": "fileID: 11500000, guid: 07994bfe8b0e4adb97d706de5dea48d5" + }, + { + "referencedResource": "TMP_SubMeshUI.cs", + "target": "guid: a5378e1f14d974d419f811d6b0861f20", + "replacement": "guid: 058cba836c1846c3aa1c5fd2e28aea77" + }, + { + "referencedResource": "TMP_SubMeshUI.cs", + "target": "fileID: 1908110080, guid: 89f0137620f6af44b9ba852b4190e64e", + "replacement": "fileID: 11500000, guid: 058cba836c1846c3aa1c5fd2e28aea77" + }, + { + "referencedResource": "TMP_Text.cs", + "target": "guid: 9ec8dc9c3fa2e5d41b939b5888d2f1e8", + "replacement": "guid: 5143f58107604835ab1a5efa2d8818fd" + }, + { + "referencedResource": "TMP_Text.cs", + "target": "fileID: -1385168320, guid: 89f0137620f6af44b9ba852b4190e64e", + "replacement": "fileID: 11500000, guid: 5143f58107604835ab1a5efa2d8818fd" + }, + { + "referencedResource": "Default Sprite Asset.png", + "target": "guid: 5b32c2d36abe44540bed74c1f787033b", + "replacement": "guid: a0fc465d6cf04254a2938578735e2383" + }, + { + "referencedResource": "EmojiOne.png", + "target": "guid: 6ec706981a919c3489f0b061a40054e2", + "replacement": "guid: dffef66376be4fa480fb02b19edbe903" + } + ] +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/PackageConversionData_Assets.json b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/PackageConversionData_Assets.json new file mode 100644 index 00000000..f07aa23f --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/PackageConversionData_Assets.json @@ -0,0 +1,184 @@ +{ + "assetRecords": [ + { + "referencedResource": "TMP_FontAsset.cs", + "target": "guid: 74dfce233ddb29b4294c3e23c1d3650d", + "replacement": "guid: 71c1514a6bd24e1e882cebbe1904ce04" + }, + { + "referencedResource": "TMP_FontAsset.cs", + "target": "fileID: -667331979, guid: 89f0137620f6af44b9ba852b4190e64e", + "replacement": "fileID: 11500000, guid: 71c1514a6bd24e1e882cebbe1904ce04" + }, + { + "referencedResource": "Anton SDF.asset", + "target": "guid: f76ef802b8b940c46a31f9027f2b0158", + "replacement": "guid: 8a89fa14b10d46a99122fd4f73fca9a2" + }, + { + "referencedResource": "Bangers SDF.asset", + "target": "guid: 808aa8f1ab804104aa7d0c337a6c1481", + "replacement": "guid: 125cb55b44b24c4393181402bc6200e6" + }, + { + "referencedResource": "Electronic Highway Sign SDF.asset", + "target": "guid: 163292f6f226d954593d45b079f8aae0", + "replacement": "guid: dc36b3fdc14f47ebb36fd484a67e268a" + }, + { + "referencedResource": "Oswald Bold SDF.asset", + "target": "guid: 09641b029dfa78843902b548a9de7553", + "replacement": "guid: 0161d805a3764c089bef00bfe00793f5" + }, + { + "referencedResource": "Roboto-Bold SDF.asset", + "target": "guid: d62a573c923f5cb47b8ff65261033b90", + "replacement": "guid: 5302535af1044152a457ed104f1f4b91" + }, + { + "referencedResource": "LiberationSans SDF.asset", + "target": "guid: 715b80e429c437e40867928a4e1fc975", + "replacement": "guid: 8f586378b4e144a9851e7b34d9b748ee" + }, + { + "referencedResource": "TMP_Bitmap.shader", + "target": "guid: edfcf888cd11d9245b91d2883049a57e", + "replacement": "guid: 128e987d567d4e2c824d754223b3f3b0" + }, + { + "referencedResource": "TMP_Bitmap-Mobile.shader", + "target": "guid: d1cf17907700cb647aa3ea423ba38f2e", + "replacement": "guid: 1e3b057af24249748ff873be7fafee47" + }, + { + "referencedResource": "TMP_SDF.shader", + "target": "guid: dca26082f9cb439469295791d9f76fe5", + "replacement": "guid: 68e6db2ebdc24f95958faec2be5558d6" + }, + { + "referencedResource": "TMP_SDF Overlay.shader", + "target": "guid: 4a7755d6b5b67874f89c85f56f95fe97", + "replacement": "guid: dd89cf5b9246416f84610a006f916af7" + }, + { + "referencedResource": "TMP_SDF-Mobile.shader", + "target": "guid: cafd18099dfc0114896e0a8b277b81b6", + "replacement": "guid: fe393ace9b354375a9cb14cdbbc28be4" + }, + { + "referencedResource": "TMP_SDF-Mobile Masking.shader", + "target": "guid: afc255f7c2be52e41973a3d10a2e632d", + "replacement": "guid: bc1ede39bf3643ee8e493720e4259791" + }, + { + "referencedResource": "TMP_SDF-Mobile Overlay.shader", + "target": "guid: 9ecb3fe313cb5f7478141eba4a2d54ed", + "replacement": "guid: a02a7d8c237544f1962732b55a9aebf1" + }, + { + "referencedResource": "TMP_SDF-Surface.shader", + "target": "guid: 8e6b9842dbb1a5a4887378afab854e63", + "replacement": "guid: f7ada0af4f174f0694ca6a487b8f543d" + }, + { + "referencedResource": "TMP_SDF-Surface-Mobile.shader", + "target": "guid: 3c2ea7753c1425145a74d106ec1cd852", + "replacement": "guid: 85187c2149c549c5b33f0cdb02836b17" + }, + { + "referencedResource": "TMP_Sprite.shader", + "target": "guid: 3a1c68c8292caf046bd21158886c5e40", + "replacement": "guid: cf81c85f95fe47e1a27f6ae460cf182c" + }, + { + "referencedResource": "TMP_ColorGradient.cs", + "target": "guid: e90e18dd4a044ff4394833216e6bf4d2", + "replacement": "guid: 54d21f6ece3b46479f0c328f8c6007e0" + }, + { + "referencedResource": "TMP_ColorGradient.cs", + "target": "fileID: 2108210716, guid: 89f0137620f6af44b9ba852b4190e64e", + "replacement": "fileID: 11500000, guid: 54d21f6ece3b46479f0c328f8c6007e0" + }, + { + "referencedResource": "TMP_Settings.cs", + "target": "guid: aafc3c7b9e915d64e8ec3d2c88b3a231", + "replacement": "guid: 2705215ac5b84b70bacc50632be6e391" + }, + { + "referencedResource": "TMP_Settings.cs", + "target": "fileID: -395462249, guid: 89f0137620f6af44b9ba852b4190e64e", + "replacement": "fileID: 11500000, guid: 2705215ac5b84b70bacc50632be6e391" + }, + { + "referencedResource": "TMP Settings.asset", + "target": "guid: 69ed5bac41eebaa4c97e9d2a4168c54f", + "replacement": "guid: 3f5b5dff67a942289a9defa416b206f3" + }, + { + "referencedResource": "LineBreaking Following Characters.txt", + "target": "guid: 312ba5b9e90627940866e19549a788cf", + "replacement": "guid: fade42e8bc714b018fac513c043d323b" + }, + { + "referencedResource": "LineBreaking Leading Characters.txt", + "target": "guid: 8d713940fcbede142ae4a33ea0062b33", + "replacement": "guid: d82c1b31c7e74239bff1220585707d2b" + }, + { + "referencedResource": "TMP_StyleSheet.cs", + "target": "guid: 13259b4ce497b194eb52a33d8eda0bdc", + "replacement": "guid: ab2114bdc8544297b417dfefe9f1e410" + }, + { + "referencedResource": "TMP_StyleSheet.cs", + "target": "fileID: -1936749209, guid: 89f0137620f6af44b9ba852b4190e64e", + "replacement": "fileID: 11500000, guid: ab2114bdc8544297b417dfefe9f1e410" + }, + { + "referencedResource": "TMP Default Style Sheet.asset", + "target": "guid: 54d1085f9a2fdea4587fcfc7dddcd4bc", + "replacement": "guid: f952c082cb03451daed3ee968ac6c63e" + }, + { + "referencedResource": "TMP_SpriteAsset.cs", + "target": "guid: 90940d439ca0ef746af0b48419b92d2e", + "replacement": "guid: 84a92b25f83d49b9bc132d206b370281" + }, + { + "referencedResource": "TMP_SpriteAsset.cs", + "target": "fileID: 2019389346, guid: 89f0137620f6af44b9ba852b4190e64e", + "replacement": "fileID: 11500000, guid: 84a92b25f83d49b9bc132d206b370281" + }, + { + "referencedResource": "Default Sprite Asset.asset", + "target": "guid: 273ca6c80b4b5d746b5e548f532bffd8", + "replacement": "guid: fbef3c704dce48f08a44612d6c856c8d" + }, + { + "referencedResource": "Default Sprite Asset.png", + "target": "guid: 5b32c2d36abe44540bed74c1f787033b", + "replacement": "guid: a0fc465d6cf04254a2938578735e2383" + }, + { + "referencedResource": "EmojiOne.asset", + "target": "guid: 9a952e2781ef26940ae089f1053ef4ef", + "replacement": "guid: c41005c129ba4d66911b75229fd70b45" + }, + { + "referencedResource": "EmojiOne.png", + "target": "guid: 6ec706981a919c3489f0b061a40054e2", + "replacement": "guid: dffef66376be4fa480fb02b19edbe903" + }, + { + "referencedResource": "DropCap Numbers.asset", + "target": "guid: c4fd2a959a50b584b92dedfefec1ffda", + "replacement": "guid: 14aa93acbb234d16aaef0e8b46814db6" + }, + { + "referencedResource": "DropCap Numbers.psd", + "target": "guid: 28b41fef228d6814f90e541deaf9f262", + "replacement": "guid: fd09957580ac4326916010f1f260975b" + } + ] +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/DropdownOptionListDrawer.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/DropdownOptionListDrawer.cs new file mode 100644 index 00000000..2b7dc854 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/DropdownOptionListDrawer.cs @@ -0,0 +1,60 @@ +using UnityEditorInternal; +using UnityEngine; +using UnityEngine.UI; +using UnityEditor; + +namespace TMPro.EditorUtilities +{ + [CustomPropertyDrawer(typeof(TMP_Dropdown.OptionDataList), true)] + class DropdownOptionListDrawer : PropertyDrawer + { + private ReorderableList m_ReorderableList; + + private void Init(SerializedProperty property) + { + if (m_ReorderableList != null) + return; + + SerializedProperty array = property.FindPropertyRelative("m_Options"); + + m_ReorderableList = new ReorderableList(property.serializedObject, array); + m_ReorderableList.drawElementCallback = DrawOptionData; + m_ReorderableList.drawHeaderCallback = DrawHeader; + m_ReorderableList.elementHeight += 16; + } + + public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) + { + Init(property); + + m_ReorderableList.DoList(position); + } + + private void DrawHeader(Rect rect) + { + GUI.Label(rect, "Options"); + } + + private void DrawOptionData(Rect rect, int index, bool isActive, bool isFocused) + { + SerializedProperty itemData = m_ReorderableList.serializedProperty.GetArrayElementAtIndex(index); + SerializedProperty itemText = itemData.FindPropertyRelative("m_Text"); + SerializedProperty itemImage = itemData.FindPropertyRelative("m_Image"); + + RectOffset offset = new RectOffset(0, 0, -1, -3); + rect = offset.Add(rect); + rect.height = EditorGUIUtility.singleLineHeight; + + EditorGUI.PropertyField(rect, itemText, GUIContent.none); + rect.y += EditorGUIUtility.singleLineHeight; + EditorGUI.PropertyField(rect, itemImage, GUIContent.none); + } + + public override float GetPropertyHeight(SerializedProperty property, GUIContent label) + { + Init(property); + + return m_ReorderableList.GetHeight(); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/GlyphInfoDrawer.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/GlyphInfoDrawer.cs new file mode 100644 index 00000000..0936dc75 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/GlyphInfoDrawer.cs @@ -0,0 +1,61 @@ +/* +using UnityEngine; +using UnityEditor; +using System.Collections; + + +namespace TMPro.EditorUtilities +{ + + [CustomPropertyDrawer(typeof(TMP_Glyph))] + public class GlyphInfoDrawer : PropertyDrawer + { + + public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) + { + SerializedProperty prop_id = property.FindPropertyRelative("id"); + SerializedProperty prop_x = property.FindPropertyRelative("x"); + SerializedProperty prop_y = property.FindPropertyRelative("y"); + SerializedProperty prop_width = property.FindPropertyRelative("width"); + SerializedProperty prop_height = property.FindPropertyRelative("height"); + SerializedProperty prop_xOffset = property.FindPropertyRelative("xOffset"); + SerializedProperty prop_yOffset = property.FindPropertyRelative("yOffset"); + SerializedProperty prop_xAdvance = property.FindPropertyRelative("xAdvance"); + SerializedProperty prop_scale = property.FindPropertyRelative("scale"); + + + // We get Rect since a valid position may not be provided by the caller. + Rect rect = GUILayoutUtility.GetRect(position.width, 48); + rect.y -= 15; + + //GUI.enabled = false; + EditorGUIUtility.labelWidth = 40f; + EditorGUIUtility.fieldWidth = 45f; + + bool prevGuiState = GUI.enabled; + GUI.enabled = true; + EditorGUI.LabelField(new Rect(rect.x + 5f, rect.y, 80f, 18), new GUIContent("Ascii: " + prop_id.intValue + ""), TMP_UIStyleManager.label); + EditorGUI.LabelField(new Rect(rect.x + 90f, rect.y, 80f, 18), new GUIContent("Hex: " + prop_id.intValue.ToString("X") + ""), TMP_UIStyleManager.label); + EditorGUI.LabelField(new Rect(rect.x + 170f, rect.y, 80, 18), "Char: [ " + (char)prop_id.intValue + " ]", TMP_UIStyleManager.label); + GUI.enabled = prevGuiState; + + EditorGUIUtility.labelWidth = 35f; + EditorGUIUtility.fieldWidth = 10f; + + float width = (rect.width - 5f) / 4; + EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 0, rect.y + 22, width - 5f, 18), prop_x, new GUIContent("X:")); + EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 1, rect.y + 22, width - 5f, 18), prop_y, new GUIContent("Y:")); + EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 2, rect.y + 22, width - 5f, 18), prop_width, new GUIContent("W:")); + EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 3, rect.y + 22, width - 5f, 18), prop_height, new GUIContent("H:")); + + //GUI.enabled = true; + EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 0, rect.y + 44, width - 5f, 18), prop_xOffset, new GUIContent("OX:")); + EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 1, rect.y + 44, width - 5f, 18), prop_yOffset, new GUIContent("OY:")); + //GUI.enabled = true; + EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 2, rect.y + 44, width - 5f, 18), prop_xAdvance, new GUIContent("ADV:")); + EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 3, rect.y + 44, width - 5f, 18), prop_scale, new GUIContent("SF:")); + } + + } +} +*/ \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/GlyphMetricsPropertyDrawer.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/GlyphMetricsPropertyDrawer.cs new file mode 100644 index 00000000..1e1f4d18 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/GlyphMetricsPropertyDrawer.cs @@ -0,0 +1,53 @@ +using UnityEngine; +using UnityEngine.TextCore; +using UnityEditor; +using System.Collections; + + +namespace TMPro.EditorUtilities +{ + + [CustomPropertyDrawer(typeof(GlyphMetrics))] + public class GlyphMetricsPropertyDrawer : PropertyDrawer + { + public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) + { + SerializedProperty prop_Width = property.FindPropertyRelative("m_Width"); + SerializedProperty prop_Height = property.FindPropertyRelative("m_Height"); + SerializedProperty prop_HoriBearingX = property.FindPropertyRelative("m_HorizontalBearingX"); + SerializedProperty prop_HoriBearingY = property.FindPropertyRelative("m_HorizontalBearingY"); + SerializedProperty prop_HoriAdvance = property.FindPropertyRelative("m_HorizontalAdvance"); + + // We get Rect since a valid position may not be provided by the caller. + Rect rect = new Rect(position.x, position.y, position.width, 49); + + EditorGUI.LabelField(rect, new GUIContent("Glyph Metrics")); + + EditorGUIUtility.labelWidth = 30f; + EditorGUIUtility.fieldWidth = 10f; + + //GUI.enabled = false; + float width = (rect.width - 75f) / 2; + EditorGUI.PropertyField(new Rect(rect.x + width * 0, rect.y + 20, width - 5f, 18), prop_Width, new GUIContent("W:")); + EditorGUI.PropertyField(new Rect(rect.x + width * 1, rect.y + 20, width - 5f, 18), prop_Height, new GUIContent("H:")); + + //GUI.enabled = true; + + width = (rect.width - 75f) / 3; + EditorGUI.BeginChangeCheck(); + EditorGUI.PropertyField(new Rect(rect.x + width * 0, rect.y + 40, width - 5f, 18), prop_HoriBearingX, new GUIContent("BX:")); + EditorGUI.PropertyField(new Rect(rect.x + width * 1, rect.y + 40, width - 5f, 18), prop_HoriBearingY, new GUIContent("BY:")); + EditorGUI.PropertyField(new Rect(rect.x + width * 2, rect.y + 40, width - 5f, 18), prop_HoriAdvance, new GUIContent("AD:")); + if (EditorGUI.EndChangeCheck()) + { + + } + } + + public override float GetPropertyHeight(SerializedProperty property, GUIContent label) + { + return 65f; + } + + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/GlyphRectPropertyDrawer.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/GlyphRectPropertyDrawer.cs new file mode 100644 index 00000000..87ecf0cc --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/GlyphRectPropertyDrawer.cs @@ -0,0 +1,44 @@ +using UnityEngine; +using UnityEngine.TextCore; +using UnityEditor; +using System.Collections; + + +namespace TMPro.EditorUtilities +{ + + [CustomPropertyDrawer(typeof(GlyphRect))] + public class GlyphRectPropertyDrawer : PropertyDrawer + { + public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) + { + //EditorGUI.BeginProperty(position, label, property); + + SerializedProperty prop_X = property.FindPropertyRelative("m_X"); + SerializedProperty prop_Y = property.FindPropertyRelative("m_Y"); + SerializedProperty prop_Width = property.FindPropertyRelative("m_Width"); + SerializedProperty prop_Height = property.FindPropertyRelative("m_Height"); + + // We get Rect since a valid position may not be provided by the caller. + Rect rect = new Rect(position.x, position.y, position.width, 49); + EditorGUI.LabelField(rect, new GUIContent("Glyph Rect")); + + EditorGUIUtility.labelWidth = 30f; + EditorGUIUtility.fieldWidth = 10f; + + //GUI.enabled = false; + float width = (rect.width - 75f) / 4; + EditorGUI.PropertyField(new Rect(rect.x + width * 0, rect.y + 20, width - 5f, 18), prop_X, new GUIContent("X:")); + EditorGUI.PropertyField(new Rect(rect.x + width * 1, rect.y + 20, width - 5f, 18), prop_Y, new GUIContent("Y:")); + EditorGUI.PropertyField(new Rect(rect.x + width * 2, rect.y + 20, width - 5f, 18), prop_Width, new GUIContent("W:")); + EditorGUI.PropertyField(new Rect(rect.x + width * 3, rect.y + 20, width - 5f, 18), prop_Height, new GUIContent("H:")); + + //EditorGUI.EndProperty(); + } + + public override float GetPropertyHeight(SerializedProperty property, GUIContent label) + { + return 45f; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_BaseEditorPanel.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_BaseEditorPanel.cs new file mode 100644 index 00000000..c4a55baf --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_BaseEditorPanel.cs @@ -0,0 +1,1116 @@ +using UnityEngine; +using UnityEditor; + +namespace TMPro.EditorUtilities +{ + public abstract class TMP_BaseEditorPanel : Editor + { + //Labels and Tooltips + static readonly GUIContent k_RtlToggleLabel = new GUIContent("Enable RTL Editor", "Reverses text direction and allows right to left editing."); + static readonly GUIContent k_MainSettingsLabel = new GUIContent("Main Settings"); + static readonly GUIContent k_FontAssetLabel = new GUIContent("Font Asset", "The Font Asset containing the glyphs that can be rendered for this text."); + static readonly GUIContent k_MaterialPresetLabel = new GUIContent("Material Preset", "The material used for rendering. Only materials created from the Font Asset can be used."); + static readonly GUIContent k_AutoSizeLabel = new GUIContent("Auto Size", "Auto sizes the text to fit the available space."); + static readonly GUIContent k_FontSizeLabel = new GUIContent("Font Size", "The size the text will be rendered at in points."); + static readonly GUIContent k_AutoSizeOptionsLabel = new GUIContent("Auto Size Options"); + static readonly GUIContent k_MinLabel = new GUIContent("Min", "The minimum font size."); + static readonly GUIContent k_MaxLabel = new GUIContent("Max", "The maximum font size."); + static readonly GUIContent k_WdLabel = new GUIContent("WD%", "Compresses character width up to this value before reducing font size."); + static readonly GUIContent k_LineLabel = new GUIContent("Line", "Negative value only. Compresses line height down to this value before reducing font size."); + static readonly GUIContent k_FontStyleLabel = new GUIContent("Font Style", "Styles to apply to the text such as Bold or Italic."); + + static readonly GUIContent k_BoldLabel = new GUIContent("B", "Bold"); + static readonly GUIContent k_ItalicLabel = new GUIContent("I", "Italic"); + static readonly GUIContent k_UnderlineLabel = new GUIContent("U", "Underline"); + static readonly GUIContent k_StrikethroughLabel = new GUIContent("S", "Strikethrough"); + static readonly GUIContent k_LowercaseLabel = new GUIContent("ab", "Lowercase"); + static readonly GUIContent k_UppercaseLabel = new GUIContent("AB", "Uppercase"); + static readonly GUIContent k_SmallcapsLabel = new GUIContent("SC", "Smallcaps"); + + static readonly GUIContent k_ColorModeLabel = new GUIContent("Color Mode", "The type of gradient to use."); + static readonly GUIContent k_BaseColorLabel = new GUIContent("Vertex Color", "The base color of the text vertices."); + static readonly GUIContent k_ColorPresetLabel = new GUIContent("Color Preset", "A Color Preset which override the local color settings."); + static readonly GUIContent k_ColorGradientLabel = new GUIContent("Color Gradient", "The gradient color applied over the Vertex Color. Can be locally set or driven by a Gradient Asset."); + static readonly GUIContent k_CorenerColorsLabel = new GUIContent("Colors", "The color composition of the gradient."); + static readonly GUIContent k_OverrideTagsLabel = new GUIContent("Override Tags", "Whether the color settings override the tag."); + + static readonly GUIContent k_SpacingOptionsLabel = new GUIContent("Spacing Options", "Spacing adjustments between different elements of the text."); + static readonly GUIContent k_CharacterSpacingLabel = new GUIContent("Character"); + static readonly GUIContent k_WordSpacingLabel = new GUIContent("Word"); + static readonly GUIContent k_LineSpacingLabel = new GUIContent("Line"); + static readonly GUIContent k_ParagraphSpacingLabel = new GUIContent("Paragraph"); + + static readonly GUIContent k_AlignmentLabel = new GUIContent("Alignment", "Horizontal and vertical aligment of the text within its container."); + static readonly GUIContent k_WrapMixLabel = new GUIContent("Wrap Mix (W <-> C)", "How much to favor words versus characters when distributing the text."); + + static readonly GUIContent k_WrappingLabel = new GUIContent("Wrapping", "Wraps text to the next line when reaching the edge of the container."); + static readonly GUIContent[] k_WrappingOptions = { new GUIContent("Disabled"), new GUIContent("Enabled") }; + static readonly GUIContent k_OverflowLabel = new GUIContent("Overflow", "How to display text which goes past the edge of the container."); + + static readonly GUIContent k_MarginsLabel = new GUIContent("Margins", "The space between the text and the edge of its container."); + static readonly GUIContent k_GeometrySortingLabel = new GUIContent("Geometry Sorting", "The order in which text geometry is sorted. Used to adjust the way overlapping characters are displayed."); + static readonly GUIContent k_RichTextLabel = new GUIContent("Rich Text", "Enables the use of rich text tags such as and ."); + static readonly GUIContent k_EscapeCharactersLabel = new GUIContent("Parse Escape Characters", "Whether to display strings such as \"\\n\" as is or replace them by the character they represent."); + static readonly GUIContent k_VisibleDescenderLabel = new GUIContent("Visible Descender", "Compute descender values from visible characters only. Used to adjust layout behavior when hiding and revealing characters dynamically."); + static readonly GUIContent k_SpriteAssetLabel = new GUIContent("Sprite Asset", "The Sprite Asset used when NOT specifically referencing one using ."); + + static readonly GUIContent k_HorizontalMappingLabel = new GUIContent("Horizontal Mapping", "Horizontal UV mapping when using a shader with a texture face option."); + static readonly GUIContent k_VerticalMappingLabel = new GUIContent("Vertical Mapping", "Vertical UV mapping when using a shader with a texture face option."); + static readonly GUIContent k_LineOffsetLabel = new GUIContent("Line Offset", "Adds an horizontal offset to each successive line. Used for slanted texturing."); + + static readonly GUIContent k_KerningLabel = new GUIContent("Kerning", "Enables character specific spacing between pairs of characters."); + static readonly GUIContent k_PaddingLabel = new GUIContent("Extra Padding", "Adds some padding between the characters and the edge of the text mesh. Can reduce graphical errors when displaying small text."); + + static readonly GUIContent k_LeftLabel = new GUIContent("Left"); + static readonly GUIContent k_TopLabel = new GUIContent("Top"); + static readonly GUIContent k_RightLabel = new GUIContent("Right"); + static readonly GUIContent k_BottomLabel = new GUIContent("Bottom"); + + protected static readonly GUIContent k_ExtraSettingsLabel = new GUIContent("Extra Settings"); + + protected struct Foldout + { + // Track Inspector foldout panel states, globally. + public static bool extraSettings = false; + public static bool materialInspector = true; + } + + protected static int s_EventId; + + public int selAlignGridA; + public int selAlignGridB; + + protected SerializedProperty m_TextProp; + + protected SerializedProperty m_IsRightToLeftProp; + protected string m_RtlText; + + protected SerializedProperty m_FontAssetProp; + + protected SerializedProperty m_FontSharedMaterialProp; + protected Material[] m_MaterialPresets; + protected GUIContent[] m_MaterialPresetNames; + protected int m_MaterialPresetSelectionIndex; + protected bool m_IsPresetListDirty; + + protected SerializedProperty m_FontStyleProp; + + protected SerializedProperty m_FontColorProp; + protected SerializedProperty m_EnableVertexGradientProp; + protected SerializedProperty m_FontColorGradientProp; + protected SerializedProperty m_FontColorGradientPresetProp; + protected SerializedProperty m_OverrideHtmlColorProp; + + protected SerializedProperty m_FontSizeProp; + protected SerializedProperty m_FontSizeBaseProp; + + protected SerializedProperty m_AutoSizingProp; + protected SerializedProperty m_FontSizeMinProp; + protected SerializedProperty m_FontSizeMaxProp; + + protected SerializedProperty m_LineSpacingMaxProp; + protected SerializedProperty m_CharWidthMaxAdjProp; + + protected SerializedProperty m_CharacterSpacingProp; + protected SerializedProperty m_WordSpacingProp; + protected SerializedProperty m_LineSpacingProp; + protected SerializedProperty m_ParagraphSpacingProp; + + protected SerializedProperty m_TextAlignmentProp; + + protected SerializedProperty m_HorizontalMappingProp; + protected SerializedProperty m_VerticalMappingProp; + protected SerializedProperty m_UvLineOffsetProp; + + protected SerializedProperty m_EnableWordWrappingProp; + protected SerializedProperty m_WordWrappingRatiosProp; + protected SerializedProperty m_TextOverflowModeProp; + protected SerializedProperty m_PageToDisplayProp; + protected SerializedProperty m_LinkedTextComponentProp; + protected SerializedProperty m_IsLinkedTextComponentProp; + + protected SerializedProperty m_EnableKerningProp; + + protected SerializedProperty m_IsRichTextProp; + + protected SerializedProperty m_HasFontAssetChangedProp; + + protected SerializedProperty m_EnableExtraPaddingProp; + protected SerializedProperty m_CheckPaddingRequiredProp; + protected SerializedProperty m_EnableEscapeCharacterParsingProp; + protected SerializedProperty m_UseMaxVisibleDescenderProp; + protected SerializedProperty m_GeometrySortingOrderProp; + + protected SerializedProperty m_SpriteAssetProp; + + protected SerializedProperty m_MarginProp; + + protected SerializedProperty m_ColorModeProp; + + protected bool m_HavePropertiesChanged; + + protected TMP_Text m_TextComponent; + protected RectTransform m_RectTransform; + + protected Material m_TargetMaterial; + + protected Vector3[] m_RectCorners = new Vector3[4]; + protected Vector3[] m_HandlePoints = new Vector3[4]; + + protected virtual void OnEnable() + { + m_TextProp = serializedObject.FindProperty("m_text"); + m_IsRightToLeftProp = serializedObject.FindProperty("m_isRightToLeft"); + m_FontAssetProp = serializedObject.FindProperty("m_fontAsset"); + m_FontSharedMaterialProp = serializedObject.FindProperty("m_sharedMaterial"); + + m_FontStyleProp = serializedObject.FindProperty("m_fontStyle"); + + m_FontSizeProp = serializedObject.FindProperty("m_fontSize"); + m_FontSizeBaseProp = serializedObject.FindProperty("m_fontSizeBase"); + + m_AutoSizingProp = serializedObject.FindProperty("m_enableAutoSizing"); + m_FontSizeMinProp = serializedObject.FindProperty("m_fontSizeMin"); + m_FontSizeMaxProp = serializedObject.FindProperty("m_fontSizeMax"); + + m_LineSpacingMaxProp = serializedObject.FindProperty("m_lineSpacingMax"); + m_CharWidthMaxAdjProp = serializedObject.FindProperty("m_charWidthMaxAdj"); + + // Colors & Gradient + m_FontColorProp = serializedObject.FindProperty("m_fontColor"); + m_EnableVertexGradientProp = serializedObject.FindProperty("m_enableVertexGradient"); + m_FontColorGradientProp = serializedObject.FindProperty("m_fontColorGradient"); + m_FontColorGradientPresetProp = serializedObject.FindProperty("m_fontColorGradientPreset"); + m_OverrideHtmlColorProp = serializedObject.FindProperty("m_overrideHtmlColors"); + + m_CharacterSpacingProp = serializedObject.FindProperty("m_characterSpacing"); + m_WordSpacingProp = serializedObject.FindProperty("m_wordSpacing"); + m_LineSpacingProp = serializedObject.FindProperty("m_lineSpacing"); + m_ParagraphSpacingProp = serializedObject.FindProperty("m_paragraphSpacing"); + + m_TextAlignmentProp = serializedObject.FindProperty("m_textAlignment"); + + m_HorizontalMappingProp = serializedObject.FindProperty("m_horizontalMapping"); + m_VerticalMappingProp = serializedObject.FindProperty("m_verticalMapping"); + m_UvLineOffsetProp = serializedObject.FindProperty("m_uvLineOffset"); + + m_EnableWordWrappingProp = serializedObject.FindProperty("m_enableWordWrapping"); + m_WordWrappingRatiosProp = serializedObject.FindProperty("m_wordWrappingRatios"); + m_TextOverflowModeProp = serializedObject.FindProperty("m_overflowMode"); + m_PageToDisplayProp = serializedObject.FindProperty("m_pageToDisplay"); + m_LinkedTextComponentProp = serializedObject.FindProperty("m_linkedTextComponent"); + m_IsLinkedTextComponentProp = serializedObject.FindProperty("m_isLinkedTextComponent"); + + m_EnableKerningProp = serializedObject.FindProperty("m_enableKerning"); + + m_EnableExtraPaddingProp = serializedObject.FindProperty("m_enableExtraPadding"); + m_IsRichTextProp = serializedObject.FindProperty("m_isRichText"); + m_CheckPaddingRequiredProp = serializedObject.FindProperty("checkPaddingRequired"); + m_EnableEscapeCharacterParsingProp = serializedObject.FindProperty("m_parseCtrlCharacters"); + m_UseMaxVisibleDescenderProp = serializedObject.FindProperty("m_useMaxVisibleDescender"); + + m_GeometrySortingOrderProp = serializedObject.FindProperty("m_geometrySortingOrder"); + + m_SpriteAssetProp = serializedObject.FindProperty("m_spriteAsset"); + + m_MarginProp = serializedObject.FindProperty("m_margin"); + + m_HasFontAssetChangedProp = serializedObject.FindProperty("m_hasFontAssetChanged"); + + m_ColorModeProp = serializedObject.FindProperty("m_colorMode"); + + m_TextComponent = (TMP_Text)target; + m_RectTransform = m_TextComponent.rectTransform; + + // Create new Material Editor if one does not exists + m_TargetMaterial = m_TextComponent.fontSharedMaterial; + + // Set material inspector visibility + if (m_TargetMaterial != null) + UnityEditorInternal.InternalEditorUtility.SetIsInspectorExpanded(m_TargetMaterial, Foldout.materialInspector); + + // Find all Material Presets matching the current Font Asset Material + m_MaterialPresetNames = GetMaterialPresets(); + + // Initialize the Event Listener for Undo Events. + Undo.undoRedoPerformed += OnUndoRedo; + } + + protected virtual void OnDisable() + { + // Set material inspector visibility + if (m_TargetMaterial != null) + Foldout.materialInspector = UnityEditorInternal.InternalEditorUtility.GetIsInspectorExpanded(m_TargetMaterial); + + if (Undo.undoRedoPerformed != null) + Undo.undoRedoPerformed -= OnUndoRedo; + } + + public override void OnInspectorGUI() + { + // Make sure Multi selection only includes TMP Text objects. + if (IsMixSelectionTypes()) return; + + serializedObject.Update(); + + DrawTextInput(); + + DrawMainSettings(); + + DrawExtraSettings(); + + EditorGUILayout.Space(); + + if (m_HavePropertiesChanged) + { + m_HavePropertiesChanged = false; + m_TextComponent.havePropertiesChanged = true; + m_TextComponent.ComputeMarginSize(); + EditorUtility.SetDirty(target); + } + + serializedObject.ApplyModifiedProperties(); + } + + public void OnSceneGUI() + { + if (IsMixSelectionTypes()) return; + + // Margin Frame & Handles + m_RectTransform.GetWorldCorners(m_RectCorners); + Vector4 marginOffset = m_TextComponent.margin; + Vector3 lossyScale = m_RectTransform.lossyScale; + + m_HandlePoints[0] = m_RectCorners[0] + m_RectTransform.TransformDirection(new Vector3(marginOffset.x * lossyScale.x, marginOffset.w * lossyScale.y, 0)); + m_HandlePoints[1] = m_RectCorners[1] + m_RectTransform.TransformDirection(new Vector3(marginOffset.x * lossyScale.x, -marginOffset.y * lossyScale.y, 0)); + m_HandlePoints[2] = m_RectCorners[2] + m_RectTransform.TransformDirection(new Vector3(-marginOffset.z * lossyScale.x, -marginOffset.y * lossyScale.y, 0)); + m_HandlePoints[3] = m_RectCorners[3] + m_RectTransform.TransformDirection(new Vector3(-marginOffset.z * lossyScale.x, marginOffset.w * lossyScale.y, 0)); + + Handles.DrawSolidRectangleWithOutline(m_HandlePoints, new Color32(255, 255, 255, 0), new Color32(255, 255, 0, 255)); + + // Draw & process FreeMoveHandles + + // LEFT HANDLE + Vector3 oldLeft = (m_HandlePoints[0] + m_HandlePoints[1]) * 0.5f; + Vector3 newLeft = Handles.FreeMoveHandle(oldLeft, Quaternion.identity, HandleUtility.GetHandleSize(m_RectTransform.position) * 0.05f, Vector3.zero, Handles.DotHandleCap); + bool hasChanged = false; + if (oldLeft != newLeft) + { + float delta = oldLeft.x - newLeft.x; + marginOffset.x += -delta / lossyScale.x; + //Debug.Log("Left Margin H0:" + handlePoints[0] + " H1:" + handlePoints[1]); + hasChanged = true; + } + + // TOP HANDLE + Vector3 oldTop = (m_HandlePoints[1] + m_HandlePoints[2]) * 0.5f; + Vector3 newTop = Handles.FreeMoveHandle(oldTop, Quaternion.identity, HandleUtility.GetHandleSize(m_RectTransform.position) * 0.05f, Vector3.zero, Handles.DotHandleCap); + if (oldTop != newTop) + { + float delta = oldTop.y - newTop.y; + marginOffset.y += delta / lossyScale.y; + //Debug.Log("Top Margin H1:" + handlePoints[1] + " H2:" + handlePoints[2]); + hasChanged = true; + } + + // RIGHT HANDLE + Vector3 oldRight = (m_HandlePoints[2] + m_HandlePoints[3]) * 0.5f; + Vector3 newRight = Handles.FreeMoveHandle(oldRight, Quaternion.identity, HandleUtility.GetHandleSize(m_RectTransform.position) * 0.05f, Vector3.zero, Handles.DotHandleCap); + if (oldRight != newRight) + { + float delta = oldRight.x - newRight.x; + marginOffset.z += delta / lossyScale.x; + hasChanged = true; + //Debug.Log("Right Margin H2:" + handlePoints[2] + " H3:" + handlePoints[3]); + } + + // BOTTOM HANDLE + Vector3 oldBottom = (m_HandlePoints[3] + m_HandlePoints[0]) * 0.5f; + Vector3 newBottom = Handles.FreeMoveHandle(oldBottom, Quaternion.identity, HandleUtility.GetHandleSize(m_RectTransform.position) * 0.05f, Vector3.zero, Handles.DotHandleCap); + if (oldBottom != newBottom) + { + float delta = oldBottom.y - newBottom.y; + marginOffset.w += -delta / lossyScale.y; + hasChanged = true; + //Debug.Log("Bottom Margin H0:" + handlePoints[0] + " H3:" + handlePoints[3]); + } + + if (hasChanged) + { + Undo.RecordObjects(new Object[] {m_RectTransform, m_TextComponent }, "Margin Changes"); + m_TextComponent.margin = marginOffset; + EditorUtility.SetDirty(target); + } + } + + protected void DrawTextInput() + { + EditorGUILayout.Space(); + + // If the text component is linked, disable the text input box. + if (m_IsLinkedTextComponentProp.boolValue) + { + EditorGUILayout.HelpBox("The Text Input Box is disabled due to this text component being linked to another.", MessageType.Info); + } + else + { + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(m_TextProp); + + if (EditorGUI.EndChangeCheck() || (m_IsRightToLeftProp.boolValue && string.IsNullOrEmpty(m_RtlText))) + { + m_TextComponent.m_inputSource = TMP_Text.TextInputSources.Text; + m_TextComponent.m_isInputParsingRequired = true; + m_HavePropertiesChanged = true; + + // Handle Left to Right or Right to Left Editor + if (m_IsRightToLeftProp.boolValue) + { + m_RtlText = string.Empty; + string sourceText = m_TextProp.stringValue; + + // Reverse Text displayed in Text Input Box + for (int i = 0; i < sourceText.Length; i++) + { + m_RtlText += sourceText[sourceText.Length - i - 1]; + } + } + } + + // Toggle showing Rich Tags + m_IsRightToLeftProp.boolValue = EditorGUILayout.Toggle(k_RtlToggleLabel, m_IsRightToLeftProp.boolValue); + + if (m_IsRightToLeftProp.boolValue) + { + EditorGUI.BeginChangeCheck(); + m_RtlText = EditorGUILayout.TextArea(m_RtlText, TMP_UIStyleManager.wrappingTextArea, GUILayout.Height(EditorGUI.GetPropertyHeight(m_TextProp) - EditorGUIUtility.singleLineHeight), GUILayout.ExpandWidth(true)); + if (EditorGUI.EndChangeCheck()) + { + // Convert RTL input + string sourceText = string.Empty; + + // Reverse Text displayed in Text Input Box + for (int i = 0; i < m_RtlText.Length; i++) + { + sourceText += m_RtlText[m_RtlText.Length - i - 1]; + } + + m_TextProp.stringValue = sourceText; + } + } + } + } + + protected void DrawMainSettings() + { + // MAIN SETTINGS SECTION + GUILayout.Label(k_MainSettingsLabel, EditorStyles.boldLabel); + + EditorGUI.indentLevel += 1; + + DrawFont(); + + DrawColor(); + + DrawSpacing(); + + DrawAlignment(); + + DrawWrappingOverflow(); + + DrawTextureMapping(); + + EditorGUI.indentLevel -= 1; + } + + void DrawFont() + { + // Update list of material presets if needed. + if (m_IsPresetListDirty) + m_MaterialPresetNames = GetMaterialPresets(); + + // FONT ASSET + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(m_FontAssetProp, k_FontAssetLabel); + if (EditorGUI.EndChangeCheck()) + { + m_HavePropertiesChanged = true; + m_HasFontAssetChangedProp.boolValue = true; + + m_IsPresetListDirty = true; + m_MaterialPresetSelectionIndex = 0; + } + + Rect rect; + + // MATERIAL PRESET + if (m_MaterialPresetNames != null) + { + EditorGUI.BeginChangeCheck(); + rect = EditorGUILayout.GetControlRect(false, 17); + + float oldHeight = EditorStyles.popup.fixedHeight; + EditorStyles.popup.fixedHeight = rect.height; + + int oldSize = EditorStyles.popup.fontSize; + EditorStyles.popup.fontSize = 11; + + m_MaterialPresetSelectionIndex = EditorGUI.Popup(rect, k_MaterialPresetLabel, m_MaterialPresetSelectionIndex, m_MaterialPresetNames); + if (EditorGUI.EndChangeCheck()) + { + m_FontSharedMaterialProp.objectReferenceValue = m_MaterialPresets[m_MaterialPresetSelectionIndex]; + m_HavePropertiesChanged = true; + } + + //Make sure material preset selection index matches the selection + if (m_MaterialPresetSelectionIndex < m_MaterialPresetNames.Length && m_TargetMaterial != m_MaterialPresets[m_MaterialPresetSelectionIndex] && !m_HavePropertiesChanged) + m_IsPresetListDirty = true; + + EditorStyles.popup.fixedHeight = oldHeight; + EditorStyles.popup.fontSize = oldSize; + } + + // FONT STYLE + EditorGUI.BeginChangeCheck(); + + int v1, v2, v3, v4, v5, v6, v7; + + if (EditorGUIUtility.wideMode) + { + rect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight + 2f); + + EditorGUI.PrefixLabel(rect, k_FontStyleLabel); + + int styleValue = m_FontStyleProp.intValue; + + rect.x += EditorGUIUtility.labelWidth; + rect.width -= EditorGUIUtility.labelWidth; + + rect.width = Mathf.Max(25f, rect.width / 7f); + + v1 = TMP_EditorUtility.EditorToggle(rect, (styleValue & 1) == 1, k_BoldLabel, TMP_UIStyleManager.alignmentButtonLeft) ? 1 : 0; // Bold + rect.x += rect.width; + v2 = TMP_EditorUtility.EditorToggle(rect, (styleValue & 2) == 2, k_ItalicLabel, TMP_UIStyleManager.alignmentButtonMid) ? 2 : 0; // Italics + rect.x += rect.width; + v3 = TMP_EditorUtility.EditorToggle(rect, (styleValue & 4) == 4, k_UnderlineLabel, TMP_UIStyleManager.alignmentButtonMid) ? 4 : 0; // Underline + rect.x += rect.width; + v7 = TMP_EditorUtility.EditorToggle(rect, (styleValue & 64) == 64, k_StrikethroughLabel, TMP_UIStyleManager.alignmentButtonRight) ? 64 : 0; // Strikethrough + rect.x += rect.width; + + int selected = 0; + + EditorGUI.BeginChangeCheck(); + v4 = TMP_EditorUtility.EditorToggle(rect, (styleValue & 8) == 8, k_LowercaseLabel, TMP_UIStyleManager.alignmentButtonLeft) ? 8 : 0; // Lowercase + if (EditorGUI.EndChangeCheck() && v4 > 0) + { + selected = v4; + } + rect.x += rect.width; + EditorGUI.BeginChangeCheck(); + v5 = TMP_EditorUtility.EditorToggle(rect, (styleValue & 16) == 16, k_UppercaseLabel, TMP_UIStyleManager.alignmentButtonMid) ? 16 : 0; // Uppercase + if (EditorGUI.EndChangeCheck() && v5 > 0) + { + selected = v5; + } + rect.x += rect.width; + EditorGUI.BeginChangeCheck(); + v6 = TMP_EditorUtility.EditorToggle(rect, (styleValue & 32) == 32, k_SmallcapsLabel, TMP_UIStyleManager.alignmentButtonRight) ? 32 : 0; // Smallcaps + if (EditorGUI.EndChangeCheck() && v6 > 0) + { + selected = v6; + } + + if (selected > 0) + { + v4 = selected == 8 ? 8 : 0; + v5 = selected == 16 ? 16 : 0; + v6 = selected == 32 ? 32 : 0; + } + } + else + { + rect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight + 2f); + + EditorGUI.PrefixLabel(rect, k_FontStyleLabel); + + int styleValue = m_FontStyleProp.intValue; + + rect.x += EditorGUIUtility.labelWidth; + rect.width -= EditorGUIUtility.labelWidth; + rect.width = Mathf.Max(25f, rect.width / 4f); + + v1 = TMP_EditorUtility.EditorToggle(rect, (styleValue & 1) == 1, k_BoldLabel, TMP_UIStyleManager.alignmentButtonLeft) ? 1 : 0; // Bold + rect.x += rect.width; + v2 = TMP_EditorUtility.EditorToggle(rect, (styleValue & 2) == 2, k_ItalicLabel, TMP_UIStyleManager.alignmentButtonMid) ? 2 : 0; // Italics + rect.x += rect.width; + v3 = TMP_EditorUtility.EditorToggle(rect, (styleValue & 4) == 4, k_UnderlineLabel, TMP_UIStyleManager.alignmentButtonMid) ? 4 : 0; // Underline + rect.x += rect.width; + v7 = TMP_EditorUtility.EditorToggle(rect, (styleValue & 64) == 64, k_StrikethroughLabel, TMP_UIStyleManager.alignmentButtonRight) ? 64 : 0; // Strikethrough + + rect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight + 2f); + + rect.x += EditorGUIUtility.labelWidth; + rect.width -= EditorGUIUtility.labelWidth; + + rect.width = Mathf.Max(25f, rect.width / 4f); + + int selected = 0; + + EditorGUI.BeginChangeCheck(); + v4 = TMP_EditorUtility.EditorToggle(rect, (styleValue & 8) == 8, k_LowercaseLabel, TMP_UIStyleManager.alignmentButtonLeft) ? 8 : 0; // Lowercase + if (EditorGUI.EndChangeCheck() && v4 > 0) + { + selected = v4; + } + rect.x += rect.width; + EditorGUI.BeginChangeCheck(); + v5 = TMP_EditorUtility.EditorToggle(rect, (styleValue & 16) == 16, k_UppercaseLabel, TMP_UIStyleManager.alignmentButtonMid) ? 16 : 0; // Uppercase + if (EditorGUI.EndChangeCheck() && v5 > 0) + { + selected = v5; + } + rect.x += rect.width; + EditorGUI.BeginChangeCheck(); + v6 = TMP_EditorUtility.EditorToggle(rect, (styleValue & 32) == 32, k_SmallcapsLabel, TMP_UIStyleManager.alignmentButtonRight) ? 32 : 0; // Smallcaps + if (EditorGUI.EndChangeCheck() && v6 > 0) + { + selected = v6; + } + + if (selected > 0) + { + v4 = selected == 8 ? 8 : 0; + v5 = selected == 16 ? 16 : 0; + v6 = selected == 32 ? 32 : 0; + } + } + + if (EditorGUI.EndChangeCheck()) + { + m_FontStyleProp.intValue = v1 + v2 + v3 + v4 + v5 + v6 + v7; + m_HavePropertiesChanged = true; + } + + // FONT SIZE + EditorGUI.BeginChangeCheck(); + + EditorGUI.BeginDisabledGroup(m_AutoSizingProp.boolValue); + EditorGUILayout.PropertyField(m_FontSizeProp, k_FontSizeLabel, GUILayout.MaxWidth(EditorGUIUtility.labelWidth + 50f)); + EditorGUI.EndDisabledGroup(); + + if (EditorGUI.EndChangeCheck()) + { + m_FontSizeBaseProp.floatValue = m_FontSizeProp.floatValue; + m_HavePropertiesChanged = true; + } + + EditorGUI.indentLevel += 1; + + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(m_AutoSizingProp, k_AutoSizeLabel); + if (EditorGUI.EndChangeCheck()) + { + if (m_AutoSizingProp.boolValue == false) + m_FontSizeProp.floatValue = m_FontSizeBaseProp.floatValue; + + m_HavePropertiesChanged = true; + } + + // Show auto sizing options + if (m_AutoSizingProp.boolValue) + { + rect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight); + + EditorGUI.PrefixLabel(rect, k_AutoSizeOptionsLabel); + + int previousIndent = EditorGUI.indentLevel; + + EditorGUI.indentLevel = 0; + + rect.width = (rect.width - EditorGUIUtility.labelWidth) / 4f; + rect.x += EditorGUIUtility.labelWidth; + + EditorGUIUtility.labelWidth = 24; + EditorGUI.BeginChangeCheck(); + EditorGUI.PropertyField(rect, m_FontSizeMinProp, k_MinLabel); + if (EditorGUI.EndChangeCheck()) + { + m_FontSizeMinProp.floatValue = Mathf.Min(m_FontSizeMinProp.floatValue, m_FontSizeMaxProp.floatValue); + m_HavePropertiesChanged = true; + } + rect.x += rect.width; + + EditorGUIUtility.labelWidth = 27; + EditorGUI.BeginChangeCheck(); + EditorGUI.PropertyField(rect, m_FontSizeMaxProp, k_MaxLabel); + if (EditorGUI.EndChangeCheck()) + { + m_FontSizeMaxProp.floatValue = Mathf.Max(m_FontSizeMinProp.floatValue, m_FontSizeMaxProp.floatValue); + m_HavePropertiesChanged = true; + } + rect.x += rect.width; + + EditorGUI.BeginChangeCheck(); + EditorGUIUtility.labelWidth = 36; + EditorGUI.PropertyField(rect, m_CharWidthMaxAdjProp, k_WdLabel); + rect.x += rect.width; + EditorGUIUtility.labelWidth = 28; + EditorGUI.PropertyField(rect, m_LineSpacingMaxProp, k_LineLabel); + + EditorGUIUtility.labelWidth = 0; + + if (EditorGUI.EndChangeCheck()) + { + m_CharWidthMaxAdjProp.floatValue = Mathf.Clamp(m_CharWidthMaxAdjProp.floatValue, 0, 50); + m_LineSpacingMaxProp.floatValue = Mathf.Min(0, m_LineSpacingMaxProp.floatValue); + m_HavePropertiesChanged = true; + } + + EditorGUI.indentLevel = previousIndent; + } + + EditorGUI.indentLevel -= 1; + + + + EditorGUILayout.Space(); + } + + void DrawColor() + { + // FACE VERTEX COLOR + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(m_FontColorProp, k_BaseColorLabel); + + EditorGUILayout.PropertyField(m_EnableVertexGradientProp, k_ColorGradientLabel); + if (EditorGUI.EndChangeCheck()) + { + m_HavePropertiesChanged = true; + } + + EditorGUIUtility.fieldWidth = 0; + + if (m_EnableVertexGradientProp.boolValue) + { + EditorGUI.indentLevel += 1; + + EditorGUI.BeginChangeCheck(); + + EditorGUILayout.PropertyField(m_FontColorGradientPresetProp, k_ColorPresetLabel); + + SerializedObject obj = null; + + SerializedProperty colorMode; + + SerializedProperty topLeft; + SerializedProperty topRight; + SerializedProperty bottomLeft; + SerializedProperty bottomRight; + + if (m_FontColorGradientPresetProp.objectReferenceValue == null) + { + colorMode = m_ColorModeProp; + topLeft = m_FontColorGradientProp.FindPropertyRelative("topLeft"); + topRight = m_FontColorGradientProp.FindPropertyRelative("topRight"); + bottomLeft = m_FontColorGradientProp.FindPropertyRelative("bottomLeft"); + bottomRight = m_FontColorGradientProp.FindPropertyRelative("bottomRight"); + } + else + { + obj = new SerializedObject(m_FontColorGradientPresetProp.objectReferenceValue); + colorMode = obj.FindProperty("colorMode"); + topLeft = obj.FindProperty("topLeft"); + topRight = obj.FindProperty("topRight"); + bottomLeft = obj.FindProperty("bottomLeft"); + bottomRight = obj.FindProperty("bottomRight"); + } + + EditorGUILayout.PropertyField(colorMode, k_ColorModeLabel); + + var rect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight * (EditorGUIUtility.wideMode ? 1 : 2)); + + EditorGUI.PrefixLabel(rect, k_CorenerColorsLabel); + + rect.x += EditorGUIUtility.labelWidth; + rect.width = rect.width - EditorGUIUtility.labelWidth; + + switch ((ColorMode)colorMode.enumValueIndex) + { + case ColorMode.Single: + TMP_EditorUtility.DrawColorProperty(rect, topLeft); + + topRight.colorValue = topLeft.colorValue; + bottomLeft.colorValue = topLeft.colorValue; + bottomRight.colorValue = topLeft.colorValue; + break; + case ColorMode.HorizontalGradient: + rect.width /= 2f; + + TMP_EditorUtility.DrawColorProperty(rect, topLeft); + + rect.x += rect.width; + + TMP_EditorUtility.DrawColorProperty(rect, topRight); + + bottomLeft.colorValue = topLeft.colorValue; + bottomRight.colorValue = topRight.colorValue; + break; + case ColorMode.VerticalGradient: + TMP_EditorUtility.DrawColorProperty(rect, topLeft); + + rect = EditorGUILayout.GetControlRect(false, EditorGUIUtility.singleLineHeight * (EditorGUIUtility.wideMode ? 1 : 2)); + rect.x += EditorGUIUtility.labelWidth; + + TMP_EditorUtility.DrawColorProperty(rect, bottomLeft); + + topRight.colorValue = topLeft.colorValue; + bottomRight.colorValue = bottomLeft.colorValue; + break; + case ColorMode.FourCornersGradient: + rect.width /= 2f; + + TMP_EditorUtility.DrawColorProperty(rect, topLeft); + + rect.x += rect.width; + + TMP_EditorUtility.DrawColorProperty(rect, topRight); + + rect = EditorGUILayout.GetControlRect(false, EditorGUIUtility.singleLineHeight * (EditorGUIUtility.wideMode ? 1 : 2)); + rect.x += EditorGUIUtility.labelWidth; + rect.width = (rect.width - EditorGUIUtility.labelWidth) / 2f; + + TMP_EditorUtility.DrawColorProperty(rect, bottomLeft); + + rect.x += rect.width; + + TMP_EditorUtility.DrawColorProperty(rect, bottomRight); + break; + } + + if (EditorGUI.EndChangeCheck()) + { + m_HavePropertiesChanged = true; + if (obj != null) + { + obj.ApplyModifiedProperties(); + TMPro_EventManager.ON_COLOR_GRAIDENT_PROPERTY_CHANGED(m_FontColorGradientPresetProp.objectReferenceValue as TMP_ColorGradient); + } + } + + EditorGUI.indentLevel -= 1; + } + + EditorGUILayout.PropertyField(m_OverrideHtmlColorProp, k_OverrideTagsLabel); + + EditorGUILayout.Space(); + } + + void DrawSpacing() + { + // CHARACTER, LINE & PARAGRAPH SPACING + EditorGUI.BeginChangeCheck(); + + Rect rect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight); + + EditorGUI.PrefixLabel(rect, k_SpacingOptionsLabel); + + int oldIndent = EditorGUI.indentLevel; + EditorGUI.indentLevel = 0; + + rect.x += EditorGUIUtility.labelWidth; + rect.width = (rect.width - EditorGUIUtility.labelWidth - 3f) / 2f; + + EditorGUIUtility.labelWidth = Mathf.Min(rect.width * 0.55f, 80f); + + EditorGUI.PropertyField(rect, m_CharacterSpacingProp, k_CharacterSpacingLabel); + rect.x += rect.width + 3f; + EditorGUI.PropertyField(rect, m_WordSpacingProp, k_WordSpacingLabel); + + rect = EditorGUILayout.GetControlRect(false, EditorGUIUtility.singleLineHeight); + EditorGUIUtility.labelWidth = 0; + rect.x += EditorGUIUtility.labelWidth; + rect.width = (rect.width - EditorGUIUtility.labelWidth -3f) / 2f; + EditorGUIUtility.labelWidth = Mathf.Min(rect.width * 0.55f, 80f); + + EditorGUI.PropertyField(rect, m_LineSpacingProp, k_LineSpacingLabel); + rect.x += rect.width + 3f; + EditorGUI.PropertyField(rect, m_ParagraphSpacingProp, k_ParagraphSpacingLabel); + + EditorGUIUtility.labelWidth = 0; + EditorGUI.indentLevel = oldIndent; + + if (EditorGUI.EndChangeCheck()) + { + m_HavePropertiesChanged = true; + } + } + + void DrawAlignment() + { + // TEXT ALIGNMENT + EditorGUI.BeginChangeCheck(); + + EditorGUILayout.PropertyField(m_TextAlignmentProp, k_AlignmentLabel); + + // WRAPPING RATIOS shown if Justified mode is selected. + if (((_HorizontalAlignmentOptions)m_TextAlignmentProp.intValue & _HorizontalAlignmentOptions.Justified) == _HorizontalAlignmentOptions.Justified || ((_HorizontalAlignmentOptions)m_TextAlignmentProp.intValue & _HorizontalAlignmentOptions.Flush) == _HorizontalAlignmentOptions.Flush) + DrawPropertySlider(k_WrapMixLabel, m_WordWrappingRatiosProp); + + if (EditorGUI.EndChangeCheck()) + m_HavePropertiesChanged = true; + + EditorGUILayout.Space(); + } + + void DrawWrappingOverflow() + { + // TEXT WRAPPING + EditorGUI.BeginChangeCheck(); + int wrapSelection = EditorGUILayout.Popup(k_WrappingLabel, m_EnableWordWrappingProp.boolValue ? 1 : 0, k_WrappingOptions); + if (EditorGUI.EndChangeCheck()) + { + m_EnableWordWrappingProp.boolValue = wrapSelection == 1; + m_HavePropertiesChanged = true; + m_TextComponent.m_isInputParsingRequired = true; + } + + // TEXT OVERFLOW + EditorGUI.BeginChangeCheck(); + + // Cache Reference to Linked Text Component + TMP_Text oldLinkedComponent = m_LinkedTextComponentProp.objectReferenceValue as TMP_Text; + + if ((TextOverflowModes)m_TextOverflowModeProp.enumValueIndex == TextOverflowModes.Linked) + { + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.PropertyField(m_TextOverflowModeProp, k_OverflowLabel); + + EditorGUILayout.PropertyField(m_LinkedTextComponentProp, GUIContent.none); + + EditorGUILayout.EndHorizontal(); + + if (GUI.changed) + { + TMP_Text linkedComponent = m_LinkedTextComponentProp.objectReferenceValue as TMP_Text; + + if (linkedComponent) + m_TextComponent.linkedTextComponent = linkedComponent; + + } + } + else if ((TextOverflowModes)m_TextOverflowModeProp.enumValueIndex == TextOverflowModes.Page) + { + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.PropertyField(m_TextOverflowModeProp, k_OverflowLabel); + EditorGUILayout.PropertyField(m_PageToDisplayProp, GUIContent.none); + EditorGUILayout.EndHorizontal(); + + if (oldLinkedComponent) + m_TextComponent.linkedTextComponent = null; + } + else + { + EditorGUILayout.PropertyField(m_TextOverflowModeProp, k_OverflowLabel); + + if (oldLinkedComponent) + m_TextComponent.linkedTextComponent = null; + } + + if (EditorGUI.EndChangeCheck()) + { + m_HavePropertiesChanged = true; + m_TextComponent.m_isInputParsingRequired = true; + } + + EditorGUILayout.Space(); + } + + protected abstract void DrawExtraSettings(); + + protected void DrawMargins() + { + EditorGUI.BeginChangeCheck(); + DrawMarginProperty(m_MarginProp, k_MarginsLabel); + if (EditorGUI.EndChangeCheck()) + { + m_HavePropertiesChanged = true; + } + + EditorGUILayout.Space(); + } + + protected void DrawGeometrySorting() + { + EditorGUI.BeginChangeCheck(); + + EditorGUILayout.PropertyField(m_GeometrySortingOrderProp, k_GeometrySortingLabel); + + if (EditorGUI.EndChangeCheck()) + m_HavePropertiesChanged = true; + + EditorGUILayout.Space(); + } + + protected void DrawRichText() + { + EditorGUI.BeginChangeCheck(); + + EditorGUILayout.PropertyField(m_IsRichTextProp, k_RichTextLabel); + if (EditorGUI.EndChangeCheck()) + m_HavePropertiesChanged = true; + } + + protected void DrawParsing() + { + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(m_EnableEscapeCharacterParsingProp, k_EscapeCharactersLabel); + EditorGUILayout.PropertyField(m_UseMaxVisibleDescenderProp, k_VisibleDescenderLabel); + + EditorGUILayout.Space(); + + EditorGUILayout.PropertyField(m_SpriteAssetProp, k_SpriteAssetLabel, true); + + if (EditorGUI.EndChangeCheck()) + m_HavePropertiesChanged = true; + + EditorGUILayout.Space(); + } + + protected void DrawTextureMapping() + { + // TEXTURE MAPPING OPTIONS + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(m_HorizontalMappingProp, k_HorizontalMappingLabel); + EditorGUILayout.PropertyField(m_VerticalMappingProp, k_VerticalMappingLabel); + if (EditorGUI.EndChangeCheck()) + { + m_HavePropertiesChanged = true; + } + + // UV OPTIONS + if (m_HorizontalMappingProp.enumValueIndex > 0) + { + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(m_UvLineOffsetProp, k_LineOffsetLabel, GUILayout.MinWidth(70f)); + if (EditorGUI.EndChangeCheck()) + { + m_HavePropertiesChanged = true; + } + } + + EditorGUILayout.Space(); + } + + protected void DrawKerning() + { + // KERNING + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(m_EnableKerningProp, k_KerningLabel); + if (EditorGUI.EndChangeCheck()) + { + m_HavePropertiesChanged = true; + } + } + + protected void DrawPadding() + { + // EXTRA PADDING + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(m_EnableExtraPaddingProp, k_PaddingLabel); + if (EditorGUI.EndChangeCheck()) + { + m_HavePropertiesChanged = true; + m_CheckPaddingRequiredProp.boolValue = true; + } + } + + /// + /// Method to retrieve the material presets that match the currently selected font asset. + /// + protected GUIContent[] GetMaterialPresets() + { + TMP_FontAsset fontAsset = m_FontAssetProp.objectReferenceValue as TMP_FontAsset; + if (fontAsset == null) return null; + + m_MaterialPresets = TMP_EditorUtility.FindMaterialReferences(fontAsset); + m_MaterialPresetNames = new GUIContent[m_MaterialPresets.Length]; + + for (int i = 0; i < m_MaterialPresetNames.Length; i++) + { + m_MaterialPresetNames[i] = new GUIContent(m_MaterialPresets[i].name); + + if (m_TargetMaterial.GetInstanceID() == m_MaterialPresets[i].GetInstanceID()) + m_MaterialPresetSelectionIndex = i; + } + + m_IsPresetListDirty = false; + + return m_MaterialPresetNames; + } + + // DRAW MARGIN PROPERTY + protected void DrawMarginProperty(SerializedProperty property, GUIContent label) + { + Rect rect = EditorGUILayout.GetControlRect(false, 2 * 18); + + EditorGUI.BeginProperty(rect, label, property); + + Rect pos0 = new Rect(rect.x + 15, rect.y + 2, rect.width - 15, 18); + + float width = rect.width + 3; + pos0.width = EditorGUIUtility.labelWidth; + GUI.Label(pos0, label); + + var vec = property.vector4Value; + + float widthB = width - EditorGUIUtility.labelWidth; + float fieldWidth = widthB / 4; + pos0.width = Mathf.Max(fieldWidth - 5, 45f); + + // Labels + pos0.x = EditorGUIUtility.labelWidth + 15; + GUI.Label(pos0, k_LeftLabel); + + pos0.x += fieldWidth; + GUI.Label(pos0, k_TopLabel); + + pos0.x += fieldWidth; + GUI.Label(pos0, k_RightLabel); + + pos0.x += fieldWidth; + GUI.Label(pos0, k_BottomLabel); + + pos0.y += 18; + + pos0.x = EditorGUIUtility.labelWidth; + vec.x = EditorGUI.FloatField(pos0, GUIContent.none, vec.x); + + pos0.x += fieldWidth; + vec.y = EditorGUI.FloatField(pos0, GUIContent.none, vec.y); + + pos0.x += fieldWidth; + vec.z = EditorGUI.FloatField(pos0, GUIContent.none, vec.z); + + pos0.x += fieldWidth; + vec.w = EditorGUI.FloatField(pos0, GUIContent.none, vec.w); + + property.vector4Value = vec; + + EditorGUI.EndProperty(); + } + + protected void DrawPropertySlider(GUIContent label, SerializedProperty property) + { + Rect rect = EditorGUILayout.GetControlRect(false, 17); + + GUIContent content = label ?? GUIContent.none; + EditorGUI.Slider(new Rect(rect.x, rect.y, rect.width, rect.height), property, 0.0f, 1.0f, content); + } + + protected abstract bool IsMixSelectionTypes(); + + // Special Handling of Undo / Redo Events. + protected abstract void OnUndoRedo(); + + } +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_BaseShaderGUI.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_BaseShaderGUI.cs new file mode 100644 index 00000000..ed87b504 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_BaseShaderGUI.cs @@ -0,0 +1,534 @@ +using UnityEngine; +using UnityEditor; + +namespace TMPro.EditorUtilities +{ + /// Base class for TextMesh Pro shader GUIs. + public abstract class TMP_BaseShaderGUI : ShaderGUI + { + /// Representation of a #pragma shader_feature. + /// It is assumed that the first feature option is for no keyword (underscores). + protected class ShaderFeature + { + public string undoLabel; + + public GUIContent label; + + /// The keyword labels, for display. Include the no-keyword as the first option. + public GUIContent[] keywordLabels; + + /// The shader keywords. Exclude the no-keyword option. + public string[] keywords; + + int m_State; + + public bool Active + { + get { return m_State >= 0; } + } + + public int State + { + get { return m_State; } + } + + public void ReadState(Material material) + { + for (int i = 0; i < keywords.Length; i++) + { + if (material.IsKeywordEnabled(keywords[i])) + { + m_State = i; + return; + } + } + + m_State = -1; + } + + public void SetActive(bool active, Material material) + { + m_State = active ? 0 : -1; + SetStateKeywords(material); + } + + public void DoPopup(MaterialEditor editor, Material material) + { + EditorGUI.BeginChangeCheck(); + int selection = EditorGUILayout.Popup(label, m_State + 1, keywordLabels); + if (EditorGUI.EndChangeCheck()) + { + m_State = selection - 1; + editor.RegisterPropertyChangeUndo(undoLabel); + SetStateKeywords(material); + } + } + + void SetStateKeywords(Material material) + { + for (int i = 0; i < keywords.Length; i++) + { + if (i == m_State) + { + material.EnableKeyword(keywords[i]); + } + else + { + material.DisableKeyword(keywords[i]); + } + } + } + } + + static GUIContent s_TempLabel = new GUIContent(); + + protected static bool s_DebugExtended; + + static int s_UndoRedoCount, s_LastSeenUndoRedoCount; + + static float[][] s_TempFloats = + { + null, new float[1], new float[2], new float[3], new float[4] + }; + + protected static GUIContent[] s_XywhVectorLabels = + { + new GUIContent("X"), + new GUIContent("Y"), + new GUIContent("W", "Width"), + new GUIContent("H", "Height") + }; + + protected static GUIContent[] s_LbrtVectorLabels = + { + new GUIContent("L", "Left"), + new GUIContent("B", "Bottom"), + new GUIContent("R", "Right"), + new GUIContent("T", "Top") + }; + + static TMP_BaseShaderGUI() + { + // Keep track of how many undo/redo events happened. + Undo.undoRedoPerformed += () => s_UndoRedoCount += 1; + } + + bool m_IsNewGUI = true; + + float m_DragAndDropMinY; + + protected MaterialEditor m_Editor; + + protected Material m_Material; + + protected MaterialProperty[] m_Properties; + + void PrepareGUI() + { + m_IsNewGUI = false; + ShaderUtilities.GetShaderPropertyIDs(); + + // New GUI just got constructed. This happens in response to a selection, + // but also after undo/redo events. + if (s_LastSeenUndoRedoCount != s_UndoRedoCount) + { + // There's been at least one undo/redo since the last time this GUI got constructed. + // Maybe the undo/redo was for this material? Assume that is was. + TMPro_EventManager.ON_MATERIAL_PROPERTY_CHANGED(true, m_Material as Material); + } + + s_LastSeenUndoRedoCount = s_UndoRedoCount; + } + + public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] properties) + { + m_Editor = materialEditor; + m_Material = materialEditor.target as Material; + this.m_Properties = properties; + + if (m_IsNewGUI) + { + PrepareGUI(); + } + + DoDragAndDropBegin(); + EditorGUI.BeginChangeCheck(); + DoGUI(); + if (EditorGUI.EndChangeCheck()) + { + TMPro_EventManager.ON_MATERIAL_PROPERTY_CHANGED(true, m_Material); + } + + DoDragAndDropEnd(); + } + + /// Override this method to create the specific shader GUI. + protected abstract void DoGUI(); + + static string[] s_PanelStateLabel = new string[] { "\t- Click to collapse -", "\t- Click to expand -" }; + + protected bool BeginPanel(string panel, bool expanded) + { + EditorGUILayout.BeginVertical(EditorStyles.helpBox); + + Rect r = EditorGUI.IndentedRect(GUILayoutUtility.GetRect(20, 18)); + r.x += 20; + r.width += 6; + + bool enabled = GUI.enabled; + GUI.enabled = true; + expanded = TMP_EditorUtility.EditorToggle(r, expanded, new GUIContent(panel), TMP_UIStyleManager.panelTitle); + r.width -= 30; + EditorGUI.LabelField(r, new GUIContent(expanded ? s_PanelStateLabel[0] : s_PanelStateLabel[1]), TMP_UIStyleManager.rightLabel); + GUI.enabled = enabled; + + EditorGUI.indentLevel += 1; + EditorGUI.BeginDisabledGroup(false); + + return expanded; + } + + protected bool BeginPanel(string panel, ShaderFeature feature, bool expanded, bool readState = true) + { + if (readState) + { + feature.ReadState(m_Material); + } + + EditorGUI.BeginChangeCheck(); + + EditorGUILayout.BeginVertical(EditorStyles.helpBox); + GUILayout.BeginHorizontal(); + + Rect r = EditorGUI.IndentedRect(GUILayoutUtility.GetRect(20, 20, GUILayout.Width(20f))); + bool active = EditorGUI.Toggle(r, feature.Active); + + if (EditorGUI.EndChangeCheck()) + { + m_Editor.RegisterPropertyChangeUndo(feature.undoLabel); + feature.SetActive(active, m_Material); + } + + r = EditorGUI.IndentedRect(GUILayoutUtility.GetRect(20, 18)); + r.width += 6; + + bool enabled = GUI.enabled; + GUI.enabled = true; + expanded = TMP_EditorUtility.EditorToggle(r, expanded, new GUIContent(panel), TMP_UIStyleManager.panelTitle); + r.width -= 10; + EditorGUI.LabelField(r, new GUIContent(expanded ? s_PanelStateLabel[0] : s_PanelStateLabel[1]), TMP_UIStyleManager.rightLabel); + GUI.enabled = enabled; + + GUILayout.EndHorizontal(); + + EditorGUI.indentLevel += 1; + EditorGUI.BeginDisabledGroup(!active); + + return expanded; + } + + public void EndPanel() + { + EditorGUI.EndDisabledGroup(); + EditorGUI.indentLevel -= 1; + EditorGUILayout.EndVertical(); + } + + MaterialProperty BeginProperty(string name) + { + MaterialProperty property = FindProperty(name, m_Properties); + EditorGUI.BeginChangeCheck(); + EditorGUI.showMixedValue = property.hasMixedValue; + m_Editor.BeginAnimatedCheck(Rect.zero, property); + + return property; + } + + bool EndProperty() + { + m_Editor.EndAnimatedCheck(); + EditorGUI.showMixedValue = false; + return EditorGUI.EndChangeCheck(); + } + + protected void DoPopup(string name, string label, GUIContent[] options) + { + MaterialProperty property = BeginProperty(name); + s_TempLabel.text = label; + int index = EditorGUILayout.Popup(s_TempLabel, (int)property.floatValue, options); + if (EndProperty()) + { + property.floatValue = index; + } + } + + protected void DoCubeMap(string name, string label) + { + DoTexture(name, label, typeof(Cubemap)); + } + + protected void DoTexture2D(string name, string label, bool withTilingOffset = false, string[] speedNames = null) + { + DoTexture(name, label, typeof(Texture2D), withTilingOffset, speedNames); + } + + void DoTexture(string name, string label, System.Type type, bool withTilingOffset = false, string[] speedNames = null) + { + MaterialProperty property = BeginProperty(name); + Rect rect = EditorGUILayout.GetControlRect(true, 60f); + float totalWidth = rect.width; + rect.width = EditorGUIUtility.labelWidth + 60f; + s_TempLabel.text = label; + Object tex = EditorGUI.ObjectField(rect, s_TempLabel, property.textureValue, type, false); + + if (EndProperty()) + { + property.textureValue = tex as Texture; + } + + rect.x += rect.width + 4f; + rect.width = totalWidth - rect.width - 4f; + rect.height = EditorGUIUtility.singleLineHeight; + + if (withTilingOffset) + { + DoTilingOffset(rect, property); + rect.y += (rect.height + 2f) * 2f; + } + + if (speedNames != null) + { + DoUVSpeed(rect, speedNames); + } + } + + void DoTilingOffset(Rect rect, MaterialProperty property) + { + float labelWidth = EditorGUIUtility.labelWidth; + int indentLevel = EditorGUI.indentLevel; + EditorGUI.indentLevel = 0; + EditorGUIUtility.labelWidth = Mathf.Min(40f, rect.width * 0.20f); + + Vector4 vector = property.textureScaleAndOffset; + + bool changed = false; + float[] values = s_TempFloats[2]; + + s_TempLabel.text = "Tiling"; + Rect vectorRect = EditorGUI.PrefixLabel(rect, s_TempLabel); + values[0] = vector.x; + values[1] = vector.y; + EditorGUI.BeginChangeCheck(); + EditorGUI.MultiFloatField(vectorRect, s_XywhVectorLabels, values); + if (EndProperty()) + { + vector.x = values[0]; + vector.y = values[1]; + changed = true; + } + + rect.y += rect.height + 2f; + s_TempLabel.text = "Offset"; + vectorRect = EditorGUI.PrefixLabel(rect, s_TempLabel); + values[0] = vector.z; + values[1] = vector.w; + EditorGUI.BeginChangeCheck(); + EditorGUI.MultiFloatField(vectorRect, s_XywhVectorLabels, values); + if (EndProperty()) + { + vector.z = values[0]; + vector.w = values[1]; + changed = true; + } + + if (changed) + { + property.textureScaleAndOffset = vector; + } + + EditorGUIUtility.labelWidth = labelWidth; + EditorGUI.indentLevel = indentLevel; + } + + protected void DoUVSpeed(Rect rect, string[] names) + { + float labelWidth = EditorGUIUtility.labelWidth; + int indentLevel = EditorGUI.indentLevel; + EditorGUI.indentLevel = 0; + EditorGUIUtility.labelWidth = Mathf.Min(40f, rect.width * 0.20f); + + s_TempLabel.text = "Speed"; + rect = EditorGUI.PrefixLabel(rect, s_TempLabel); + + EditorGUIUtility.labelWidth = 13f; + rect.width = rect.width * 0.5f - 1f; + DoFloat(rect, names[0], "X"); + rect.x += rect.width + 2f; + DoFloat(rect, names[1], "Y"); + EditorGUIUtility.labelWidth = labelWidth; + EditorGUI.indentLevel = indentLevel; + } + + protected void DoToggle(string name, string label) + { + MaterialProperty property = BeginProperty(name); + s_TempLabel.text = label; + bool value = EditorGUILayout.Toggle(s_TempLabel, property.floatValue == 1f); + if (EndProperty()) + { + property.floatValue = value ? 1f : 0f; + } + } + + protected void DoFloat(string name, string label) + { + MaterialProperty property = BeginProperty(name); + Rect rect = EditorGUILayout.GetControlRect(); + rect.width = EditorGUIUtility.labelWidth + 55f; + s_TempLabel.text = label; + float value = EditorGUI.FloatField(rect, s_TempLabel, property.floatValue); + if (EndProperty()) + { + property.floatValue = value; + } + } + + protected void DoColor(string name, string label) + { + MaterialProperty property = BeginProperty(name); + s_TempLabel.text = label; + Color value = EditorGUI.ColorField(EditorGUILayout.GetControlRect(), s_TempLabel, property.colorValue); + if (EndProperty()) + { + property.colorValue = value; + } + } + + void DoFloat(Rect rect, string name, string label) + { + MaterialProperty property = BeginProperty(name); + s_TempLabel.text = label; + float value = EditorGUI.FloatField(rect, s_TempLabel, property.floatValue); + if (EndProperty()) + { + property.floatValue = value; + } + } + + protected void DoSlider(string name, string label) + { + MaterialProperty property = BeginProperty(name); + Vector2 range = property.rangeLimits; + s_TempLabel.text = label; + float value = EditorGUI.Slider( + EditorGUILayout.GetControlRect(), s_TempLabel, property.floatValue, range.x, range.y + ); + if (EndProperty()) + { + property.floatValue = value; + } + } + + protected void DoVector3(string name, string label) + { + MaterialProperty property = BeginProperty(name); + s_TempLabel.text = label; + Vector4 value = EditorGUILayout.Vector3Field(s_TempLabel, property.vectorValue); + if (EndProperty()) + { + property.vectorValue = value; + } + } + + protected void DoVector(string name, string label, GUIContent[] subLabels) + { + MaterialProperty property = BeginProperty(name); + Rect rect = EditorGUILayout.GetControlRect(); + s_TempLabel.text = label; + rect = EditorGUI.PrefixLabel(rect, s_TempLabel); + Vector4 vector = property.vectorValue; + + float[] values = s_TempFloats[subLabels.Length]; + for (int i = 0; i < subLabels.Length; i++) + { + values[i] = vector[i]; + } + + EditorGUI.MultiFloatField(rect, subLabels, values); + if (EndProperty()) + { + for (int i = 0; i < subLabels.Length; i++) + { + vector[i] = values[i]; + } + + property.vectorValue = vector; + } + } + + void DoDragAndDropBegin() + { + m_DragAndDropMinY = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true)).y; + } + + void DoDragAndDropEnd() + { + Rect rect = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true)); + Event evt = Event.current; + if (evt.type == EventType.DragUpdated) + { + DragAndDrop.visualMode = DragAndDropVisualMode.Generic; + evt.Use(); + } + else if ( + evt.type == EventType.DragPerform && + Rect.MinMaxRect(rect.xMin, m_DragAndDropMinY, rect.xMax, rect.yMax).Contains(evt.mousePosition) + ) + { + DragAndDrop.AcceptDrag(); + evt.Use(); + Material droppedMaterial = DragAndDrop.objectReferences[0] as Material; + if (droppedMaterial && droppedMaterial != m_Material) + { + PerformDrop(droppedMaterial); + } + } + } + + void PerformDrop(Material droppedMaterial) + { + Texture droppedTex = droppedMaterial.GetTexture(ShaderUtilities.ID_MainTex); + if (!droppedTex) + { + return; + } + + Texture currentTex = m_Material.GetTexture(ShaderUtilities.ID_MainTex); + TMP_FontAsset requiredFontAsset = null; + if (droppedTex != currentTex) + { + requiredFontAsset = TMP_EditorUtility.FindMatchingFontAsset(droppedMaterial); + if (!requiredFontAsset) + { + return; + } + } + + foreach (GameObject o in Selection.gameObjects) + { + if (requiredFontAsset) + { + TMP_Text textComponent = o.GetComponent(); + if (textComponent) + { + Undo.RecordObject(textComponent, "Font Asset Change"); + textComponent.font = requiredFontAsset; + } + } + + TMPro_EventManager.ON_DRAG_AND_DROP_MATERIAL_CHANGED(o, m_Material, droppedMaterial); + EditorUtility.SetDirty(o); + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_BitmapShaderGUI.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_BitmapShaderGUI.cs new file mode 100644 index 00000000..d35d5392 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_BitmapShaderGUI.cs @@ -0,0 +1,85 @@ +using UnityEngine; +using UnityEditor; + +namespace TMPro.EditorUtilities +{ + public class TMP_BitmapShaderGUI : TMP_BaseShaderGUI + { + static bool s_Face = true; + + protected override void DoGUI() + { + s_Face = BeginPanel("Face", s_Face); + if (s_Face) + { + DoFacePanel(); + } + + EndPanel(); + + s_DebugExtended = BeginPanel("Debug Settings", s_DebugExtended); + if (s_DebugExtended) + { + DoDebugPanel(); + } + + EndPanel(); + } + + void DoFacePanel() + { + EditorGUI.indentLevel += 1; + if (m_Material.HasProperty(ShaderUtilities.ID_FaceTex)) + { + DoColor("_FaceColor", "Color"); + DoTexture2D("_FaceTex", "Texture", true); + } + else + { + DoColor("_Color", "Color"); + DoSlider("_DiffusePower", "Diffuse Power"); + } + + EditorGUI.indentLevel -= 1; + + EditorGUILayout.Space(); + } + + void DoDebugPanel() + { + EditorGUI.indentLevel += 1; + DoTexture2D("_MainTex", "Font Atlas"); + if (m_Material.HasProperty(ShaderUtilities.ID_VertexOffsetX)) + { + if (m_Material.HasProperty(ShaderUtilities.ID_Padding)) + { + EditorGUILayout.Space(); + DoFloat("_Padding", "Padding"); + } + + EditorGUILayout.Space(); + DoFloat("_VertexOffsetX", "Offset X"); + DoFloat("_VertexOffsetY", "Offset Y"); + } + + if (m_Material.HasProperty(ShaderUtilities.ID_MaskSoftnessX)) + { + EditorGUILayout.Space(); + DoFloat("_MaskSoftnessX", "Softness X"); + DoFloat("_MaskSoftnessY", "Softness Y"); + DoVector("_ClipRect", "Clip Rect", s_LbrtVectorLabels); + } + + if (m_Material.HasProperty(ShaderUtilities.ID_StencilID)) + { + EditorGUILayout.Space(); + DoFloat("_Stencil", "Stencil ID"); + DoFloat("_StencilComp", "Stencil Comp"); + } + + EditorGUI.indentLevel -= 1; + + EditorGUILayout.Space(); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_CharacterPropertyDrawer.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_CharacterPropertyDrawer.cs new file mode 100644 index 00000000..c1f5fb99 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_CharacterPropertyDrawer.cs @@ -0,0 +1,237 @@ +using UnityEngine; +using UnityEngine.TextCore; +using UnityEngine.TextCore.LowLevel; +using UnityEditor; +using System.Collections; + + +namespace TMPro.EditorUtilities +{ + [CustomPropertyDrawer(typeof(TMP_Character))] + public class TMP_CharacterPropertyDrawer : PropertyDrawer + { + //[SerializeField] + //static Material s_InternalSDFMaterial; + + //[SerializeField] + //static Material s_InternalBitmapMaterial; + + int m_GlyphSelectedForEditing = -1; + + public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) + { + SerializedProperty prop_Unicode = property.FindPropertyRelative("m_Unicode"); + SerializedProperty prop_GlyphIndex = property.FindPropertyRelative("m_GlyphIndex"); + SerializedProperty prop_Scale = property.FindPropertyRelative("m_Scale"); + + + GUIStyle style = new GUIStyle(EditorStyles.label); + style.richText = true; + + EditorGUIUtility.labelWidth = 40f; + EditorGUIUtility.fieldWidth = 50; + + Rect rect = new Rect(position.x + 50, position.y, position.width, 49); + + // Display non-editable fields + if (GUI.enabled == false) + { + int unicode = prop_Unicode.intValue; + EditorGUI.LabelField(new Rect(rect.x, rect.y, 120f, 18), new GUIContent("Unicode: 0x" + unicode.ToString("X") + ""), style); + EditorGUI.LabelField(new Rect(rect.x + 115, rect.y, 120f, 18), unicode <= 0xFFFF ? new GUIContent("UTF16: \\u" + unicode.ToString("X4") + "") : new GUIContent("UTF32: \\U" + unicode.ToString("X8") + ""), style); + EditorGUI.LabelField(new Rect(rect.x, rect.y + 18, 120, 18), new GUIContent("Glyph ID: " + prop_GlyphIndex.intValue + ""), style); + EditorGUI.LabelField(new Rect(rect.x, rect.y + 36, 80, 18), new GUIContent("Scale: " + prop_Scale.floatValue + ""), style); + + // Draw Glyph (if exists) + DrawGlyph(position, property); + } + else // Display editable fields + { + EditorGUIUtility.labelWidth = 55f; + GUI.SetNextControlName("Unicode Input"); + EditorGUI.BeginChangeCheck(); + string unicode = EditorGUI.TextField(new Rect(rect.x, rect.y, 120, 18), "Unicode:", prop_Unicode.intValue.ToString("X")); + + if (GUI.GetNameOfFocusedControl() == "Unicode Input") + { + //Filter out unwanted characters. + char chr = Event.current.character; + if ((chr < '0' || chr > '9') && (chr < 'a' || chr > 'f') && (chr < 'A' || chr > 'F')) + { + Event.current.character = '\0'; + } + } + + if (EditorGUI.EndChangeCheck()) + { + // Update Unicode value + prop_Unicode.intValue = TMP_TextUtilities.StringHexToInt(unicode); + } + + // Cache current glyph index in case it needs to be restored if the new glyph index is invalid. + int currentGlyphIndex = prop_GlyphIndex.intValue; + + EditorGUIUtility.labelWidth = 59f; + EditorGUI.BeginChangeCheck(); + EditorGUI.DelayedIntField(new Rect(rect.x, rect.y + 18, 100, 18), prop_GlyphIndex, new GUIContent("Glyph ID:")); + if (EditorGUI.EndChangeCheck()) + { + // Get a reference to the font asset + TMP_FontAsset fontAsset = property.serializedObject.targetObject as TMP_FontAsset; + + // Make sure new glyph index is valid. + int elementIndex = fontAsset.glyphTable.FindIndex(item => item.index == prop_GlyphIndex.intValue); + + if (elementIndex == -1) + prop_GlyphIndex.intValue = currentGlyphIndex; + else + fontAsset.m_IsFontAssetLookupTablesDirty = true; + } + + int glyphIndex = prop_GlyphIndex.intValue; + + // Reset glyph selection if new character has been selected. + if (GUI.enabled && m_GlyphSelectedForEditing != glyphIndex) + m_GlyphSelectedForEditing = -1; + + // Display button to edit the glyph data. + if (GUI.Button(new Rect(rect.x + 120, rect.y + 18, 75, 18), new GUIContent("Edit Glyph"))) + { + if (m_GlyphSelectedForEditing == -1) + m_GlyphSelectedForEditing = glyphIndex; + else + m_GlyphSelectedForEditing = -1; + + // Button clicks should not result in potential change. + GUI.changed = false; + } + + // Show the glyph property drawer if selected + if (glyphIndex == m_GlyphSelectedForEditing && GUI.enabled) + { + // Get a reference to the font asset + TMP_FontAsset fontAsset = property.serializedObject.targetObject as TMP_FontAsset; + + if (fontAsset != null) + { + // Get the index of the glyph in the font asset glyph table. + int elementIndex = fontAsset.glyphTable.FindIndex(item => item.index == glyphIndex); + + if (elementIndex != -1) + { + SerializedProperty prop_GlyphTable = property.serializedObject.FindProperty("m_GlyphTable"); + SerializedProperty prop_Glyph = prop_GlyphTable.GetArrayElementAtIndex(elementIndex); + + SerializedProperty prop_GlyphMetrics = prop_Glyph.FindPropertyRelative("m_Metrics"); + SerializedProperty prop_GlyphRect = prop_Glyph.FindPropertyRelative("m_GlyphRect"); + + Rect newRect = EditorGUILayout.GetControlRect(false, 115); + EditorGUI.DrawRect(new Rect(newRect.x + 52, newRect.y - 20, newRect.width - 52, newRect.height - 5), new Color(0.1f, 0.1f, 0.1f, 0.45f)); + EditorGUI.DrawRect(new Rect(newRect.x + 53, newRect.y - 19, newRect.width - 54, newRect.height - 7), new Color(0.3f, 0.3f, 0.3f, 0.8f)); + + // Display GlyphRect + newRect.x += 55; + newRect.y -= 18; + newRect.width += 5; + EditorGUI.PropertyField(newRect, prop_GlyphRect); + + // Display GlyphMetrics + newRect.y += 45; + EditorGUI.PropertyField(newRect, prop_GlyphMetrics); + + rect.y += 120; + } + } + } + + EditorGUIUtility.labelWidth = 39f; + EditorGUI.PropertyField(new Rect(rect.x, rect.y + 36, 80, 18), prop_Scale, new GUIContent("Scale:")); + + // Draw Glyph (if exists) + DrawGlyph(position, property); + } + } + + public override float GetPropertyHeight(SerializedProperty property, GUIContent label) + { + return 58; + } + + void DrawGlyph(Rect position, SerializedProperty property) + { + // Get a reference to the atlas texture + TMP_FontAsset fontAsset = property.serializedObject.targetObject as TMP_FontAsset; + + if (fontAsset == null) + return; + + // Get a reference to the Glyph Table + SerializedProperty prop_GlyphTable = property.serializedObject.FindProperty("m_GlyphTable"); + int glyphIndex = property.FindPropertyRelative("m_GlyphIndex").intValue; + int elementIndex = fontAsset.glyphTable.FindIndex(item => item.index == glyphIndex); + + // Return if we can't find the glyph + if (elementIndex == -1) + return; + + SerializedProperty prop_Glyph = prop_GlyphTable.GetArrayElementAtIndex(elementIndex); + + // Get reference to atlas texture. + int atlasIndex = prop_Glyph.FindPropertyRelative("m_AtlasIndex").intValue; + Texture2D atlasTexture = fontAsset.atlasTextures.Length > atlasIndex ? fontAsset.atlasTextures[atlasIndex] : null; + + if (atlasTexture == null) + return; + + Material mat; + if (((GlyphRasterModes)fontAsset.atlasRenderMode & GlyphRasterModes.RASTER_MODE_BITMAP) == GlyphRasterModes.RASTER_MODE_BITMAP) + { + mat = TMP_FontAssetEditor.internalBitmapMaterial; + + if (mat == null) + return; + + mat.mainTexture = atlasTexture; + mat.SetColor("_Color", Color.white); + } + else + { + mat = TMP_FontAssetEditor.internalSDFMaterial; + + if (mat == null) + return; + + mat.mainTexture = atlasTexture; + mat.SetFloat(ShaderUtilities.ID_GradientScale, fontAsset.atlasPadding + 1); + } + + // Draw glyph + Rect glyphDrawPosition = new Rect(position.x, position.y, 48, 58); + + SerializedProperty prop_GlyphRect = prop_Glyph.FindPropertyRelative("m_GlyphRect"); + + int glyphOriginX = prop_GlyphRect.FindPropertyRelative("m_X").intValue; + int glyphOriginY = prop_GlyphRect.FindPropertyRelative("m_Y").intValue; + int glyphWidth = prop_GlyphRect.FindPropertyRelative("m_Width").intValue; + int glyphHeight = prop_GlyphRect.FindPropertyRelative("m_Height").intValue; + + float normalizedHeight = fontAsset.faceInfo.ascentLine - fontAsset.faceInfo.descentLine; + float scale = glyphDrawPosition.width / normalizedHeight; + + // Compute the normalized texture coordinates + Rect texCoords = new Rect((float)glyphOriginX / atlasTexture.width, (float)glyphOriginY / atlasTexture.height, (float)glyphWidth / atlasTexture.width, (float)glyphHeight / atlasTexture.height); + + if (Event.current.type == EventType.Repaint) + { + glyphDrawPosition.x += (glyphDrawPosition.width - glyphWidth * scale) / 2; + glyphDrawPosition.y += (glyphDrawPosition.height - glyphHeight * scale) / 2; + glyphDrawPosition.width = glyphWidth * scale; + glyphDrawPosition.height = glyphHeight * scale; + + // Could switch to using the default material of the font asset which would require passing scale to the shader. + Graphics.DrawTexture(glyphDrawPosition, atlasTexture, texCoords, 0, 0, 0, 0, new Color(1f, 1f, 1f), mat); + } + } + + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_ColorGradientAssetMenu.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_ColorGradientAssetMenu.cs new file mode 100644 index 00000000..ccfd3676 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_ColorGradientAssetMenu.cs @@ -0,0 +1,51 @@ +using UnityEditor; +using UnityEngine; +using System.IO; +using System.Collections; + + + +namespace TMPro.EditorUtilities +{ + + public static class TMP_ColorGradientAssetMenu + { + [MenuItem("Assets/Create/TextMeshPro/Color Gradient", false, 115)] + public static void CreateColorGradient(MenuCommand context) + { + string filePath; + + if (Selection.assetGUIDs.Length == 0) + filePath = "Assets/New TMP Color Gradient.asset"; + else + filePath = AssetDatabase.GUIDToAssetPath(Selection.assetGUIDs[0]); + + if (Directory.Exists(filePath)) + { + filePath += "/New TMP Color Gradient.asset"; + } + else + { + filePath = Path.GetDirectoryName(filePath) + "/New TMP Color Gradient.asset"; + } + + filePath = AssetDatabase.GenerateUniqueAssetPath(filePath); + + // Create new Color Gradient Asset. + TMP_ColorGradient colorGradient = ScriptableObject.CreateInstance(); + + // Create Asset + AssetDatabase.CreateAsset(colorGradient, filePath); + + //EditorUtility.SetDirty(colorGradient); + + AssetDatabase.SaveAssets(); + + AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(colorGradient)); + + EditorUtility.FocusProjectWindow(); + Selection.activeObject = colorGradient; + + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_ColorGradientEditor.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_ColorGradientEditor.cs new file mode 100644 index 00000000..4dddbfb0 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_ColorGradientEditor.cs @@ -0,0 +1,146 @@ +using UnityEngine; +using UnityEditor; +using System.Collections; + + +namespace TMPro.EditorUtilities +{ + [CustomEditor(typeof(TMP_ColorGradient))] + public class TMP_ColorGradientEditor : Editor + { + SerializedProperty m_ColorMode; + SerializedProperty m_TopLeftColor; + SerializedProperty m_TopRightColor; + SerializedProperty m_BottomLeftColor; + SerializedProperty m_BottomRightColor; + + void OnEnable() + { + m_ColorMode = serializedObject.FindProperty("colorMode"); + m_TopLeftColor = serializedObject.FindProperty("topLeft"); + m_TopRightColor = serializedObject.FindProperty("topRight"); + m_BottomLeftColor = serializedObject.FindProperty("bottomLeft"); + m_BottomRightColor = serializedObject.FindProperty("bottomRight"); + } + + public override void OnInspectorGUI() + { + serializedObject.Update(); + + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(m_ColorMode, new GUIContent("Color Mode")); + if (EditorGUI.EndChangeCheck()) + { + switch ((ColorMode)m_ColorMode.enumValueIndex) + { + case ColorMode.Single: + m_TopRightColor.colorValue = m_TopLeftColor.colorValue; + m_BottomLeftColor.colorValue = m_TopLeftColor.colorValue; + m_BottomRightColor.colorValue = m_TopLeftColor.colorValue; + break; + case ColorMode.HorizontalGradient: + m_BottomLeftColor.colorValue = m_TopLeftColor.colorValue; + m_BottomRightColor.colorValue = m_TopRightColor.colorValue; + break; + case ColorMode.VerticalGradient: + m_TopRightColor.colorValue = m_TopLeftColor.colorValue; + m_BottomRightColor.colorValue = m_BottomLeftColor.colorValue; + break; + } + } + Rect rect; + switch ((ColorMode)m_ColorMode.enumValueIndex) + { + case ColorMode.Single: + EditorGUI.BeginChangeCheck(); + rect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight * (EditorGUIUtility.wideMode ? 1 : 2)); + EditorGUI.PrefixLabel(rect, new GUIContent("Colors")); + rect.x += EditorGUIUtility.labelWidth; + rect.width = (rect.width - EditorGUIUtility.labelWidth) / (EditorGUIUtility.wideMode ? 1f : 2f); + TMP_EditorUtility.DrawColorProperty(rect, m_TopLeftColor); + if (EditorGUI.EndChangeCheck()) + { + m_TopRightColor.colorValue = m_TopLeftColor.colorValue; + m_BottomLeftColor.colorValue = m_TopLeftColor.colorValue; + m_BottomRightColor.colorValue = m_TopLeftColor.colorValue; + } + break; + + case ColorMode.HorizontalGradient: + rect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight * (EditorGUIUtility.wideMode ? 1 : 2)); + EditorGUI.PrefixLabel(rect, new GUIContent("Colors")); + rect.x += EditorGUIUtility.labelWidth; + rect.width = (rect.width - EditorGUIUtility.labelWidth) / 2f; + + EditorGUI.BeginChangeCheck(); + TMP_EditorUtility.DrawColorProperty(rect, m_TopLeftColor); + if (EditorGUI.EndChangeCheck()) + { + m_BottomLeftColor.colorValue = m_TopLeftColor.colorValue; + } + + rect.x += rect.width; + + EditorGUI.BeginChangeCheck(); + TMP_EditorUtility.DrawColorProperty(rect, m_TopRightColor); + if (EditorGUI.EndChangeCheck()) + { + m_BottomRightColor.colorValue = m_TopRightColor.colorValue; + } + break; + + case ColorMode.VerticalGradient: + rect = EditorGUILayout.GetControlRect(false, EditorGUIUtility.singleLineHeight * (EditorGUIUtility.wideMode ? 1 : 2)); + EditorGUI.PrefixLabel(rect, new GUIContent("Colors")); + rect.x += EditorGUIUtility.labelWidth; + rect.width = (rect.width - EditorGUIUtility.labelWidth) / (EditorGUIUtility.wideMode ? 1f : 2f); + rect.height = EditorGUIUtility.singleLineHeight * (EditorGUIUtility.wideMode ? 1 : 2); + + EditorGUI.BeginChangeCheck(); + TMP_EditorUtility.DrawColorProperty(rect, m_TopLeftColor); + if (EditorGUI.EndChangeCheck()) + { + m_TopRightColor.colorValue = m_TopLeftColor.colorValue; + } + + rect = EditorGUILayout.GetControlRect(false, EditorGUIUtility.singleLineHeight * (EditorGUIUtility.wideMode ? 1 : 2)); + rect.x += EditorGUIUtility.labelWidth; + rect.width = (rect.width - EditorGUIUtility.labelWidth) / (EditorGUIUtility.wideMode ? 1f : 2f); + rect.height = EditorGUIUtility.singleLineHeight * (EditorGUIUtility.wideMode ? 1 : 2); + + EditorGUI.BeginChangeCheck(); + TMP_EditorUtility.DrawColorProperty(rect, m_BottomLeftColor); + if (EditorGUI.EndChangeCheck()) + { + m_BottomRightColor.colorValue = m_BottomLeftColor.colorValue; + } + break; + + case ColorMode.FourCornersGradient: + rect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight * (EditorGUIUtility.wideMode ? 1 : 2)); + EditorGUI.PrefixLabel(rect, new GUIContent("Colors")); + rect.x += EditorGUIUtility.labelWidth; + rect.width = (rect.width - EditorGUIUtility.labelWidth) / 2f; + rect.height = EditorGUIUtility.singleLineHeight * (EditorGUIUtility.wideMode ? 1 : 2); + + TMP_EditorUtility.DrawColorProperty(rect, m_TopLeftColor); + rect.x += rect.width; + TMP_EditorUtility.DrawColorProperty(rect, m_TopRightColor); + + rect = EditorGUILayout.GetControlRect(false, EditorGUIUtility.singleLineHeight * (EditorGUIUtility.wideMode ? 1 : 2)); + rect.x += EditorGUIUtility.labelWidth; + rect.width = (rect.width - EditorGUIUtility.labelWidth) / 2f; + rect.height = EditorGUIUtility.singleLineHeight * (EditorGUIUtility.wideMode ? 1 : 2); + + TMP_EditorUtility.DrawColorProperty(rect, m_BottomLeftColor); + rect.x += rect.width; + TMP_EditorUtility.DrawColorProperty(rect, m_BottomRightColor); + break; + } + + if (serializedObject.ApplyModifiedProperties()) + TMPro_EventManager.ON_COLOR_GRAIDENT_PROPERTY_CHANGED(target as TMP_ColorGradient); + + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_DropdownEditor.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_DropdownEditor.cs new file mode 100644 index 00000000..b8e96135 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_DropdownEditor.cs @@ -0,0 +1,51 @@ +using UnityEngine; +using UnityEditor; +using UnityEditor.UI; +using UnityEngine.UI; + +namespace TMPro.EditorUtilities +{ + [CustomEditor(typeof(TMP_Dropdown), true)] + [CanEditMultipleObjects] + public class DropdownEditor : SelectableEditor + { + SerializedProperty m_Template; + SerializedProperty m_CaptionText; + SerializedProperty m_CaptionImage; + SerializedProperty m_ItemText; + SerializedProperty m_ItemImage; + SerializedProperty m_OnSelectionChanged; + SerializedProperty m_Value; + SerializedProperty m_Options; + + protected override void OnEnable() + { + base.OnEnable(); + m_Template = serializedObject.FindProperty("m_Template"); + m_CaptionText = serializedObject.FindProperty("m_CaptionText"); + m_CaptionImage = serializedObject.FindProperty("m_CaptionImage"); + m_ItemText = serializedObject.FindProperty("m_ItemText"); + m_ItemImage = serializedObject.FindProperty("m_ItemImage"); + m_OnSelectionChanged = serializedObject.FindProperty("m_OnValueChanged"); + m_Value = serializedObject.FindProperty("m_Value"); + m_Options = serializedObject.FindProperty("m_Options"); + } + + public override void OnInspectorGUI() + { + base.OnInspectorGUI(); + EditorGUILayout.Space(); + + serializedObject.Update(); + EditorGUILayout.PropertyField(m_Template); + EditorGUILayout.PropertyField(m_CaptionText); + EditorGUILayout.PropertyField(m_CaptionImage); + EditorGUILayout.PropertyField(m_ItemText); + EditorGUILayout.PropertyField(m_ItemImage); + EditorGUILayout.PropertyField(m_Value); + EditorGUILayout.PropertyField(m_Options); + EditorGUILayout.PropertyField(m_OnSelectionChanged); + serializedObject.ApplyModifiedProperties(); + } + } +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_EditorCoroutine.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_EditorCoroutine.cs new file mode 100644 index 00000000..e0056039 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_EditorCoroutine.cs @@ -0,0 +1,96 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using UnityEditor; +using UnityEngine; + + +namespace TMPro.EditorUtilities +{ + /// + /// Simple implementation of coroutine working in the Unity Editor. + /// + public class TMP_EditorCoroutine + { + //private static Dictionary s_ActiveCoroutines; + + readonly IEnumerator coroutine; + + /// + /// Constructor + /// + /// + TMP_EditorCoroutine(IEnumerator routine) + { + this.coroutine = routine; + } + + + /// + /// Starts a new EditorCoroutine. + /// + /// Coroutine + /// new EditorCoroutine + public static TMP_EditorCoroutine StartCoroutine(IEnumerator routine) + { + TMP_EditorCoroutine coroutine = new TMP_EditorCoroutine(routine); + coroutine.Start(); + + // Add coroutine to tracking list + //if (s_ActiveCoroutines == null) + // s_ActiveCoroutines = new Dictionary(); + + // Add new instance of editor coroutine to dictionary. + //s_ActiveCoroutines.Add(coroutine.GetHashCode(), coroutine); + + return coroutine; + } + + + /// + /// Clear delegate list + /// + //public static void StopAllEditorCoroutines() + //{ + // EditorApplication.update = null; + //} + + + /// + /// Register callback for editor updates + /// + void Start() + { + EditorApplication.update += EditorUpdate; + } + + + /// + /// Unregister callback for editor updates. + /// + public void Stop() + { + if (EditorApplication.update != null) + EditorApplication.update -= EditorUpdate; + + //s_ActiveCoroutines.Remove(this.GetHashCode()); + } + + + /// + /// Delegate function called on editor updates. + /// + void EditorUpdate() + { + // Stop editor coroutine if it does not continue. + if (coroutine.MoveNext() == false) + Stop(); + + // Process the different types of EditorCoroutines. + if (coroutine.Current != null) + { + + } + } + } +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_EditorPanel.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_EditorPanel.cs new file mode 100644 index 00000000..bf961c6d --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_EditorPanel.cs @@ -0,0 +1,153 @@ +using UnityEngine; +using UnityEditor; + +namespace TMPro.EditorUtilities +{ + + [CustomEditor(typeof(TextMeshPro), true), CanEditMultipleObjects] + public class TMP_EditorPanel : TMP_BaseEditorPanel + { + static readonly GUIContent k_SortingLayerLabel = new GUIContent("Sorting Layer", "Name of the Renderer's sorting layer."); + static readonly GUIContent k_OrderInLayerLabel = new GUIContent("Order in Layer", "Renderer's order within a sorting layer."); + static readonly GUIContent k_OrthographicLabel = new GUIContent("Orthographic Mode", "Should be enabled when using an orthographic camera. Instructs the shader to not perform any perspective correction."); + static readonly GUIContent k_VolumetricLabel = new GUIContent("Volumetric Setup", "Use cubes rather than quads to render the text. Allows for volumetric rendering when combined with a compatible shader."); + + SerializedProperty m_IsVolumetricTextProp; + + SerializedProperty m_IsOrthographicProp; + + Renderer m_Renderer; + + protected override void OnEnable() + { + base.OnEnable(); + + m_IsOrthographicProp = serializedObject.FindProperty("m_isOrthographic"); + + m_IsVolumetricTextProp = serializedObject.FindProperty("m_isVolumetricText"); + + m_Renderer = m_TextComponent.GetComponent(); + } + + protected override void DrawExtraSettings() + { + Foldout.extraSettings = EditorGUILayout.Foldout(Foldout.extraSettings, k_ExtraSettingsLabel, true, TMP_UIStyleManager.boldFoldout); + if (Foldout.extraSettings) + { + EditorGUI.indentLevel += 1; + + DrawMargins(); + + DrawSortingLayer(); + + DrawGeometrySorting(); + + DrawOrthographicMode(); + + DrawRichText(); + + DrawParsing(); + + DrawVolumetricSetup(); + + DrawKerning(); + + DrawPadding(); + + EditorGUI.indentLevel -= 1; + } + } + + protected void DrawSortingLayer() + { + Undo.RecordObject(m_Renderer, "Sorting Layer Change"); + + EditorGUI.BeginChangeCheck(); + + // SORTING LAYERS + var sortingLayerNames = SortingLayerHelper.sortingLayerNames; + + var textComponent = (TextMeshPro)m_TextComponent; + + // Look up the layer name using the current layer ID + string oldName = SortingLayerHelper.GetSortingLayerNameFromID(textComponent.sortingLayerID); + + // Use the name to look up our array index into the names list + int oldLayerIndex = System.Array.IndexOf(sortingLayerNames, oldName); + + // Show the pop-up for the names + EditorGUIUtility.fieldWidth = 0f; + int newLayerIndex = EditorGUILayout.Popup(k_SortingLayerLabel, oldLayerIndex, sortingLayerNames); + + // If the index changes, look up the ID for the new index to store as the new ID + if (newLayerIndex != oldLayerIndex) + { + textComponent.sortingLayerID = SortingLayerHelper.GetSortingLayerIDForIndex(newLayerIndex); + } + + // Expose the manual sorting order + int newSortingLayerOrder = EditorGUILayout.IntField(k_OrderInLayerLabel, textComponent.sortingOrder); + if (newSortingLayerOrder != textComponent.sortingOrder) + { + textComponent.sortingOrder = newSortingLayerOrder; + } + + if (EditorGUI.EndChangeCheck()) + m_HavePropertiesChanged = true; + + EditorGUILayout.Space(); + } + + protected void DrawOrthographicMode() + { + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(m_IsOrthographicProp, k_OrthographicLabel); + if (EditorGUI.EndChangeCheck()) + m_HavePropertiesChanged = true; + } + + protected void DrawVolumetricSetup() + { + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(m_IsVolumetricTextProp, k_VolumetricLabel); + if (EditorGUI.EndChangeCheck()) + { + m_HavePropertiesChanged = true; + m_TextComponent.textInfo.ResetVertexLayout(m_IsVolumetricTextProp.boolValue); + } + + EditorGUILayout.Space(); + } + + // Method to handle multi object selection + protected override bool IsMixSelectionTypes() + { + GameObject[] objects = Selection.gameObjects; + if (objects.Length > 1) + { + for (int i = 0; i < objects.Length; i++) + { + if (objects[i].GetComponent() == null) + return true; + } + } + return false; + } + + protected override void OnUndoRedo() + { + int undoEventId = Undo.GetCurrentGroup(); + int lastUndoEventId = s_EventId; + + if (undoEventId != lastUndoEventId) + { + for (int i = 0; i < targets.Length; i++) + { + //Debug.Log("Undo & Redo Performed detected in Editor Panel. Event ID:" + Undo.GetCurrentGroup()); + TMPro_EventManager.ON_TEXTMESHPRO_PROPERTY_CHANGED(true, targets[i] as TextMeshPro); + s_EventId = undoEventId; + } + } + } + } +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_EditorUtility.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_EditorUtility.cs new file mode 100644 index 00000000..d9ccd86f --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_EditorUtility.cs @@ -0,0 +1,450 @@ +using UnityEngine; +using UnityEditor; +using System.Text; +using System.IO; +using System.Collections; +using System.Collections.Generic; + + +namespace TMPro.EditorUtilities +{ + + public static class TMP_EditorUtility + { + /// + /// Returns the relative path of the package. + /// + public static string packageRelativePath + { + get + { + if (string.IsNullOrEmpty(m_PackagePath)) + m_PackagePath = GetPackageRelativePath(); + + return m_PackagePath; + } + } + [SerializeField] + private static string m_PackagePath; + + /// + /// Returns the fully qualified path of the package. + /// + public static string packageFullPath + { + get + { + if (string.IsNullOrEmpty(m_PackageFullPath)) + m_PackageFullPath = GetPackageFullPath(); + + return m_PackageFullPath; + } + } + [SerializeField] + private static string m_PackageFullPath; + + + // Static Fields Related to locating the TextMesh Pro Asset + private static string folderPath = "Not Found"; + + private static EditorWindow Gameview; + private static bool isInitialized = false; + + private static void GetGameview() + { + System.Reflection.Assembly assembly = typeof(UnityEditor.EditorWindow).Assembly; + System.Type type = assembly.GetType("UnityEditor.GameView"); + Gameview = EditorWindow.GetWindow(type); + } + + + public static void RepaintAll() + { + if (isInitialized == false) + { + GetGameview(); + isInitialized = true; + } + + SceneView.RepaintAll(); + Gameview.Repaint(); + } + + + /// + /// Create and return a new asset in a smart location based on the current selection and then select it. + /// + /// + /// Name of the new asset. Do not include the .asset extension. + /// + /// + /// The new asset. + /// + public static T CreateAsset(string name) where T : ScriptableObject + { + string path = AssetDatabase.GetAssetPath(Selection.activeObject); + if (path.Length == 0) + { + // no asset selected, place in asset root + path = "Assets/" + name + ".asset"; + } + else if (Directory.Exists(path)) + { + // place in currently selected directory + path += "/" + name + ".asset"; + } + else { + // place in current selection's containing directory + path = Path.GetDirectoryName(path) + "/" + name + ".asset"; + } + T asset = ScriptableObject.CreateInstance(); + AssetDatabase.CreateAsset(asset, AssetDatabase.GenerateUniqueAssetPath(path)); + EditorUtility.FocusProjectWindow(); + Selection.activeObject = asset; + return asset; + } + + + + // Function used to find all materials which reference a font atlas so we can update all their references. + public static Material[] FindMaterialReferences(TMP_FontAsset fontAsset) + { + List refs = new List(); + Material mat = fontAsset.material; + refs.Add(mat); + + // Get materials matching the search pattern. + string searchPattern = "t:Material" + " " + fontAsset.name.Split(new char[] { ' ' })[0]; + string[] materialAssetGUIDs = AssetDatabase.FindAssets(searchPattern); + + for (int i = 0; i < materialAssetGUIDs.Length; i++) + { + string materialPath = AssetDatabase.GUIDToAssetPath(materialAssetGUIDs[i]); + Material targetMaterial = AssetDatabase.LoadAssetAtPath(materialPath); + + if (targetMaterial.HasProperty(ShaderUtilities.ID_MainTex) && targetMaterial.GetTexture(ShaderUtilities.ID_MainTex) != null && mat.GetTexture(ShaderUtilities.ID_MainTex) != null && targetMaterial.GetTexture(ShaderUtilities.ID_MainTex).GetInstanceID() == mat.GetTexture(ShaderUtilities.ID_MainTex).GetInstanceID()) + { + if (!refs.Contains(targetMaterial)) + refs.Add(targetMaterial); + } + else + { + // TODO: Find a more efficient method to unload resources. + //Resources.UnloadAsset(targetMaterial.GetTexture(ShaderUtilities.ID_MainTex)); + } + } + + return refs.ToArray(); + } + + + // Function used to find the Font Asset which matches the given Material Preset and Font Atlas Texture. + public static TMP_FontAsset FindMatchingFontAsset(Material mat) + { + if (mat.GetTexture(ShaderUtilities.ID_MainTex) == null) return null; + + // Find the dependent assets of this material. + string[] dependentAssets = AssetDatabase.GetDependencies(AssetDatabase.GetAssetPath(mat), false); + + for (int i = 0; i < dependentAssets.Length; i++) + { + TMP_FontAsset fontAsset = AssetDatabase.LoadAssetAtPath(dependentAssets[i]); + if (fontAsset != null) + return fontAsset; + } + + return null; + } + + + private static string GetPackageRelativePath() + { + // Check for potential UPM package + string packagePath = Path.GetFullPath("Packages/com.unity.textmeshpro"); + if (Directory.Exists(packagePath)) + { + return "Packages/com.unity.textmeshpro"; + } + + packagePath = Path.GetFullPath("Assets/.."); + if (Directory.Exists(packagePath)) + { + // Search default location for development package + if (Directory.Exists(packagePath + "/Assets/Packages/com.unity.TextMeshPro/Editor Resources")) + { + return "Assets/Packages/com.unity.TextMeshPro"; + } + + // Search for default location of normal TextMesh Pro AssetStore package + if (Directory.Exists(packagePath + "/Assets/TextMesh Pro/Editor Resources")) + { + return "Assets/TextMesh Pro"; + } + + // Search for potential alternative locations in the user project + string[] matchingPaths = Directory.GetDirectories(packagePath, "TextMesh Pro", SearchOption.AllDirectories); + packagePath = ValidateLocation(matchingPaths, packagePath); + if (packagePath != null) return packagePath; + } + + return null; + } + + private static string GetPackageFullPath() + { + // Check for potential UPM package + string packagePath = Path.GetFullPath("Packages/com.unity.textmeshpro"); + if (Directory.Exists(packagePath)) + { + return packagePath; + } + + packagePath = Path.GetFullPath("Assets/.."); + if (Directory.Exists(packagePath)) + { + // Search default location for development package + if (Directory.Exists(packagePath + "/Assets/Packages/com.unity.TextMeshPro/Editor Resources")) + { + return packagePath + "/Assets/Packages/com.unity.TextMeshPro"; + } + + // Search for default location of normal TextMesh Pro AssetStore package + if (Directory.Exists(packagePath + "/Assets/TextMesh Pro/Editor Resources")) + { + return packagePath + "/Assets/TextMesh Pro"; + } + + // Search for potential alternative locations in the user project + string[] matchingPaths = Directory.GetDirectories(packagePath, "TextMesh Pro", SearchOption.AllDirectories); + string path = ValidateLocation(matchingPaths, packagePath); + if (path != null) return packagePath + path; + } + + return null; + } + + + /// + /// Method to validate the location of the asset folder by making sure the GUISkins folder exists. + /// + /// + /// + private static string ValidateLocation(string[] paths, string projectPath) + { + for (int i = 0; i < paths.Length; i++) + { + // Check if any of the matching directories contain a GUISkins directory. + if (Directory.Exists(paths[i] + "/Editor Resources")) + { + folderPath = paths[i].Replace(projectPath, ""); + folderPath = folderPath.TrimStart('\\', '/'); + return folderPath; + } + } + + return null; + } + + + /// + /// Function which returns a string containing a sequence of Decimal character ranges. + /// + /// + /// + public static string GetDecimalCharacterSequence(int[] characterSet) + { + if (characterSet == null || characterSet.Length == 0) + return string.Empty; + + string characterSequence = string.Empty; + int count = characterSet.Length; + int first = characterSet[0]; + int last = first; + + for (int i = 1; i < count; i++) + { + if (characterSet[i - 1] + 1 == characterSet[i]) + { + last = characterSet[i]; + } + else + { + if (first == last) + characterSequence += first + ","; + else + characterSequence += first + "-" + last + ","; + + first = last = characterSet[i]; + } + + } + + // handle the final group + if (first == last) + characterSequence += first; + else + characterSequence += first + "-" + last; + + return characterSequence; + } + + + /// + /// Function which returns a string containing a sequence of Unicode (Hex) character ranges. + /// + /// + /// + public static string GetUnicodeCharacterSequence(int[] characterSet) + { + if (characterSet == null || characterSet.Length == 0) + return string.Empty; + + string characterSequence = string.Empty; + int count = characterSet.Length; + int first = characterSet[0]; + int last = first; + + for (int i = 1; i < count; i++) + { + if (characterSet[i - 1] + 1 == characterSet[i]) + { + last = characterSet[i]; + } + else + { + if (first == last) + characterSequence += first.ToString("X2") + ","; + else + characterSequence += first.ToString("X2") + "-" + last.ToString("X2") + ","; + + first = last = characterSet[i]; + } + + } + + // handle the final group + if (first == last) + characterSequence += first.ToString("X2"); + else + characterSequence += first.ToString("X2") + "-" + last.ToString("X2"); + + return characterSequence; + } + + + /// + /// + /// + /// + /// + /// + public static void DrawBox(Rect rect, float thickness, Color color) + { + EditorGUI.DrawRect(new Rect(rect.x - thickness, rect.y + thickness, rect.width + thickness * 2, thickness), color); + EditorGUI.DrawRect(new Rect(rect.x - thickness, rect.y + thickness, thickness, rect.height - thickness * 2), color); + EditorGUI.DrawRect(new Rect(rect.x - thickness, rect.y + rect.height - thickness * 2, rect.width + thickness * 2, thickness), color); + EditorGUI.DrawRect(new Rect(rect.x + rect.width, rect.y + thickness, thickness, rect.height - thickness * 2), color); + } + + + /// + /// Function to return the horizontal alignment grid value. + /// + /// + /// + public static int GetHorizontalAlignmentGridValue(int value) + { + if ((value & 0x1) == 0x1) + return 0; + else if ((value & 0x2) == 0x2) + return 1; + else if ((value & 0x4) == 0x4) + return 2; + else if ((value & 0x8) == 0x8) + return 3; + else if ((value & 0x10) == 0x10) + return 4; + else if ((value & 0x20) == 0x20) + return 5; + + return 0; + } + + /// + /// Function to return the vertical alignment grid value. + /// + /// + /// + public static int GetVerticalAlignmentGridValue(int value) + { + if ((value & 0x100) == 0x100) + return 0; + if ((value & 0x200) == 0x200) + return 1; + if ((value & 0x400) == 0x400) + return 2; + if ((value & 0x800) == 0x800) + return 3; + if ((value & 0x1000) == 0x1000) + return 4; + if ((value & 0x2000) == 0x2000) + return 5; + + return 0; + } + + public static void DrawColorProperty(Rect rect, SerializedProperty property) + { + int oldIndent = EditorGUI.indentLevel; + EditorGUI.indentLevel = 0; + if (EditorGUIUtility.wideMode) + { + EditorGUI.PropertyField(new Rect(rect.x, rect.y, 50f, rect.height), property, GUIContent.none); + rect.x += 50f; + rect.width = Mathf.Min(100f, rect.width - 55f); + } + else + { + rect.height /= 2f; + rect.width = Mathf.Min(100f, rect.width - 5f); + EditorGUI.PropertyField(rect, property, GUIContent.none); + rect.y += rect.height; + } + + EditorGUI.BeginChangeCheck(); + string colorString = EditorGUI.TextField(rect, string.Format("#{0}", ColorUtility.ToHtmlStringRGBA(property.colorValue))); + if (EditorGUI.EndChangeCheck()) + { + if (ColorUtility.TryParseHtmlString(colorString, out Color color)) + { + property.colorValue = color; + } + } + EditorGUI.indentLevel = oldIndent; + } + + public static bool EditorToggle(Rect position, bool value, GUIContent content, GUIStyle style) + { + var id = GUIUtility.GetControlID(content, FocusType.Keyboard, position); + var evt = Event.current; + + // Toggle selected toggle on space or return key + if (GUIUtility.keyboardControl == id && evt.type == EventType.KeyDown && (evt.keyCode == KeyCode.Space || evt.keyCode == KeyCode.Return || evt.keyCode == KeyCode.KeypadEnter)) + { + value = !value; + evt.Use(); + GUI.changed = true; + } + + if (evt.type == EventType.MouseDown && position.Contains(Event.current.mousePosition)) + { + GUIUtility.keyboardControl = id; + EditorGUIUtility.editingTextField = false; + HandleUtility.Repaint(); + } + + return GUI.Toggle(position, id, value, content, style); + } + + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_FontAssetEditor.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_FontAssetEditor.cs new file mode 100644 index 00000000..0e445262 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_FontAssetEditor.cs @@ -0,0 +1,1711 @@ +using UnityEngine; +using UnityEditor; +using UnityEditorInternal; +using System.Collections; +using System.Collections.Generic; +using UnityEngine.TextCore; +using UnityEngine.TextCore.LowLevel; + + +namespace TMPro.EditorUtilities +{ + + [CustomPropertyDrawer(typeof(TMP_FontWeightPair))] + public class FontWeightDrawer : PropertyDrawer + { + public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) + { + SerializedProperty prop_regular = property.FindPropertyRelative("regularTypeface"); + SerializedProperty prop_italic = property.FindPropertyRelative("italicTypeface"); + + float width = position.width; + + position.width = EditorGUIUtility.labelWidth; + EditorGUI.LabelField(position, label); + + int oldIndent = EditorGUI.indentLevel; + EditorGUI.indentLevel = 0; + + // NORMAL TYPEFACE + if (label.text[0] == '4') GUI.enabled = false; + position.x += position.width; position.width = (width - position.width) / 2; + EditorGUI.PropertyField(position, prop_regular, GUIContent.none); + + // ITALIC TYPEFACE + GUI.enabled = true; + position.x += position.width; + EditorGUI.PropertyField(position, prop_italic, GUIContent.none); + + EditorGUI.indentLevel = oldIndent; + } + } + + [CustomEditor(typeof(TMP_FontAsset))] + public class TMP_FontAssetEditor : Editor + { + private struct UI_PanelState + { + public static bool faceInfoPanel = true; + public static bool generationSettingsPanel = true; + public static bool fontAtlasInfoPanel = true; + public static bool fontWeightPanel = true; + public static bool fallbackFontAssetPanel = true; + public static bool glyphTablePanel = false; + public static bool characterTablePanel = false; + public static bool fontFeatureTablePanel = false; + } + + private struct AtlasSettings + { + public GlyphRenderMode glyphRenderMode; + public int pointSize; + public int padding; + public int atlasWidth; + public int atlasHeight; + } + + /// + /// Material used to display SDF glyphs in the Character and Glyph tables. + /// + internal static Material internalSDFMaterial + { + get + { + if (s_InternalSDFMaterial == null) + { + Shader shader = Shader.Find("Hidden/TextMeshPro/Internal/Distance Field SSD"); + + if (shader != null) + s_InternalSDFMaterial = new Material(shader); + } + + return s_InternalSDFMaterial; + } + } + static Material s_InternalSDFMaterial; + + /// + /// Material used to display Bitmap glyphs in the Character and Glyph tables. + /// + internal static Material internalBitmapMaterial + { + get + { + if (s_InternalBitmapMaterial == null) + { + Shader shader = Shader.Find("Hidden/Internal-GUITextureClipText"); + + if (shader != null) + s_InternalBitmapMaterial = new Material(shader); + } + + return s_InternalBitmapMaterial; + } + } + static Material s_InternalBitmapMaterial; + + private static string[] s_UiStateLabel = new string[] { "(Click to collapse) ", "(Click to expand) " }; + private GUIContent[] m_AtlasResolutionLabels = { new GUIContent("8"), new GUIContent("16"), new GUIContent("32"), new GUIContent("64"), new GUIContent("128"), new GUIContent("256"), new GUIContent("512"), new GUIContent("1024"), new GUIContent("2048"), new GUIContent("4096"), new GUIContent("8192") }; + private int[] m_AtlasResolutions = { 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192 }; + + private struct Warning + { + public bool isEnabled; + public double expirationTime; + } + + private int m_CurrentGlyphPage = 0; + private int m_CurrentCharacterPage = 0; + private int m_CurrentKerningPage = 0; + + private int m_SelectedGlyphRecord = -1; + private int m_SelectedCharacterRecord = -1; + private int m_SelectedAdjustmentRecord = -1; + + private string m_dstGlyphID; + private string m_dstUnicode; + private const string k_placeholderUnicodeHex = "New Unicode (Hex)"; + private string m_unicodeHexLabel = k_placeholderUnicodeHex; + private const string k_placeholderGlyphID = "New Glyph ID"; + private string m_GlyphIDLabel = k_placeholderGlyphID; + + private Warning m_AddGlyphWarning; + private Warning m_AddCharacterWarning; + private bool m_DisplayDestructiveChangeWarning; + private AtlasSettings m_AtlasSettings; + private bool m_MaterialPresetsRequireUpdate; + + private string m_GlyphSearchPattern; + private List m_GlyphSearchList; + + private string m_CharacterSearchPattern; + private List m_CharacterSearchList; + + private string m_KerningTableSearchPattern; + private List m_KerningTableSearchList; + + private bool m_isSearchDirty; + + private const string k_UndoRedo = "UndoRedoPerformed"; + + private SerializedProperty m_AtlasPopulationMode_prop; + private SerializedProperty font_atlas_prop; + private SerializedProperty font_material_prop; + + private SerializedProperty m_AtlasRenderMode_prop; + private SerializedProperty m_SamplingPointSize_prop; + private SerializedProperty m_AtlasPadding_prop; + private SerializedProperty m_AtlasWidth_prop; + private SerializedProperty m_AtlasHeight_prop; + + private SerializedProperty fontWeights_prop; + + //private SerializedProperty fallbackFontAssets_prop; + private ReorderableList m_list; + + private SerializedProperty font_normalStyle_prop; + private SerializedProperty font_normalSpacing_prop; + + private SerializedProperty font_boldStyle_prop; + private SerializedProperty font_boldSpacing_prop; + + private SerializedProperty font_italicStyle_prop; + private SerializedProperty font_tabSize_prop; + + private SerializedProperty m_FaceInfo_prop; + private SerializedProperty m_GlyphTable_prop; + private SerializedProperty m_CharacterTable_prop; + + private TMP_FontFeatureTable m_FontFeatureTable; + private SerializedProperty m_FontFeatureTable_prop; + private SerializedProperty m_GlyphPairAdjustmentRecords_prop; + + private TMP_SerializedPropertyHolder m_SerializedPropertyHolder; + private SerializedProperty m_EmptyGlyphPairAdjustmentRecord_prop; + + private TMP_FontAsset m_fontAsset; + + private Material[] m_materialPresets; + + private bool isAssetDirty = false; + + private int errorCode; + + private System.DateTime timeStamp; + + + public void OnEnable() + { + m_FaceInfo_prop = serializedObject.FindProperty("m_FaceInfo"); + + font_atlas_prop = serializedObject.FindProperty("m_AtlasTextures").GetArrayElementAtIndex(0); + font_material_prop = serializedObject.FindProperty("material"); + + m_AtlasPopulationMode_prop = serializedObject.FindProperty("m_AtlasPopulationMode"); + m_AtlasRenderMode_prop = serializedObject.FindProperty("m_AtlasRenderMode"); + m_SamplingPointSize_prop = m_FaceInfo_prop.FindPropertyRelative("m_PointSize"); + m_AtlasPadding_prop = serializedObject.FindProperty("m_AtlasPadding"); + m_AtlasWidth_prop = serializedObject.FindProperty("m_AtlasWidth"); + m_AtlasHeight_prop = serializedObject.FindProperty("m_AtlasHeight"); + + fontWeights_prop = serializedObject.FindProperty("m_FontWeightTable"); + + m_list = new ReorderableList(serializedObject, serializedObject.FindProperty("m_FallbackFontAssetTable"), true, true, true, true); + + m_list.drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) => + { + var element = m_list.serializedProperty.GetArrayElementAtIndex(index); + rect.y += 2; + EditorGUI.PropertyField(new Rect(rect.x, rect.y, rect.width, EditorGUIUtility.singleLineHeight), element, GUIContent.none); + }; + + m_list.drawHeaderCallback = rect => + { + EditorGUI.LabelField(rect, "Fallback List"); + }; + + // Clean up fallback list in the event if contains null elements. + CleanFallbackFontAssetTable(); + + font_normalStyle_prop = serializedObject.FindProperty("normalStyle"); + font_normalSpacing_prop = serializedObject.FindProperty("normalSpacingOffset"); + + font_boldStyle_prop = serializedObject.FindProperty("boldStyle"); + font_boldSpacing_prop = serializedObject.FindProperty("boldSpacing"); + + font_italicStyle_prop = serializedObject.FindProperty("italicStyle"); + font_tabSize_prop = serializedObject.FindProperty("tabSize"); + + m_CharacterTable_prop = serializedObject.FindProperty("m_CharacterTable"); + m_GlyphTable_prop = serializedObject.FindProperty("m_GlyphTable"); + + m_FontFeatureTable_prop = serializedObject.FindProperty("m_FontFeatureTable"); + m_GlyphPairAdjustmentRecords_prop = m_FontFeatureTable_prop.FindPropertyRelative("m_GlyphPairAdjustmentRecords"); + + m_fontAsset = target as TMP_FontAsset; + m_FontFeatureTable = m_fontAsset.fontFeatureTable; + + // Upgrade Font Feature Table if necessary + if (m_fontAsset.m_KerningTable != null && m_fontAsset.m_KerningTable.kerningPairs != null && m_fontAsset.m_KerningTable.kerningPairs.Count > 0) + m_fontAsset.ReadFontAssetDefinition(); + + // Create serialized object to allow us to use a serialized property of an empty kerning pair. + m_SerializedPropertyHolder = CreateInstance(); + m_SerializedPropertyHolder.fontAsset = m_fontAsset; + SerializedObject internalSerializedObject = new SerializedObject(m_SerializedPropertyHolder); + m_EmptyGlyphPairAdjustmentRecord_prop = internalSerializedObject.FindProperty("glyphPairAdjustmentRecord"); + + m_materialPresets = TMP_EditorUtility.FindMaterialReferences(m_fontAsset); + + m_GlyphSearchList = new List(); + m_KerningTableSearchList = new List(); + } + + + public void OnDisable() + { + // Revert changes if user closes or changes selection without having made a choice. + if (m_DisplayDestructiveChangeWarning) + { + m_DisplayDestructiveChangeWarning = false; + RestoreAtlasGenerationSettings(); + GUIUtility.keyboardControl = 0; + + serializedObject.ApplyModifiedProperties(); + } + } + + + public override void OnInspectorGUI() + { + //Debug.Log("OnInspectorGUI Called."); + + Event currentEvent = Event.current; + + serializedObject.Update(); + + Rect rect = EditorGUILayout.GetControlRect(false, 24); + float labelWidth = EditorGUIUtility.labelWidth; + float fieldWidth = EditorGUIUtility.fieldWidth; + + // FACE INFO PANEL + #region Face info + GUI.Label(rect, new GUIContent("Face Info - v" + m_fontAsset.version), TMP_UIStyleManager.sectionHeader); + + rect.x += rect.width - 132f; + rect.y += 2; + rect.width = 130f; + rect.height = 18f; + if (GUI.Button(rect, new GUIContent("Update Atlas Texture"))) + { + TMPro_FontAssetCreatorWindow.ShowFontAtlasCreatorWindow(target as TMP_FontAsset); + } + + EditorGUI.indentLevel = 1; + GUI.enabled = false; // Lock UI + + // TODO : Consider creating a property drawer for these. + EditorGUILayout.PropertyField(m_FaceInfo_prop.FindPropertyRelative("m_FamilyName")); + EditorGUILayout.PropertyField(m_FaceInfo_prop.FindPropertyRelative("m_StyleName")); + EditorGUILayout.PropertyField(m_FaceInfo_prop.FindPropertyRelative("m_PointSize")); + + GUI.enabled = true; + + EditorGUILayout.PropertyField(m_FaceInfo_prop.FindPropertyRelative("m_Scale")); + EditorGUILayout.PropertyField(m_FaceInfo_prop.FindPropertyRelative("m_LineHeight")); + + EditorGUILayout.PropertyField(m_FaceInfo_prop.FindPropertyRelative("m_AscentLine")); + EditorGUILayout.PropertyField(m_FaceInfo_prop.FindPropertyRelative("m_CapLine")); + EditorGUILayout.PropertyField(m_FaceInfo_prop.FindPropertyRelative("m_MeanLine")); + EditorGUILayout.PropertyField(m_FaceInfo_prop.FindPropertyRelative("m_Baseline")); + EditorGUILayout.PropertyField(m_FaceInfo_prop.FindPropertyRelative("m_DescentLine")); + EditorGUILayout.PropertyField(m_FaceInfo_prop.FindPropertyRelative("m_UnderlineOffset")); + EditorGUILayout.PropertyField(m_FaceInfo_prop.FindPropertyRelative("m_UnderlineThickness")); + EditorGUILayout.PropertyField(m_FaceInfo_prop.FindPropertyRelative("m_StrikethroughOffset")); + //EditorGUILayout.PropertyField(m_FaceInfo_prop.FindPropertyRelative("strikethroughThickness")); + EditorGUILayout.PropertyField(m_FaceInfo_prop.FindPropertyRelative("m_SuperscriptOffset")); + EditorGUILayout.PropertyField(m_FaceInfo_prop.FindPropertyRelative("m_SuperscriptSize")); + EditorGUILayout.PropertyField(m_FaceInfo_prop.FindPropertyRelative("m_SubscriptOffset")); + EditorGUILayout.PropertyField(m_FaceInfo_prop.FindPropertyRelative("m_SubscriptSize")); + EditorGUILayout.PropertyField(m_FaceInfo_prop.FindPropertyRelative("m_TabWidth")); + // TODO : Add clamping for some of these values. + //subSize_prop.floatValue = Mathf.Clamp(subSize_prop.floatValue, 0.25f, 1f); + + EditorGUILayout.Space(); + #endregion + + // GENERATION SETTINGS + #region Generation Settings + rect = EditorGUILayout.GetControlRect(false, 24); + + if (GUI.Button(rect, new GUIContent("Generation Settings"), TMP_UIStyleManager.sectionHeader)) + UI_PanelState.generationSettingsPanel = !UI_PanelState.generationSettingsPanel; + + GUI.Label(rect, (UI_PanelState.generationSettingsPanel ? "" : s_UiStateLabel[1]), TMP_UIStyleManager.rightLabel); + + if (UI_PanelState.generationSettingsPanel) + { + EditorGUI.indentLevel = 1; + + EditorGUI.BeginChangeCheck(); + Font sourceFont = (Font)EditorGUILayout.ObjectField("Source Font File", m_fontAsset.m_SourceFontFile_EditorRef, typeof(Font), false); + if (EditorGUI.EndChangeCheck()) + { + string guid = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(sourceFont)); + m_fontAsset.m_SourceFontFileGUID = guid; + m_fontAsset.m_SourceFontFile_EditorRef = sourceFont; + } + + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(m_AtlasPopulationMode_prop, new GUIContent("Atlas Population Mode")); + if (EditorGUI.EndChangeCheck()) + { + serializedObject.ApplyModifiedProperties(); + + bool isDatabaseRefreshRequired = false; + + if (m_AtlasPopulationMode_prop.intValue == 0) + { + m_fontAsset.sourceFontFile = null; + + // Set atlas textures to non readable. + //for (int i = 0; i < m_fontAsset.atlasTextures.Length; i++) + //{ + // Texture2D tex = m_fontAsset.atlasTextures[i]; + + // if (tex != null && tex.isReadable) + // { + // string texPath = AssetDatabase.GetAssetPath(tex); + // var texImporter = AssetImporter.GetAtPath(texPath) as TextureImporter; + // if (texImporter != null) + // { + // texImporter.isReadable = false; + // AssetDatabase.ImportAsset(texPath); + // isDatabaseRefreshRequired = true; + // } + // } + //} + + Debug.Log("Atlas Population mode set to [Static]."); + } + else if (m_AtlasPopulationMode_prop.intValue == 1) + { + if (m_fontAsset.m_SourceFontFile_EditorRef.dynamic == false) + { + Debug.LogWarning("Please set the [" + m_fontAsset.name + "] font to dynamic mode as this is required for Dynamic SDF support.", m_fontAsset.m_SourceFontFile_EditorRef); + m_AtlasPopulationMode_prop.intValue = 0; + + serializedObject.ApplyModifiedProperties(); + } + else + { + m_fontAsset.sourceFontFile = m_fontAsset.m_SourceFontFile_EditorRef; + + /* + // Set atlas textures to non readable. + for (int i = 0; i < m_fontAsset.atlasTextures.Length; i++) + { + Texture2D tex = m_fontAsset.atlasTextures[i]; + + if (tex != null && tex.isReadable == false) + { + string texPath = AssetDatabase.GetAssetPath(tex.GetInstanceID()); + Object[] paths = AssetDatabase.LoadAllAssetsAtPath(texPath); + var texImporter = AssetImporter.GetAtPath(texPath) as TextureImporter; + if (texImporter != null) + { + texImporter.isReadable = true; + AssetDatabase.ImportAsset(texPath); + isDatabaseRefreshRequired = true; + } + } + } + */ + Debug.Log("Atlas Population mode set to [Dynamic]."); + } + } + + if (isDatabaseRefreshRequired) + AssetDatabase.Refresh(); + + serializedObject.Update(); + isAssetDirty = true; + } + + GUI.enabled = true; + // Save state of atlas settings + if (m_DisplayDestructiveChangeWarning == false) + { + SavedAtlasGenerationSettings(); + //Undo.RegisterCompleteObjectUndo(m_fontAsset, "Font Asset Changes"); + } + + EditorGUI.BeginChangeCheck(); + // TODO: Switch shaders depending on GlyphRenderMode. + EditorGUILayout.PropertyField(m_AtlasRenderMode_prop); + EditorGUILayout.PropertyField(m_SamplingPointSize_prop, new GUIContent("Sampling Point Size")); + if (EditorGUI.EndChangeCheck()) + { + m_DisplayDestructiveChangeWarning = true; + } + + // Changes to these properties require updating Material Presets for this font asset. + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(m_AtlasPadding_prop, new GUIContent("Padding")); + EditorGUILayout.IntPopup(m_AtlasWidth_prop, m_AtlasResolutionLabels, m_AtlasResolutions, new GUIContent("Atlas Width")); + EditorGUILayout.IntPopup(m_AtlasHeight_prop, m_AtlasResolutionLabels, m_AtlasResolutions, new GUIContent("Atlas Height")); + if (EditorGUI.EndChangeCheck()) + { + m_MaterialPresetsRequireUpdate = true; + m_DisplayDestructiveChangeWarning = true; + } + + if (m_DisplayDestructiveChangeWarning) + { + // These changes are destructive on the font asset + rect = EditorGUILayout.GetControlRect(false, 60); + rect.x += 15; + rect.width -= 15; + EditorGUI.HelpBox(rect, "Changing these settings will clear the font asset's character, glyph and texture data.", MessageType.Warning); + + if (GUI.Button(new Rect(rect.width - 140, rect.y + 36, 80, 18), new GUIContent("Apply"))) + { + m_DisplayDestructiveChangeWarning = false; + + // Update face info is sampling point size was changed. + if (m_AtlasSettings.pointSize != m_SamplingPointSize_prop.intValue) + { + FontEngine.LoadFontFace(m_fontAsset.sourceFontFile, m_SamplingPointSize_prop.intValue); + m_fontAsset.faceInfo = FontEngine.GetFaceInfo(); + } + + // Update material + m_fontAsset.material.SetFloat(ShaderUtilities.ID_TextureWidth, m_AtlasWidth_prop.intValue); + m_fontAsset.material.SetFloat(ShaderUtilities.ID_TextureHeight, m_AtlasHeight_prop.intValue); + m_fontAsset.material.SetFloat(ShaderUtilities.ID_GradientScale, m_AtlasPadding_prop.intValue + 1); + + // Update material presets if any of the relevant properties have been changed. + if (m_MaterialPresetsRequireUpdate) + { + m_MaterialPresetsRequireUpdate = false; + + Material[] materialPresets = TMP_EditorUtility.FindMaterialReferences(m_fontAsset); + for (int i = 0; i < materialPresets.Length; i++) + { + Material mat = materialPresets[i]; + + mat.SetFloat(ShaderUtilities.ID_TextureWidth, m_AtlasWidth_prop.intValue); + mat.SetFloat(ShaderUtilities.ID_TextureHeight, m_AtlasHeight_prop.intValue); + mat.SetFloat(ShaderUtilities.ID_GradientScale, m_AtlasPadding_prop.intValue + 1); + } + } + + m_fontAsset.ClearFontAssetData(); + GUIUtility.keyboardControl = 0; + isAssetDirty = true; + + // Update Font Asset Creation Settings to reflect new changes. + UpdateFontAssetCreationSettings(); + + // TODO: Clear undo buffers. + //Undo.ClearUndo(m_fontAsset); + } + + if (GUI.Button(new Rect(rect.width - 56, rect.y + 36, 80, 18), new GUIContent("Revert"))) + { + m_DisplayDestructiveChangeWarning = false; + RestoreAtlasGenerationSettings(); + GUIUtility.keyboardControl = 0; + + // TODO: Clear undo buffers. + //Undo.ClearUndo(m_fontAsset); + } + } + EditorGUILayout.Space(); + } + #endregion + + // ATLAS & MATERIAL PANEL + #region Atlas & Material + rect = EditorGUILayout.GetControlRect(false, 24); + + if (GUI.Button(rect, new GUIContent("Atlas & Material"), TMP_UIStyleManager.sectionHeader)) + UI_PanelState.fontAtlasInfoPanel = !UI_PanelState.fontAtlasInfoPanel; + + GUI.Label(rect, (UI_PanelState.fontAtlasInfoPanel ? "" : s_UiStateLabel[1]), TMP_UIStyleManager.rightLabel); + + if (UI_PanelState.fontAtlasInfoPanel) + { + EditorGUI.indentLevel = 1; + + GUI.enabled = false; + EditorGUILayout.PropertyField(font_atlas_prop, new GUIContent("Font Atlas")); + EditorGUILayout.PropertyField(font_material_prop, new GUIContent("Font Material")); + GUI.enabled = true; + EditorGUILayout.Space(); + } + #endregion + + string evt_cmd = Event.current.commandName; // Get Current Event CommandName to check for Undo Events + + // FONT WEIGHT PANEL + #region Font Weights + rect = EditorGUILayout.GetControlRect(false, 24); + + if (GUI.Button(rect, new GUIContent("Font Weights", "The Font Assets that will be used for different font weights and the settings used to simulate a typeface when no asset is available."), TMP_UIStyleManager.sectionHeader)) + UI_PanelState.fontWeightPanel = !UI_PanelState.fontWeightPanel; + + GUI.Label(rect, (UI_PanelState.fontWeightPanel ? "" : s_UiStateLabel[1]), TMP_UIStyleManager.rightLabel); + + if (UI_PanelState.fontWeightPanel) + { + EditorGUIUtility.labelWidth *= 0.75f; + EditorGUIUtility.fieldWidth *= 0.25f; + + EditorGUILayout.BeginVertical(); + EditorGUI.indentLevel = 1; + rect = EditorGUILayout.GetControlRect(true); + rect.x += EditorGUIUtility.labelWidth; + rect.width = (rect.width - EditorGUIUtility.labelWidth) / 2f; + GUI.Label(rect, "Regular Tyepface", EditorStyles.label); + rect.x += rect.width; + GUI.Label(rect, "Italic Typeface", EditorStyles.label); + + EditorGUI.indentLevel = 1; + + EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(1), new GUIContent("100 - Thin")); + EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(2), new GUIContent("200 - Extra-Light")); + EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(3), new GUIContent("300 - Light")); + EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(4), new GUIContent("400 - Regular")); + EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(5), new GUIContent("500 - Medium")); + EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(6), new GUIContent("600 - Semi-Bold")); + EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(7), new GUIContent("700 - Bold")); + EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(8), new GUIContent("800 - Heavy")); + EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(9), new GUIContent("900 - Black")); + + EditorGUILayout.EndVertical(); + + EditorGUILayout.Space(); + + EditorGUILayout.BeginVertical(); + + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.PropertyField(font_normalStyle_prop, new GUIContent("Normal Weight")); + font_normalStyle_prop.floatValue = Mathf.Clamp(font_normalStyle_prop.floatValue, -3.0f, 3.0f); + if (GUI.changed || evt_cmd == k_UndoRedo) + { + GUI.changed = false; + + // Modify the material property on matching material presets. + for (int i = 0; i < m_materialPresets.Length; i++) + m_materialPresets[i].SetFloat("_WeightNormal", font_normalStyle_prop.floatValue); + } + + EditorGUILayout.PropertyField(font_boldStyle_prop, new GUIContent("Bold Weight")); + font_boldStyle_prop.floatValue = Mathf.Clamp(font_boldStyle_prop.floatValue, -3.0f, 3.0f); + if (GUI.changed || evt_cmd == k_UndoRedo) + { + GUI.changed = false; + + // Modify the material property on matching material presets. + for (int i = 0; i < m_materialPresets.Length; i++) + m_materialPresets[i].SetFloat("_WeightBold", font_boldStyle_prop.floatValue); + } + EditorGUILayout.EndHorizontal(); + + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.PropertyField(font_normalSpacing_prop, new GUIContent("Spacing Offset")); + font_normalSpacing_prop.floatValue = Mathf.Clamp(font_normalSpacing_prop.floatValue, -100, 100); + if (GUI.changed || evt_cmd == k_UndoRedo) + { + GUI.changed = false; + } + + EditorGUILayout.PropertyField(font_boldSpacing_prop, new GUIContent("Bold Spacing")); + font_boldSpacing_prop.floatValue = Mathf.Clamp(font_boldSpacing_prop.floatValue, 0, 100); + if (GUI.changed || evt_cmd == k_UndoRedo) + { + GUI.changed = false; + } + EditorGUILayout.EndHorizontal(); + + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.PropertyField(font_italicStyle_prop, new GUIContent("Italic Style")); + font_italicStyle_prop.intValue = Mathf.Clamp(font_italicStyle_prop.intValue, 15, 60); + + EditorGUILayout.PropertyField(font_tabSize_prop, new GUIContent("Tab Multiple")); + EditorGUILayout.EndHorizontal(); + EditorGUILayout.EndVertical(); + EditorGUILayout.Space(); + } + + EditorGUIUtility.labelWidth = 0; + EditorGUIUtility.fieldWidth = 0; + #endregion + + // FALLBACK FONT ASSETS + #region Fallback Font Asset + rect = EditorGUILayout.GetControlRect(false, 24); + EditorGUI.indentLevel = 0; + if (GUI.Button(rect, new GUIContent("Fallback Font Assets", "Select the Font Assets that will be searched and used as fallback when characters are missing from this font asset."), TMP_UIStyleManager.sectionHeader)) + UI_PanelState.fallbackFontAssetPanel = !UI_PanelState.fallbackFontAssetPanel; + + GUI.Label(rect, (UI_PanelState.fallbackFontAssetPanel ? "" : s_UiStateLabel[1]), TMP_UIStyleManager.rightLabel); + + if (UI_PanelState.fallbackFontAssetPanel) + { + EditorGUIUtility.labelWidth = 120; + EditorGUI.indentLevel = 0; + + m_list.DoLayoutList(); + EditorGUILayout.Space(); + } + #endregion + + // CHARACTER TABLE TABLE + #region Character Table + EditorGUIUtility.labelWidth = labelWidth; + EditorGUIUtility.fieldWidth = fieldWidth; + EditorGUI.indentLevel = 0; + rect = EditorGUILayout.GetControlRect(false, 24); + + if (GUI.Button(rect, new GUIContent("Character Table", "List of characters contained in this font asset."), TMP_UIStyleManager.sectionHeader)) + UI_PanelState.characterTablePanel = !UI_PanelState.characterTablePanel; + + GUI.Label(rect, (UI_PanelState.characterTablePanel ? "" : s_UiStateLabel[1]), TMP_UIStyleManager.rightLabel); + + if (UI_PanelState.characterTablePanel) + { + int arraySize = m_CharacterTable_prop.arraySize; + int itemsPerPage = 15; + + // Display Glyph Management Tools + EditorGUILayout.BeginVertical(EditorStyles.helpBox); + { + // Search Bar implementation + #region DISPLAY SEARCH BAR + EditorGUILayout.BeginHorizontal(); + { + EditorGUIUtility.labelWidth = 130f; + EditorGUI.BeginChangeCheck(); + string searchPattern = EditorGUILayout.TextField("Character Search", m_CharacterSearchPattern, "SearchTextField"); + if (EditorGUI.EndChangeCheck() || m_isSearchDirty) + { + if (string.IsNullOrEmpty(searchPattern) == false) + { + m_CharacterSearchPattern = searchPattern; + + // Search Character Table for potential matches + SearchCharacterTable (m_CharacterSearchPattern, ref m_CharacterSearchList); + } + else + m_CharacterSearchPattern = null; + + m_isSearchDirty = false; + } + + string styleName = string.IsNullOrEmpty(m_CharacterSearchPattern) ? "SearchCancelButtonEmpty" : "SearchCancelButton"; + if (GUILayout.Button(GUIContent.none, styleName)) + { + GUIUtility.keyboardControl = 0; + m_CharacterSearchPattern = string.Empty; + } + } + EditorGUILayout.EndHorizontal(); + #endregion + + // Display Page Navigation + if (!string.IsNullOrEmpty(m_CharacterSearchPattern)) + arraySize = m_CharacterSearchList.Count; + + DisplayPageNavigation(ref m_CurrentCharacterPage, arraySize, itemsPerPage); + } + EditorGUILayout.EndVertical(); + + // Display Character Table Elements + if (arraySize > 0) + { + // Display each character entry using the CharacterPropertyDrawer. + for (int i = itemsPerPage * m_CurrentCharacterPage; i < arraySize && i < itemsPerPage * (m_CurrentCharacterPage + 1); i++) + { + // Define the start of the selection region of the element. + Rect elementStartRegion = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true)); + + int elementIndex = i; + if (!string.IsNullOrEmpty(m_CharacterSearchPattern)) + elementIndex = m_CharacterSearchList[i]; + + SerializedProperty characterProperty = m_CharacterTable_prop.GetArrayElementAtIndex(elementIndex); + + EditorGUILayout.BeginVertical(EditorStyles.helpBox); + + EditorGUI.BeginDisabledGroup(i != m_SelectedCharacterRecord); + { + EditorGUILayout.PropertyField(characterProperty); + } + EditorGUI.EndDisabledGroup(); + + EditorGUILayout.EndVertical(); + + // Define the end of the selection region of the element. + Rect elementEndRegion = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true)); + + // Check for Item selection + Rect selectionArea = new Rect(elementStartRegion.x, elementStartRegion.y, elementEndRegion.width, elementEndRegion.y - elementStartRegion.y); + if (DoSelectionCheck(selectionArea)) + { + if (m_SelectedCharacterRecord == i) + m_SelectedCharacterRecord = -1; + else + { + m_SelectedCharacterRecord = i; + m_AddCharacterWarning.isEnabled = false; + m_unicodeHexLabel = k_placeholderUnicodeHex; + GUIUtility.keyboardControl = 0; + } + } + + // Draw Selection Highlight and Glyph Options + if (m_SelectedCharacterRecord == i) + { + TMP_EditorUtility.DrawBox(selectionArea, 2f, new Color32(40, 192, 255, 255)); + + // Draw Glyph management options + Rect controlRect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight * 1f); + float optionAreaWidth = controlRect.width * 0.6f; + float btnWidth = optionAreaWidth / 3; + + Rect position = new Rect(controlRect.x + controlRect.width * .4f, controlRect.y, btnWidth, controlRect.height); + + // Copy Selected Glyph to Target Glyph ID + GUI.enabled = !string.IsNullOrEmpty(m_dstUnicode); + if (GUI.Button(position, new GUIContent("Copy to"))) + { + GUIUtility.keyboardControl = 0; + + // Convert Hex Value to Decimal + int dstGlyphID = TMP_TextUtilities.StringHexToInt(m_dstUnicode); + + //Add new glyph at target Unicode hex id. + if (!AddNewCharacter(elementIndex, dstGlyphID)) + { + m_AddCharacterWarning.isEnabled = true; + m_AddCharacterWarning.expirationTime = EditorApplication.timeSinceStartup + 1; + } + + m_dstUnicode = string.Empty; + m_isSearchDirty = true; + + TMPro_EventManager.ON_FONT_PROPERTY_CHANGED(true, m_fontAsset); + } + + // Target Glyph ID + GUI.enabled = true; + position.x += btnWidth; + + GUI.SetNextControlName("CharacterID_Input"); + m_dstUnicode = EditorGUI.TextField(position, m_dstUnicode); + + // Placeholder text + EditorGUI.LabelField(position, new GUIContent(m_unicodeHexLabel, "The Unicode (Hex) ID of the duplicated Character"), TMP_UIStyleManager.label); + + // Only filter the input when the destination glyph ID text field has focus. + if (GUI.GetNameOfFocusedControl() == "CharacterID_Input") + { + m_unicodeHexLabel = string.Empty; + + //Filter out unwanted characters. + char chr = Event.current.character; + if ((chr < '0' || chr > '9') && (chr < 'a' || chr > 'f') && (chr < 'A' || chr > 'F')) + { + Event.current.character = '\0'; + } + } + else + { + m_unicodeHexLabel = k_placeholderUnicodeHex; + //m_dstUnicode = string.Empty; + } + + + // Remove Glyph + position.x += btnWidth; + if (GUI.Button(position, "Remove")) + { + GUIUtility.keyboardControl = 0; + + RemoveCharacterFromList(elementIndex); + + isAssetDirty = true; + m_SelectedCharacterRecord = -1; + m_isSearchDirty = true; + break; + } + + if (m_AddCharacterWarning.isEnabled && EditorApplication.timeSinceStartup < m_AddCharacterWarning.expirationTime) + { + EditorGUILayout.HelpBox("The Destination Character ID already exists", MessageType.Warning); + } + + } + } + } + + DisplayPageNavigation(ref m_CurrentCharacterPage, arraySize, itemsPerPage); + + EditorGUILayout.Space(); + } + #endregion + + // GLYPH TABLE + #region Glyph Table + EditorGUIUtility.labelWidth = labelWidth; + EditorGUIUtility.fieldWidth = fieldWidth; + EditorGUI.indentLevel = 0; + rect = EditorGUILayout.GetControlRect(false, 24); + + GUIStyle glyphPanelStyle = new GUIStyle(EditorStyles.helpBox); + + if (GUI.Button(rect, new GUIContent("Glyph Table", "List of glyphs contained in this font asset."), TMP_UIStyleManager.sectionHeader)) + UI_PanelState.glyphTablePanel = !UI_PanelState.glyphTablePanel; + + GUI.Label(rect, (UI_PanelState.glyphTablePanel ? "" : s_UiStateLabel[1]), TMP_UIStyleManager.rightLabel); + + if (UI_PanelState.glyphTablePanel) + { + int arraySize = m_GlyphTable_prop.arraySize; + int itemsPerPage = 15; + + // Display Glyph Management Tools + EditorGUILayout.BeginVertical(EditorStyles.helpBox); + { + // Search Bar implementation + #region DISPLAY SEARCH BAR + EditorGUILayout.BeginHorizontal(); + { + EditorGUIUtility.labelWidth = 130f; + EditorGUI.BeginChangeCheck(); + string searchPattern = EditorGUILayout.TextField("Glyph Search", m_GlyphSearchPattern, "SearchTextField"); + if (EditorGUI.EndChangeCheck() || m_isSearchDirty) + { + if (string.IsNullOrEmpty(searchPattern) == false) + { + m_GlyphSearchPattern = searchPattern; + + // Search Glyph Table for potential matches + SearchGlyphTable(m_GlyphSearchPattern, ref m_GlyphSearchList); + } + else + m_GlyphSearchPattern = null; + + m_isSearchDirty = false; + } + + string styleName = string.IsNullOrEmpty(m_GlyphSearchPattern) ? "SearchCancelButtonEmpty" : "SearchCancelButton"; + if (GUILayout.Button(GUIContent.none, styleName)) + { + GUIUtility.keyboardControl = 0; + m_GlyphSearchPattern = string.Empty; + } + } + EditorGUILayout.EndHorizontal(); + #endregion + + // Display Page Navigation + if (!string.IsNullOrEmpty(m_GlyphSearchPattern)) + arraySize = m_GlyphSearchList.Count; + + DisplayPageNavigation(ref m_CurrentGlyphPage, arraySize, itemsPerPage); + } + EditorGUILayout.EndVertical(); + + // Display Glyph Table Elements + + if (arraySize > 0) + { + // Display each GlyphInfo entry using the GlyphInfo property drawer. + for (int i = itemsPerPage * m_CurrentGlyphPage; i < arraySize && i < itemsPerPage * (m_CurrentGlyphPage + 1); i++) + { + // Define the start of the selection region of the element. + Rect elementStartRegion = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true)); + + int elementIndex = i; + if (!string.IsNullOrEmpty(m_GlyphSearchPattern)) + elementIndex = m_GlyphSearchList[i]; + + SerializedProperty glyphProperty = m_GlyphTable_prop.GetArrayElementAtIndex(elementIndex); + + EditorGUILayout.BeginVertical(glyphPanelStyle); + + using (new EditorGUI.DisabledScope(i != m_SelectedGlyphRecord)) + { + EditorGUILayout.PropertyField(glyphProperty); + } + + EditorGUILayout.EndVertical(); + + // Define the end of the selection region of the element. + Rect elementEndRegion = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true)); + + // Check for Item selection + Rect selectionArea = new Rect(elementStartRegion.x, elementStartRegion.y, elementEndRegion.width, elementEndRegion.y - elementStartRegion.y); + if (DoSelectionCheck(selectionArea)) + { + if (m_SelectedGlyphRecord == i) + m_SelectedGlyphRecord = -1; + else + { + m_SelectedGlyphRecord = i; + m_AddGlyphWarning.isEnabled = false; + m_unicodeHexLabel = k_placeholderUnicodeHex; + GUIUtility.keyboardControl = 0; + } + } + + // Draw Selection Highlight and Glyph Options + if (m_SelectedGlyphRecord == i) + { + TMP_EditorUtility.DrawBox(selectionArea, 2f, new Color32(40, 192, 255, 255)); + + // Draw Glyph management options + Rect controlRect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight * 1f); + float optionAreaWidth = controlRect.width * 0.6f; + float btnWidth = optionAreaWidth / 3; + + Rect position = new Rect(controlRect.x + controlRect.width * .4f, controlRect.y, btnWidth, controlRect.height); + + // Copy Selected Glyph to Target Glyph ID + GUI.enabled = !string.IsNullOrEmpty(m_dstGlyphID); + if (GUI.Button(position, new GUIContent("Copy to"))) + { + GUIUtility.keyboardControl = 0; + + // Convert Hex Value to Decimal + int.TryParse(m_dstGlyphID, out int dstGlyphID); + + //Add new glyph at target Unicode hex id. + if (!AddNewGlyph(elementIndex, dstGlyphID)) + { + m_AddGlyphWarning.isEnabled = true; + m_AddGlyphWarning.expirationTime = EditorApplication.timeSinceStartup + 1; + } + + m_dstGlyphID = string.Empty; + m_isSearchDirty = true; + + TMPro_EventManager.ON_FONT_PROPERTY_CHANGED(true, m_fontAsset); + } + + // Target Glyph ID + GUI.enabled = true; + position.x += btnWidth; + + GUI.SetNextControlName("GlyphID_Input"); + m_dstGlyphID = EditorGUI.TextField(position, m_dstGlyphID); + + // Placeholder text + EditorGUI.LabelField(position, new GUIContent(m_GlyphIDLabel, "The Glyph ID of the duplicated Glyph"), TMP_UIStyleManager.label); + + // Only filter the input when the destination glyph ID text field has focus. + if (GUI.GetNameOfFocusedControl() == "GlyphID_Input") + { + m_GlyphIDLabel = string.Empty; + + //Filter out unwanted characters. + char chr = Event.current.character; + if ((chr < '0' || chr > '9')) + { + Event.current.character = '\0'; + } + } + else + { + m_GlyphIDLabel = k_placeholderGlyphID; + //m_dstGlyphID = string.Empty; + } + + // Remove Glyph + position.x += btnWidth; + if (GUI.Button(position, "Remove")) + { + GUIUtility.keyboardControl = 0; + + RemoveGlyphFromList(elementIndex); + + isAssetDirty = true; + m_SelectedGlyphRecord = -1; + m_isSearchDirty = true; + break; + } + + if (m_AddGlyphWarning.isEnabled && EditorApplication.timeSinceStartup < m_AddGlyphWarning.expirationTime) + { + EditorGUILayout.HelpBox("The Destination Glyph ID already exists", MessageType.Warning); + } + + } + } + } + + DisplayPageNavigation(ref m_CurrentGlyphPage, arraySize, itemsPerPage); + + EditorGUILayout.Space(); + } + #endregion + + // FONT FEATURE TABLE + #region Font Feature Table + EditorGUIUtility.labelWidth = labelWidth; + EditorGUIUtility.fieldWidth = fieldWidth; + EditorGUI.indentLevel = 0; + rect = EditorGUILayout.GetControlRect(false, 24); + + if (GUI.Button(rect, new GUIContent("Glyph Adjustment Table", "List of glyph adjustment / advanced kerning pairs."), TMP_UIStyleManager.sectionHeader)) + UI_PanelState.fontFeatureTablePanel = !UI_PanelState.fontFeatureTablePanel; + + GUI.Label(rect, (UI_PanelState.fontFeatureTablePanel ? "" : s_UiStateLabel[1]), TMP_UIStyleManager.rightLabel); + + if (UI_PanelState.fontFeatureTablePanel) + { + int arraySize = m_GlyphPairAdjustmentRecords_prop.arraySize; + int itemsPerPage = 20; + + // Display Kerning Pair Management Tools + EditorGUILayout.BeginVertical(EditorStyles.helpBox); + { + // Search Bar implementation + #region DISPLAY SEARCH BAR + EditorGUILayout.BeginHorizontal(); + { + EditorGUIUtility.labelWidth = 150f; + EditorGUI.BeginChangeCheck(); + string searchPattern = EditorGUILayout.TextField("Adjustment Pair Search", m_KerningTableSearchPattern, "SearchTextField"); + if (EditorGUI.EndChangeCheck() || m_isSearchDirty) + { + if (string.IsNullOrEmpty(searchPattern) == false) + { + m_KerningTableSearchPattern = searchPattern; + + // Search Glyph Table for potential matches + SearchKerningTable(m_KerningTableSearchPattern, ref m_KerningTableSearchList); + } + else + m_KerningTableSearchPattern = null; + + m_isSearchDirty = false; + } + + string styleName = string.IsNullOrEmpty(m_KerningTableSearchPattern) ? "SearchCancelButtonEmpty" : "SearchCancelButton"; + if (GUILayout.Button(GUIContent.none, styleName)) + { + GUIUtility.keyboardControl = 0; + m_KerningTableSearchPattern = string.Empty; + } + } + EditorGUILayout.EndHorizontal(); + #endregion + + // Display Page Navigation + if (!string.IsNullOrEmpty(m_KerningTableSearchPattern)) + arraySize = m_KerningTableSearchList.Count; + + DisplayPageNavigation(ref m_CurrentKerningPage, arraySize, itemsPerPage); + } + EditorGUILayout.EndVertical(); + + if (arraySize > 0) + { + // Display each GlyphInfo entry using the GlyphInfo property drawer. + for (int i = itemsPerPage * m_CurrentKerningPage; i < arraySize && i < itemsPerPage * (m_CurrentKerningPage + 1); i++) + { + // Define the start of the selection region of the element. + Rect elementStartRegion = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true)); + + int elementIndex = i; + if (!string.IsNullOrEmpty(m_KerningTableSearchPattern)) + elementIndex = m_KerningTableSearchList[i]; + + SerializedProperty pairAdjustmentRecordProperty = m_GlyphPairAdjustmentRecords_prop.GetArrayElementAtIndex(elementIndex); + + EditorGUILayout.BeginVertical(EditorStyles.helpBox); + + using (new EditorGUI.DisabledScope(i != m_SelectedAdjustmentRecord)) + { + EditorGUILayout.PropertyField(pairAdjustmentRecordProperty, new GUIContent("Selectable")); + } + + EditorGUILayout.EndVertical(); + + // Define the end of the selection region of the element. + Rect elementEndRegion = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true)); + + // Check for Item selection + Rect selectionArea = new Rect(elementStartRegion.x, elementStartRegion.y, elementEndRegion.width, elementEndRegion.y - elementStartRegion.y); + if (DoSelectionCheck(selectionArea)) + { + if (m_SelectedAdjustmentRecord == i) + { + m_SelectedAdjustmentRecord = -1; + } + else + { + m_SelectedAdjustmentRecord = i; + GUIUtility.keyboardControl = 0; + } + } + + // Draw Selection Highlight and Kerning Pair Options + if (m_SelectedAdjustmentRecord == i) + { + TMP_EditorUtility.DrawBox(selectionArea, 2f, new Color32(40, 192, 255, 255)); + + // Draw Glyph management options + Rect controlRect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight * 1f); + float optionAreaWidth = controlRect.width; + float btnWidth = optionAreaWidth / 4; + + Rect position = new Rect(controlRect.x + controlRect.width - btnWidth, controlRect.y, btnWidth, controlRect.height); + + // Remove Kerning pair + GUI.enabled = true; + if (GUI.Button(position, "Remove")) + { + GUIUtility.keyboardControl = 0; + + RemoveAdjustmentPairFromList(i); + + isAssetDirty = true; + m_SelectedAdjustmentRecord = -1; + m_isSearchDirty = true; + break; + } + } + } + } + + DisplayPageNavigation(ref m_CurrentKerningPage, arraySize, itemsPerPage); + + GUILayout.Space(5); + + // Add new kerning pair + EditorGUILayout.BeginVertical(EditorStyles.helpBox); + { + EditorGUILayout.PropertyField(m_EmptyGlyphPairAdjustmentRecord_prop); + } + EditorGUILayout.EndVertical(); + + if (GUILayout.Button("Add New Glyph Adjustment Record")) + { + SerializedProperty firstAdjustmentRecordProperty = m_EmptyGlyphPairAdjustmentRecord_prop.FindPropertyRelative("m_FirstAdjustmentRecord"); + SerializedProperty secondAdjustmentRecordProperty = m_EmptyGlyphPairAdjustmentRecord_prop.FindPropertyRelative("m_SecondAdjustmentRecord"); + + uint firstGlyphIndex = (uint)firstAdjustmentRecordProperty.FindPropertyRelative("m_GlyphIndex").intValue; + uint secondGlyphIndex = (uint)secondAdjustmentRecordProperty.FindPropertyRelative("m_GlyphIndex").intValue; + + TMP_GlyphValueRecord firstValueRecord = GetValueRecord(firstAdjustmentRecordProperty.FindPropertyRelative("m_GlyphValueRecord")); + TMP_GlyphValueRecord secondValueRecord = GetValueRecord(secondAdjustmentRecordProperty.FindPropertyRelative("m_GlyphValueRecord")); + + errorCode = -1; + long pairKey = (long)secondGlyphIndex << 32 | firstGlyphIndex; + if (m_FontFeatureTable.m_GlyphPairAdjustmentRecordLookupDictionary.ContainsKey(pairKey) == false) + { + TMP_GlyphPairAdjustmentRecord adjustmentRecord = new TMP_GlyphPairAdjustmentRecord(new TMP_GlyphAdjustmentRecord(firstGlyphIndex, firstValueRecord), new TMP_GlyphAdjustmentRecord(secondGlyphIndex, secondValueRecord)); + m_FontFeatureTable.m_GlyphPairAdjustmentRecords.Add(adjustmentRecord); + m_FontFeatureTable.m_GlyphPairAdjustmentRecordLookupDictionary.Add(pairKey, adjustmentRecord); + errorCode = 0; + } + + // Add glyphs and characters + uint firstCharacter = m_SerializedPropertyHolder.firstCharacter; + if (!m_fontAsset.characterLookupTable.ContainsKey(firstCharacter)) + m_fontAsset.TryAddCharacterInternal(firstCharacter, out TMP_Character character); + + uint secondCharacter = m_SerializedPropertyHolder.secondCharacter; + if (!m_fontAsset.characterLookupTable.ContainsKey(secondCharacter)) + m_fontAsset.TryAddCharacterInternal(secondCharacter, out TMP_Character character); + + // Sort Kerning Pairs & Reload Font Asset if new kerning pair was added. + if (errorCode != -1) + { + m_FontFeatureTable.SortGlyphPairAdjustmentRecords(); + serializedObject.ApplyModifiedProperties(); + isAssetDirty = true; + m_isSearchDirty = true; + } + else + { + timeStamp = System.DateTime.Now.AddSeconds(5); + } + + // Clear Add Kerning Pair Panel + // TODO + } + + if (errorCode == -1) + { + GUILayout.BeginHorizontal(); + GUILayout.FlexibleSpace(); + GUILayout.Label("Kerning Pair already exists!", TMP_UIStyleManager.label); + GUILayout.FlexibleSpace(); + GUILayout.EndHorizontal(); + + if (System.DateTime.Now > timeStamp) + errorCode = 0; + } + } + #endregion + + if (serializedObject.ApplyModifiedProperties() || evt_cmd == k_UndoRedo || isAssetDirty) + { + // Delay callback until user has decided to Apply or Revert the changes. + if (m_DisplayDestructiveChangeWarning == false) + TMPro_EventManager.ON_FONT_PROPERTY_CHANGED(true, m_fontAsset); + + if (m_fontAsset.m_IsFontAssetLookupTablesDirty || evt_cmd == k_UndoRedo) + m_fontAsset.ReadFontAssetDefinition(); + + isAssetDirty = false; + EditorUtility.SetDirty(target); + } + + + // Clear selection if mouse event was not consumed. + GUI.enabled = true; + if (currentEvent.type == EventType.MouseDown && currentEvent.button == 0) + m_SelectedAdjustmentRecord = -1; + + } + + void CleanFallbackFontAssetTable() + { + SerializedProperty m_FallbackFontAsseTable = serializedObject.FindProperty("m_FallbackFontAssetTable"); + + bool isListDirty = false; + + int elementCount = m_FallbackFontAsseTable.arraySize; + + for (int i = 0; i < elementCount; i++) + { + SerializedProperty element = m_FallbackFontAsseTable.GetArrayElementAtIndex(i); + if (element.objectReferenceValue == null) + { + m_FallbackFontAsseTable.DeleteArrayElementAtIndex(i); + elementCount -= 1; + i -= 1; + + isListDirty = true; + } + } + + if (isListDirty) + { + serializedObject.ApplyModifiedProperties(); + serializedObject.Update(); + } + } + + void SavedAtlasGenerationSettings() + { + m_AtlasSettings.glyphRenderMode = (GlyphRenderMode)m_AtlasRenderMode_prop.intValue; + m_AtlasSettings.pointSize = m_SamplingPointSize_prop.intValue; + m_AtlasSettings.padding = m_AtlasPadding_prop.intValue; + m_AtlasSettings.atlasWidth = m_AtlasWidth_prop.intValue; + m_AtlasSettings.atlasHeight = m_AtlasHeight_prop.intValue; + } + + void RestoreAtlasGenerationSettings() + { + m_AtlasRenderMode_prop.intValue = (int)m_AtlasSettings.glyphRenderMode; + m_SamplingPointSize_prop.intValue = m_AtlasSettings.pointSize; + m_AtlasPadding_prop.intValue = m_AtlasSettings.padding; + m_AtlasWidth_prop.intValue = m_AtlasSettings.atlasWidth; + m_AtlasHeight_prop.intValue = m_AtlasSettings.atlasHeight; + } + + + void UpdateFontAssetCreationSettings() + { + m_fontAsset.m_CreationSettings.pointSize = m_SamplingPointSize_prop.intValue; + m_fontAsset.m_CreationSettings.renderMode = m_AtlasRenderMode_prop.intValue; + m_fontAsset.m_CreationSettings.padding = m_AtlasPadding_prop.intValue; + m_fontAsset.m_CreationSettings.atlasWidth = m_AtlasWidth_prop.intValue; + m_fontAsset.m_CreationSettings.atlasHeight = m_AtlasHeight_prop.intValue; + } + + + void UpdateCharacterData(SerializedProperty property, int index) + { + TMP_Character character = m_fontAsset.characterTable[index]; + + character.unicode = (uint)property.FindPropertyRelative("m_Unicode").intValue; + character.scale = property.FindPropertyRelative("m_Scale").floatValue; + + SerializedProperty glyphProperty = property.FindPropertyRelative("m_Glyph"); + character.glyph.index = (uint)glyphProperty.FindPropertyRelative("m_Index").intValue; + + SerializedProperty glyphRectProperty = glyphProperty.FindPropertyRelative("m_GlyphRect"); + character.glyph.glyphRect = new GlyphRect(glyphRectProperty.FindPropertyRelative("m_X").intValue, glyphRectProperty.FindPropertyRelative("m_Y").intValue, glyphRectProperty.FindPropertyRelative("m_Width").intValue, glyphRectProperty.FindPropertyRelative("m_Height").intValue); + + SerializedProperty glyphMetricsProperty = glyphProperty.FindPropertyRelative("m_Metrics"); + character.glyph.metrics = new GlyphMetrics(glyphMetricsProperty.FindPropertyRelative("m_Width").floatValue, glyphMetricsProperty.FindPropertyRelative("m_Height").floatValue, glyphMetricsProperty.FindPropertyRelative("m_HorizontalBearingX").floatValue, glyphMetricsProperty.FindPropertyRelative("m_HorizontalBearingY").floatValue, glyphMetricsProperty.FindPropertyRelative("m_HorizontalAdvance").floatValue); + + character.glyph.scale = glyphProperty.FindPropertyRelative("m_Scale").floatValue; + + character.glyph.atlasIndex = glyphProperty.FindPropertyRelative("m_AtlasIndex").intValue; + } + + + void UpdateGlyphData(SerializedProperty property, int index) + { + Glyph glyph = m_fontAsset.glyphTable[index]; + + glyph.index = (uint)property.FindPropertyRelative("m_Index").intValue; + + SerializedProperty glyphRect = property.FindPropertyRelative("m_GlyphRect"); + glyph.glyphRect = new GlyphRect(glyphRect.FindPropertyRelative("m_X").intValue, glyphRect.FindPropertyRelative("m_Y").intValue, glyphRect.FindPropertyRelative("m_Width").intValue, glyphRect.FindPropertyRelative("m_Height").intValue); + + SerializedProperty glyphMetrics = property.FindPropertyRelative("m_Metrics"); + glyph.metrics = new GlyphMetrics(glyphMetrics.FindPropertyRelative("m_Width").floatValue, glyphMetrics.FindPropertyRelative("m_Height").floatValue, glyphMetrics.FindPropertyRelative("m_HorizontalBearingX").floatValue, glyphMetrics.FindPropertyRelative("m_HorizontalBearingY").floatValue, glyphMetrics.FindPropertyRelative("m_HorizontalAdvance").floatValue); + + glyph.scale = property.FindPropertyRelative("m_Scale").floatValue; + } + + + void DisplayPageNavigation(ref int currentPage, int arraySize, int itemsPerPage) + { + Rect pagePos = EditorGUILayout.GetControlRect(false, 20); + pagePos.width /= 3; + + int shiftMultiplier = Event.current.shift ? 10 : 1; // Page + Shift goes 10 page forward + + // Previous Page + GUI.enabled = currentPage > 0; + + if (GUI.Button(pagePos, "Previous Page")) + currentPage -= 1 * shiftMultiplier; + + + // Page Counter + GUI.enabled = true; + pagePos.x += pagePos.width; + int totalPages = (int)(arraySize / (float)itemsPerPage + 0.999f); + GUI.Label(pagePos, "Page " + (currentPage + 1) + " / " + totalPages, TMP_UIStyleManager.centeredLabel); + + // Next Page + pagePos.x += pagePos.width; + GUI.enabled = itemsPerPage * (currentPage + 1) < arraySize; + + if (GUI.Button(pagePos, "Next Page")) + currentPage += 1 * shiftMultiplier; + + // Clamp page range + currentPage = Mathf.Clamp(currentPage, 0, arraySize / itemsPerPage); + + GUI.enabled = true; + } + + + /// + /// + /// + /// + /// + bool AddNewGlyph(int srcIndex, int dstGlyphID) + { + // Make sure Destination Glyph ID doesn't already contain a Glyph + if (m_fontAsset.glyphLookupTable.ContainsKey((uint)dstGlyphID)) + return false; + + // Add new element to glyph list. + m_GlyphTable_prop.arraySize += 1; + + // Get a reference to the source glyph. + SerializedProperty sourceGlyph = m_GlyphTable_prop.GetArrayElementAtIndex(srcIndex); + + int dstIndex = m_GlyphTable_prop.arraySize - 1; + + // Get a reference to the target / destination glyph. + SerializedProperty targetGlyph = m_GlyphTable_prop.GetArrayElementAtIndex(dstIndex); + + CopyGlyphSerializedProperty(sourceGlyph, ref targetGlyph); + + // Update the ID of the glyph + targetGlyph.FindPropertyRelative("m_Index").intValue = dstGlyphID; + + serializedObject.ApplyModifiedProperties(); + + m_fontAsset.SortGlyphTable(); + + m_fontAsset.ReadFontAssetDefinition(); + + return true; + } + + /// + /// + /// + /// + void RemoveGlyphFromList(int index) + { + if (index > m_GlyphTable_prop.arraySize) + return; + + int targetGlyphIndex = m_GlyphTable_prop.GetArrayElementAtIndex(index).FindPropertyRelative("m_Index").intValue; + + m_GlyphTable_prop.DeleteArrayElementAtIndex(index); + + // Remove all characters referencing this glyph. + for (int i = 0; i < m_CharacterTable_prop.arraySize; i++) + { + int glyphIndex = m_CharacterTable_prop.GetArrayElementAtIndex(i).FindPropertyRelative("m_GlyphIndex").intValue; + + if (glyphIndex == targetGlyphIndex) + { + // Remove character + m_CharacterTable_prop.DeleteArrayElementAtIndex(i); + } + } + + serializedObject.ApplyModifiedProperties(); + + m_fontAsset.ReadFontAssetDefinition(); + } + + bool AddNewCharacter(int srcIndex, int dstGlyphID) + { + // Make sure Destination Glyph ID doesn't already contain a Glyph + if (m_fontAsset.characterLookupTable.ContainsKey((uint)dstGlyphID)) + return false; + + // Add new element to glyph list. + m_CharacterTable_prop.arraySize += 1; + + // Get a reference to the source glyph. + SerializedProperty sourceCharacter = m_CharacterTable_prop.GetArrayElementAtIndex(srcIndex); + + int dstIndex = m_CharacterTable_prop.arraySize - 1; + + // Get a reference to the target / destination glyph. + SerializedProperty targetCharacter = m_CharacterTable_prop.GetArrayElementAtIndex(dstIndex); + + CopyCharacterSerializedProperty(sourceCharacter, ref targetCharacter); + + // Update the ID of the glyph + targetCharacter.FindPropertyRelative("m_Unicode").intValue = dstGlyphID; + + serializedObject.ApplyModifiedProperties(); + + m_fontAsset.SortCharacterTable(); + + m_fontAsset.ReadFontAssetDefinition(); + + return true; + } + + void RemoveCharacterFromList(int index) + { + if (index > m_CharacterTable_prop.arraySize) + return; + + m_CharacterTable_prop.DeleteArrayElementAtIndex(index); + + serializedObject.ApplyModifiedProperties(); + + m_fontAsset.ReadFontAssetDefinition(); + } + + + // Check if any of the Style elements were clicked on. + private bool DoSelectionCheck(Rect selectionArea) + { + Event currentEvent = Event.current; + + switch (currentEvent.type) + { + case EventType.MouseDown: + if (selectionArea.Contains(currentEvent.mousePosition) && currentEvent.button == 0) + { + currentEvent.Use(); + return true; + } + + break; + } + + return false; + } + + TMP_GlyphValueRecord GetValueRecord(SerializedProperty property) + { + TMP_GlyphValueRecord record = new TMP_GlyphValueRecord(); + record.xPlacement = property.FindPropertyRelative("m_XPlacement").floatValue; + record.yPlacement = property.FindPropertyRelative("m_YPlacement").floatValue; + record.xAdvance = property.FindPropertyRelative("m_XAdvance").floatValue; + record.yAdvance = property.FindPropertyRelative("m_YAdvance").floatValue; + + return record; + } + + void RemoveAdjustmentPairFromList(int index) + { + if (index > m_GlyphPairAdjustmentRecords_prop.arraySize) + return; + + m_GlyphPairAdjustmentRecords_prop.DeleteArrayElementAtIndex(index); + + serializedObject.ApplyModifiedProperties(); + + m_fontAsset.ReadFontAssetDefinition(); + } + + /// + /// + /// + /// + /// + void CopyGlyphSerializedProperty(SerializedProperty srcGlyph, ref SerializedProperty dstGlyph) + { + // TODO : Should make a generic function which copies each of the properties. + dstGlyph.FindPropertyRelative("m_Index").intValue = srcGlyph.FindPropertyRelative("m_Index").intValue; + + // Glyph -> GlyphMetrics + SerializedProperty srcGlyphMetrics = srcGlyph.FindPropertyRelative("m_Metrics"); + SerializedProperty dstGlyphMetrics = dstGlyph.FindPropertyRelative("m_Metrics"); + + dstGlyphMetrics.FindPropertyRelative("m_Width").floatValue = srcGlyphMetrics.FindPropertyRelative("m_Width").floatValue; + dstGlyphMetrics.FindPropertyRelative("m_Height").floatValue = srcGlyphMetrics.FindPropertyRelative("m_Height").floatValue; + dstGlyphMetrics.FindPropertyRelative("m_HorizontalBearingX").floatValue = srcGlyphMetrics.FindPropertyRelative("m_HorizontalBearingX").floatValue; + dstGlyphMetrics.FindPropertyRelative("m_HorizontalBearingY").floatValue = srcGlyphMetrics.FindPropertyRelative("m_HorizontalBearingY").floatValue; + dstGlyphMetrics.FindPropertyRelative("m_HorizontalAdvance").floatValue = srcGlyphMetrics.FindPropertyRelative("m_HorizontalAdvance").floatValue; + + // Glyph -> GlyphRect + SerializedProperty srcGlyphRect = srcGlyph.FindPropertyRelative("m_GlyphRect"); + SerializedProperty dstGlyphRect = dstGlyph.FindPropertyRelative("m_GlyphRect"); + + dstGlyphRect.FindPropertyRelative("m_X").intValue = srcGlyphRect.FindPropertyRelative("m_X").intValue; + dstGlyphRect.FindPropertyRelative("m_Y").intValue = srcGlyphRect.FindPropertyRelative("m_Y").intValue; + dstGlyphRect.FindPropertyRelative("m_Width").intValue = srcGlyphRect.FindPropertyRelative("m_Width").intValue; + dstGlyphRect.FindPropertyRelative("m_Height").intValue = srcGlyphRect.FindPropertyRelative("m_Height").intValue; + + dstGlyph.FindPropertyRelative("m_Scale").floatValue = srcGlyph.FindPropertyRelative("m_Scale").floatValue; + dstGlyph.FindPropertyRelative("m_AtlasIndex").intValue = srcGlyph.FindPropertyRelative("m_AtlasIndex").intValue; + } + + + void CopyCharacterSerializedProperty(SerializedProperty source, ref SerializedProperty target) + { + // TODO : Should make a generic function which copies each of the properties. + int unicode = source.FindPropertyRelative("m_Unicode").intValue; + target.FindPropertyRelative("m_Unicode").intValue = unicode; + + int srcGlyphIndex = source.FindPropertyRelative("m_GlyphIndex").intValue; + target.FindPropertyRelative("m_GlyphIndex").intValue = srcGlyphIndex; + + target.FindPropertyRelative("m_Scale").floatValue = source.FindPropertyRelative("m_Scale").floatValue; + } + + + /// + /// + /// + /// + /// + void SearchGlyphTable (string searchPattern, ref List searchResults) + { + if (searchResults == null) searchResults = new List(); + + searchResults.Clear(); + + int arraySize = m_GlyphTable_prop.arraySize; + + for (int i = 0; i < arraySize; i++) + { + SerializedProperty sourceGlyph = m_GlyphTable_prop.GetArrayElementAtIndex(i); + + int id = sourceGlyph.FindPropertyRelative("m_Index").intValue; + + // Check for potential match against a character. + //if (searchPattern.Length == 1 && id == searchPattern[0]) + // searchResults.Add(i); + + // Check for potential match against decimal id + if (id.ToString().Contains(searchPattern)) + searchResults.Add(i); + + //if (id.ToString("x").Contains(searchPattern)) + // searchResults.Add(i); + + //if (id.ToString("X").Contains(searchPattern)) + // searchResults.Add(i); + } + } + + + void SearchCharacterTable(string searchPattern, ref List searchResults) + { + if (searchResults == null) searchResults = new List(); + + searchResults.Clear(); + + int arraySize = m_CharacterTable_prop.arraySize; + + for (int i = 0; i < arraySize; i++) + { + SerializedProperty sourceCharacter = m_CharacterTable_prop.GetArrayElementAtIndex(i); + + int id = sourceCharacter.FindPropertyRelative("m_Unicode").intValue; + + // Check for potential match against a character. + if (searchPattern.Length == 1 && id == searchPattern[0]) + searchResults.Add(i); + else if (id.ToString("x").Contains(searchPattern)) + searchResults.Add(i); + else if (id.ToString("X").Contains(searchPattern)) + searchResults.Add(i); + + // Check for potential match against decimal id + //if (id.ToString().Contains(searchPattern)) + // searchResults.Add(i); + } + } + + + void SearchKerningTable(string searchPattern, ref List searchResults) + { + if (searchResults == null) searchResults = new List(); + + searchResults.Clear(); + + // Lookup glyph index of potential characters contained in the search pattern. + uint firstGlyphIndex = 0; + if (searchPattern.Length > 0 && m_fontAsset.characterLookupTable.TryGetValue(searchPattern[0], out TMP_Character firstCharacterSearch)) + firstGlyphIndex = firstCharacterSearch.glyphIndex; + + uint secondGlyphIndex = 0; + if (searchPattern.Length > 1 && m_fontAsset.characterLookupTable.TryGetValue(searchPattern[1], out TMP_Character secondCharacterSearch)) + secondGlyphIndex = secondCharacterSearch.glyphIndex; + + int arraySize = m_GlyphPairAdjustmentRecords_prop.arraySize; + + for (int i = 0; i < arraySize; i++) + { + SerializedProperty record = m_GlyphPairAdjustmentRecords_prop.GetArrayElementAtIndex(i); + + SerializedProperty firstAdjustmentRecord = record.FindPropertyRelative("m_FirstAdjustmentRecord"); + SerializedProperty secondAdjustmentRecord = record.FindPropertyRelative("m_SecondAdjustmentRecord"); + + int firstGlyph = firstAdjustmentRecord.FindPropertyRelative("m_GlyphIndex").intValue; + int secondGlyph = secondAdjustmentRecord.FindPropertyRelative("m_GlyphIndex").intValue; + + if (firstGlyphIndex == firstGlyph && secondGlyphIndex == secondGlyph) + searchResults.Add(i); + else if (searchPattern.Length == 1 && (firstGlyphIndex == firstGlyph || firstGlyphIndex == secondGlyph)) + searchResults.Add(i); + else if (firstGlyph.ToString().Contains(searchPattern)) + searchResults.Add(i); + else if (secondGlyph.ToString().Contains(searchPattern)) + searchResults.Add(i); + } + } + } +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_FontAsset_CreationMenu.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_FontAsset_CreationMenu.cs new file mode 100644 index 00000000..1e432331 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_FontAsset_CreationMenu.cs @@ -0,0 +1,190 @@ +using UnityEngine; +using UnityEditor; +using System.Linq; +using System.IO; +using System.Collections; +using System.Collections.Generic; +using UnityEngine.TextCore; +using UnityEngine.TextCore.LowLevel; +using TMPro; + + +namespace TMPro +{ + public static class TMP_FontAsset_CreationMenu + { + /* + [MenuItem("Assets/Create/TextMeshPro/Font Asset Fallback", false, 105)] + public static void CreateFallbackFontAsset() + { + Object target = Selection.activeObject; + + // Make sure the selection is a font file + if (target == null || target.GetType() != typeof(TMP_FontAsset)) + { + Debug.LogWarning("A Font file must first be selected in order to create a Font Asset."); + return; + } + + TMP_FontAsset sourceFontAsset = (TMP_FontAsset)target; + + string sourceFontFilePath = AssetDatabase.GetAssetPath(target); + + string folderPath = Path.GetDirectoryName(sourceFontFilePath); + string assetName = Path.GetFileNameWithoutExtension(sourceFontFilePath); + + string newAssetFilePathWithName = AssetDatabase.GenerateUniqueAssetPath(folderPath + "/" + assetName + " - Fallback.asset"); + + //// Create new TM Font Asset. + TMP_FontAsset fontAsset = ScriptableObject.CreateInstance(); + AssetDatabase.CreateAsset(fontAsset, newAssetFilePathWithName); + + fontAsset.version = "1.1.0"; + + fontAsset.faceInfo = sourceFontAsset.faceInfo; + + fontAsset.m_SourceFontFileGUID = sourceFontAsset.m_SourceFontFileGUID; + fontAsset.m_SourceFontFile_EditorRef = sourceFontAsset.m_SourceFontFile_EditorRef; + fontAsset.atlasPopulationMode = TMP_FontAsset.AtlasPopulationMode.Dynamic; + + int atlasWidth = fontAsset.atlasWidth = sourceFontAsset.atlasWidth; + int atlasHeight = fontAsset.atlasHeight = sourceFontAsset.atlasHeight; + int atlasPadding = fontAsset.atlasPadding = sourceFontAsset.atlasPadding; + fontAsset.atlasRenderMode = sourceFontAsset.atlasRenderMode; + + // Initialize array for the font atlas textures. + fontAsset.atlasTextures = new Texture2D[1]; + + // Create and add font atlas texture + Texture2D texture = new Texture2D(atlasWidth, atlasHeight, TextureFormat.Alpha8, false); + Color32[] colors = new Color32[atlasWidth * atlasHeight]; + texture.SetPixels32(colors); + + texture.name = assetName + " Atlas"; + fontAsset.atlasTextures[0] = texture; + AssetDatabase.AddObjectToAsset(texture, fontAsset); + + // Add free rectangle of the size of the texture. + int packingModifier = ((GlyphRasterModes)fontAsset.atlasRenderMode & GlyphRasterModes.RASTER_MODE_BITMAP) == GlyphRasterModes.RASTER_MODE_BITMAP ? 0 : 1; + fontAsset.m_FreeGlyphRects = new List() { new GlyphRect(0, 0, atlasWidth - packingModifier, atlasHeight - packingModifier) }; + fontAsset.m_UsedGlyphRects = new List(); + + // Create new Material and Add it as Sub-Asset + Material tmp_material = new Material(sourceFontAsset.material); + + tmp_material.name = texture.name + " Material"; + tmp_material.SetTexture(ShaderUtilities.ID_MainTex, texture); + tmp_material.SetFloat(ShaderUtilities.ID_TextureWidth, atlasWidth); + tmp_material.SetFloat(ShaderUtilities.ID_TextureHeight, atlasHeight); + + tmp_material.SetFloat(ShaderUtilities.ID_GradientScale, atlasPadding + packingModifier); + + tmp_material.SetFloat(ShaderUtilities.ID_WeightNormal, fontAsset.normalStyle); + tmp_material.SetFloat(ShaderUtilities.ID_WeightBold, fontAsset.boldStyle); + + fontAsset.material = tmp_material; + + AssetDatabase.AddObjectToAsset(tmp_material, fontAsset); + + // Add Font Asset Creation Settings + // TODO + + // Not sure if this is still necessary in newer versions of Unity. + EditorUtility.SetDirty(fontAsset); + + AssetDatabase.SaveAssets(); + } + */ + + //[MenuItem("Assets/Create/TextMeshPro/Font Asset #%F12", true)] + //public static bool CreateFontAssetMenuValidation() + //{ + // return false; + //} + + [MenuItem("Assets/Create/TextMeshPro/Font Asset #%F12", false, 100)] + public static void CreateFontAsset() + { + Object target = Selection.activeObject; + + // Make sure the selection is a font file + if (target == null || target.GetType() != typeof(Font)) + { + Debug.LogWarning("A Font file must first be selected in order to create a Font Asset."); + return; + } + + Font sourceFont = (Font)target; + + string sourceFontFilePath = AssetDatabase.GetAssetPath(target); + + string folderPath = Path.GetDirectoryName(sourceFontFilePath); + string assetName = Path.GetFileNameWithoutExtension(sourceFontFilePath); + + string newAssetFilePathWithName = AssetDatabase.GenerateUniqueAssetPath(folderPath + "/" + assetName + " SDF.asset"); + + //// Create new TM Font Asset. + TMP_FontAsset fontAsset = ScriptableObject.CreateInstance(); + AssetDatabase.CreateAsset(fontAsset, newAssetFilePathWithName); + + fontAsset.version = "1.1.0"; + + // Set face information + FontEngine.InitializeFontEngine(); + FontEngine.LoadFontFace(sourceFont, 90); + fontAsset.faceInfo = FontEngine.GetFaceInfo(); + + // Set font reference and GUID + fontAsset.m_SourceFontFileGUID = AssetDatabase.AssetPathToGUID(sourceFontFilePath); + fontAsset.m_SourceFontFile_EditorRef = sourceFont; + fontAsset.atlasPopulationMode = AtlasPopulationMode.Dynamic; + + // Default atlas resolution is 1024 x 1024. + int atlasWidth = fontAsset.atlasWidth = 1024; + int atlasHeight = fontAsset.atlasHeight = 1024; + int atlasPadding = fontAsset.atlasPadding = 9; + fontAsset.atlasRenderMode = GlyphRenderMode.SDFAA; + + // Initialize array for the font atlas textures. + fontAsset.atlasTextures = new Texture2D[1]; + + // Create atlas texture of size zero. + Texture2D texture = new Texture2D(0, 0, TextureFormat.Alpha8, false); + + texture.name = assetName + " Atlas"; + fontAsset.atlasTextures[0] = texture; + AssetDatabase.AddObjectToAsset(texture, fontAsset); + + // Add free rectangle of the size of the texture. + int packingModifier = ((GlyphRasterModes)fontAsset.atlasRenderMode & GlyphRasterModes.RASTER_MODE_BITMAP) == GlyphRasterModes.RASTER_MODE_BITMAP ? 0 : 1; + fontAsset.freeGlyphRects = new List() { new GlyphRect(0, 0, atlasWidth - packingModifier, atlasHeight - packingModifier) }; + fontAsset.usedGlyphRects = new List(); + + // Create new Material and Add it as Sub-Asset + Shader default_Shader = Shader.Find("TextMeshPro/Distance Field"); + Material tmp_material = new Material(default_Shader); + + tmp_material.name = texture.name + " Material"; + tmp_material.SetTexture(ShaderUtilities.ID_MainTex, texture); + tmp_material.SetFloat(ShaderUtilities.ID_TextureWidth, atlasWidth); + tmp_material.SetFloat(ShaderUtilities.ID_TextureHeight, atlasHeight); + + tmp_material.SetFloat(ShaderUtilities.ID_GradientScale, atlasPadding + packingModifier); + + tmp_material.SetFloat(ShaderUtilities.ID_WeightNormal, fontAsset.normalStyle); + tmp_material.SetFloat(ShaderUtilities.ID_WeightBold, fontAsset.boldStyle); + + fontAsset.material = tmp_material; + + AssetDatabase.AddObjectToAsset(tmp_material, fontAsset); + + // Add Font Asset Creation Settings + fontAsset.creationSettings = new FontAssetCreationSettings(fontAsset.m_SourceFontFileGUID, fontAsset.faceInfo.pointSize, 0, atlasPadding, 0, 1024, 1024, 7, string.Empty, (int)GlyphRenderMode.SDFAA); + + // Not sure if this is still necessary in newer versions of Unity. + EditorUtility.SetDirty(fontAsset); + + AssetDatabase.SaveAssets(); + } + } +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_GlyphPairAdjustmentRecordPropertyDrawer.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_GlyphPairAdjustmentRecordPropertyDrawer.cs new file mode 100644 index 00000000..77268baa --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_GlyphPairAdjustmentRecordPropertyDrawer.cs @@ -0,0 +1,382 @@ +using UnityEngine; +using UnityEngine.TextCore; +using UnityEngine.TextCore.LowLevel; +using UnityEditor; +using System.Collections; +using System.Text.RegularExpressions; + + +namespace TMPro.EditorUtilities +{ + + [CustomPropertyDrawer(typeof(TMP_GlyphPairAdjustmentRecord))] + public class TMP_GlyphPairAdjustmentRecordPropertyDrawer : PropertyDrawer + { + private bool isEditingEnabled = false; + private bool isSelectable = false; + + private string m_FirstCharacter = string.Empty; + private string m_SecondCharacter = string.Empty; + private string m_PreviousInput; + + static GUIContent s_CharacterTextFieldLabel = new GUIContent("Char:", "Enter the character or its UTF16 or UTF32 Unicode character escape sequence. For UTF16 use \"\\uFF00\" and for UTF32 use \"\\UFF00FF00\" representation."); + + public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) + { + SerializedProperty prop_FirstAdjustmentRecord = property.FindPropertyRelative("m_FirstAdjustmentRecord"); + SerializedProperty prop_SecondAdjustmentRecord = property.FindPropertyRelative("m_SecondAdjustmentRecord"); + + SerializedProperty prop_FirstGlyphIndex = prop_FirstAdjustmentRecord.FindPropertyRelative("m_GlyphIndex"); + SerializedProperty prop_FirstGlyphValueRecord = prop_FirstAdjustmentRecord.FindPropertyRelative("m_GlyphValueRecord"); + + SerializedProperty prop_SecondGlyphIndex = prop_SecondAdjustmentRecord.FindPropertyRelative("m_GlyphIndex"); + SerializedProperty prop_SecondGlyphValueRecord = prop_SecondAdjustmentRecord.FindPropertyRelative("m_GlyphValueRecord"); + + SerializedProperty prop_FontFeatureLookupFlags = property.FindPropertyRelative("m_FeatureLookupFlags"); + + position.yMin += 2; + + float width = position.width / 2; + float padding = 5.0f; + + Rect rect; + + isEditingEnabled = GUI.enabled; + isSelectable = label.text == "Selectable" ? true : false; + + if (isSelectable) + GUILayoutUtility.GetRect(position.width, 75); + else + GUILayoutUtility.GetRect(position.width, 55); + + GUIStyle style = new GUIStyle(EditorStyles.label); + style.richText = true; + + // First Glyph + GUI.enabled = isEditingEnabled; + if (isSelectable) + { + rect = new Rect(position.x + 70, position.y, position.width, 49); + + float labelWidth = GUI.skin.label.CalcSize(new GUIContent("ID: " + prop_FirstGlyphIndex.intValue)).x; + EditorGUI.LabelField(new Rect(position.x + (64 - labelWidth) / 2, position.y + 60, 64f, 18f), new GUIContent("ID: " + prop_FirstGlyphIndex.intValue + ""), style); + + GUI.enabled = isEditingEnabled; + EditorGUIUtility.labelWidth = 30f; + + rect = new Rect(position.x + 70, position.y + 10, (width - 70) - padding, 18); + EditorGUI.PropertyField(rect, prop_FirstGlyphValueRecord.FindPropertyRelative("m_XPlacement"), new GUIContent("OX:")); + + rect.y += 20; + EditorGUI.PropertyField(rect, prop_FirstGlyphValueRecord.FindPropertyRelative("m_YPlacement"), new GUIContent("OY:")); + + rect.y += 20; + EditorGUI.PropertyField(rect, prop_FirstGlyphValueRecord.FindPropertyRelative("m_XAdvance"), new GUIContent("AX:")); + + //rect.y += 20; + //EditorGUI.PropertyField(rect, prop_FirstGlyphValueRecord.FindPropertyRelative("m_YAdvance"), new GUIContent("AY:")); + + DrawGlyph((uint)prop_FirstGlyphIndex.intValue, new Rect(position.x, position.y, position.width, position.height), property); + } + else + { + rect = new Rect(position.x, position.y, width / 2 * 0.8f - padding, 18); + EditorGUIUtility.labelWidth = 40f; + + // First Character Lookup + GUI.SetNextControlName("FirstCharacterField"); + EditorGUI.BeginChangeCheck(); + string firstCharacter = EditorGUI.TextField(rect, s_CharacterTextFieldLabel, m_FirstCharacter); + + if (GUI.GetNameOfFocusedControl() == "FirstCharacterField") + { + if (ValidateInput(firstCharacter)) + { + //Debug.Log("1st Unicode value: [" + firstCharacter + "]"); + + uint unicode = GetUnicodeCharacter(firstCharacter); + + // Lookup glyph index + TMP_SerializedPropertyHolder propertyHolder = property.serializedObject.targetObject as TMP_SerializedPropertyHolder; + TMP_FontAsset fontAsset = propertyHolder.fontAsset; + if (fontAsset != null) + { + prop_FirstGlyphIndex.intValue = (int)fontAsset.GetGlyphIndex(unicode); + propertyHolder.firstCharacter = unicode; + } + } + } + + if (EditorGUI.EndChangeCheck()) + m_FirstCharacter = firstCharacter; + + // First Glyph Index + rect.x += width / 2 * 0.8f; + + EditorGUIUtility.labelWidth = 25f; + EditorGUI.BeginChangeCheck(); + EditorGUI.PropertyField(rect, prop_FirstGlyphIndex, new GUIContent("ID:")); + if (EditorGUI.EndChangeCheck()) + { + + } + + GUI.enabled = isEditingEnabled; + EditorGUIUtility.labelWidth = 25f; + + rect = new Rect(position.x, position.y + 20, width * 0.5f - padding, 18); + EditorGUI.PropertyField(rect, prop_FirstGlyphValueRecord.FindPropertyRelative("m_XPlacement"), new GUIContent("OX")); + + rect.x += width * 0.5f; + EditorGUI.PropertyField(rect, prop_FirstGlyphValueRecord.FindPropertyRelative("m_YPlacement"), new GUIContent("OY")); + + rect.x = position.x; + rect.y += 20; + EditorGUI.PropertyField(rect, prop_FirstGlyphValueRecord.FindPropertyRelative("m_XAdvance"), new GUIContent("AX")); + + //rect.x += width * 0.5f; + //EditorGUI.PropertyField(rect, prop_FirstGlyphAdjustment.FindPropertyRelative("m_YAdvance"), new GUIContent("AY")); + + } + + + // Second Glyph + GUI.enabled = isEditingEnabled; + if (isSelectable) + { + float labelWidth = GUI.skin.label.CalcSize(new GUIContent("ID: " + prop_SecondGlyphIndex.intValue)).x; + EditorGUI.LabelField(new Rect(position.width / 2 + 20 + (64 - labelWidth) / 2, position.y + 60, 64f, 18f), new GUIContent("ID: " + prop_SecondGlyphIndex.intValue + ""), style); + + GUI.enabled = isEditingEnabled; + EditorGUIUtility.labelWidth = 30f; + + rect = new Rect(position.width / 2 + 20 + 70, position.y + 10, (width - 70) - padding, 18); + EditorGUI.PropertyField(rect, prop_SecondGlyphValueRecord.FindPropertyRelative("m_XPlacement"), new GUIContent("OX:")); + + rect.y += 20; + EditorGUI.PropertyField(rect, prop_SecondGlyphValueRecord.FindPropertyRelative("m_YPlacement"), new GUIContent("OY:")); + + rect.y += 20; + EditorGUI.PropertyField(rect, prop_SecondGlyphValueRecord.FindPropertyRelative("m_XAdvance"), new GUIContent("AX:")); + + //rect.y += 20; + //EditorGUI.PropertyField(rect, prop_SecondGlyphAdjustment.FindPropertyRelative("m_YAdvance"), new GUIContent("AY")); + + DrawGlyph((uint)prop_SecondGlyphIndex.intValue, new Rect(position.width / 2 + 20, position.y, position.width, position.height), property); + } + else + { + rect = new Rect(position.width / 2 + 20, position.y, width / 2 * 0.8f - padding, 18); + EditorGUIUtility.labelWidth = 40f; + + // Second Character Lookup + GUI.SetNextControlName("SecondCharacterField"); + EditorGUI.BeginChangeCheck(); + string secondCharacter = EditorGUI.TextField(rect, s_CharacterTextFieldLabel, m_SecondCharacter); + + if (GUI.GetNameOfFocusedControl() == "SecondCharacterField") + { + if (ValidateInput(secondCharacter)) + { + //Debug.Log("2nd Unicode value: [" + secondCharacter + "]"); + + uint unicode = GetUnicodeCharacter(secondCharacter); + + // Lookup glyph index + TMP_SerializedPropertyHolder propertyHolder = property.serializedObject.targetObject as TMP_SerializedPropertyHolder; + TMP_FontAsset fontAsset = propertyHolder.fontAsset; + if (fontAsset != null) + { + prop_SecondGlyphIndex.intValue = (int)fontAsset.GetGlyphIndex(unicode); + propertyHolder.secondCharacter = unicode; + } + } + } + + if (EditorGUI.EndChangeCheck()) + m_SecondCharacter = secondCharacter; + + // Second Glyph Index + rect.x += width / 2 * 0.8f; + + EditorGUIUtility.labelWidth = 25f; + EditorGUI.BeginChangeCheck(); + EditorGUI.PropertyField(rect, prop_SecondGlyphIndex, new GUIContent("ID:")); + if (EditorGUI.EndChangeCheck()) + { + + } + + GUI.enabled = isEditingEnabled; + EditorGUIUtility.labelWidth = 25f; + + rect = new Rect(position.width / 2 + 20, position.y + 20, width * 0.5f - padding, 18); + EditorGUI.PropertyField(rect, prop_SecondGlyphValueRecord.FindPropertyRelative("m_XPlacement"), new GUIContent("OX")); + + rect.x += width * 0.5f; + EditorGUI.PropertyField(rect, prop_SecondGlyphValueRecord.FindPropertyRelative("m_YPlacement"), new GUIContent("OY")); + + rect.x = position.width / 2 + 20; + rect.y += 20; + EditorGUI.PropertyField(rect, prop_SecondGlyphValueRecord.FindPropertyRelative("m_XAdvance"), new GUIContent("AX")); + + //rect.x += width * 0.5f; + //EditorGUI.PropertyField(rect, prop_SecondGlyphAdjustment.FindPropertyRelative("m_YAdvance"), new GUIContent("AY")); + } + + // Font Feature Lookup Flags + if (isSelectable) + { + EditorGUIUtility.labelWidth = 55f; + + rect.x = position.width - 255; + rect.y += 23; + rect.width = 270; // width - 70 - padding; + + FontFeatureLookupFlags flags = (FontFeatureLookupFlags)prop_FontFeatureLookupFlags.intValue; + + EditorGUI.BeginChangeCheck(); + flags = (FontFeatureLookupFlags)EditorGUI.EnumFlagsField(rect, new GUIContent("Options:"), flags); + if (EditorGUI.EndChangeCheck()) + { + prop_FontFeatureLookupFlags.intValue = (int)flags; + } + } + + } + + bool ValidateInput(string source) + { + int length = string.IsNullOrEmpty(source) ? 0 : source.Length; + + ////Filter out unwanted characters. + Event evt = Event.current; + + char c = evt.character; + + if (c != '\0') + { + switch (length) + { + case 0: + break; + case 1: + if (source != m_PreviousInput) + return true; + + if ((source[0] == '\\' && (c == 'u' || c == 'U')) == false) + evt.character = '\0'; + + break; + case 2: + case 3: + case 4: + case 5: + if ((c < '0' || c > '9') && (c < 'a' || c > 'f') && (c < 'A' || c > 'F')) + evt.character = '\0'; + break; + case 6: + case 7: + case 8: + case 9: + if (source[1] == 'u' || (c < '0' || c > '9') && (c < 'a' || c > 'f') && (c < 'A' || c > 'F')) + evt.character = '\0'; + + // Validate input + if (length == 6 && source[1] == 'u' && source != m_PreviousInput) + return true; + break; + case 10: + if (source != m_PreviousInput) + return true; + + evt.character = '\0'; + break; + } + } + + m_PreviousInput = source; + + return false; + } + + uint GetUnicodeCharacter (string source) + { + uint unicode; + + if (source.Length == 1) + unicode = source[0]; + else if (source.Length == 6) + unicode = (uint)TMP_TextUtilities.StringHexToInt(source.Replace("\\u", "")); + else + unicode = (uint)TMP_TextUtilities.StringHexToInt(source.Replace("\\U", "")); + + return unicode; + } + + void DrawGlyph(uint glyphIndex, Rect position, SerializedProperty property) + { + // Get a reference to the sprite texture + TMP_FontAsset fontAsset = property.serializedObject.targetObject as TMP_FontAsset; + + if (fontAsset == null) + return; + + // Check if glyph currently exists in the atlas texture. + if (!fontAsset.glyphLookupTable.TryGetValue(glyphIndex, out Glyph glyph)) + return; + + // Get reference to atlas texture. + int atlasIndex = fontAsset.m_AtlasTextureIndex; + Texture2D atlasTexture = fontAsset.atlasTextures.Length > atlasIndex ? fontAsset.atlasTextures[atlasIndex] : null; + + if (atlasTexture == null) + return; + + Material mat; + if (((GlyphRasterModes)fontAsset.atlasRenderMode & GlyphRasterModes.RASTER_MODE_BITMAP) == GlyphRasterModes.RASTER_MODE_BITMAP) + { + mat = TMP_FontAssetEditor.internalBitmapMaterial; + + if (mat == null) + return; + + mat.mainTexture = atlasTexture; + } + else + { + mat = TMP_FontAssetEditor.internalSDFMaterial; + + if (mat == null) + return; + + mat.mainTexture = atlasTexture; + mat.SetFloat(ShaderUtilities.ID_GradientScale, fontAsset.atlasPadding + 1); + } + + // Draw glyph from atlas texture. + Rect glyphDrawPosition = new Rect(position.x, position.y + 2, 64, 60); + + GlyphRect glyphRect = glyph.glyphRect; + + float normalizedHeight = fontAsset.faceInfo.ascentLine - fontAsset.faceInfo.descentLine; + float scale = glyphDrawPosition.width / normalizedHeight; + + // Compute the normalized texture coordinates + Rect texCoords = new Rect((float)glyphRect.x / atlasTexture.width, (float)glyphRect.y / atlasTexture.height, (float)glyphRect.width / atlasTexture.width, (float)glyphRect.height / atlasTexture.height); + + if (Event.current.type == EventType.Repaint) + { + glyphDrawPosition.x += (glyphDrawPosition.width - glyphRect.width * scale) / 2; + glyphDrawPosition.y += (glyphDrawPosition.height - glyphRect.height * scale) / 2; + glyphDrawPosition.width = glyphRect.width * scale; + glyphDrawPosition.height = glyphRect.height * scale; + + // Could switch to using the default material of the font asset which would require passing scale to the shader. + Graphics.DrawTexture(glyphDrawPosition, atlasTexture, texCoords, 0, 0, 0, 0, new Color(1f, 1f, 1f), mat); + } + } + + + } +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_GlyphPropertyDrawer.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_GlyphPropertyDrawer.cs new file mode 100644 index 00000000..b92dfd66 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_GlyphPropertyDrawer.cs @@ -0,0 +1,118 @@ + using UnityEngine; +using UnityEngine.TextCore; +using UnityEngine.TextCore.LowLevel; +using UnityEditor; +using System.Collections; + + +namespace TMPro.EditorUtilities +{ + + [CustomPropertyDrawer(typeof(Glyph))] + public class TMP_GlyphPropertyDrawer : PropertyDrawer + { + public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) + { + SerializedProperty prop_GlyphIndex = property.FindPropertyRelative("m_Index"); + SerializedProperty prop_GlyphMetrics = property.FindPropertyRelative("m_Metrics"); + SerializedProperty prop_GlyphRect = property.FindPropertyRelative("m_GlyphRect"); + SerializedProperty prop_Scale = property.FindPropertyRelative("m_Scale"); + SerializedProperty prop_AtlasIndex = property.FindPropertyRelative("m_AtlasIndex"); + + GUIStyle style = new GUIStyle(EditorStyles.label); + style.richText = true; + + Rect rect = new Rect(position.x + 70, position.y, position.width, 49); + + float labelWidth = GUI.skin.label.CalcSize(new GUIContent("ID: " + prop_GlyphIndex.intValue)).x; + EditorGUI.LabelField(new Rect(position.x + (64 - labelWidth) / 2, position.y + 85, 64f, 18f), new GUIContent("ID: " + prop_GlyphIndex.intValue + ""), style); + //EditorGUIUtility.labelWidth = 22f; + //EditorGUI.DelayedIntField(new Rect(position.x + (64 - labelWidth) / 2, position.y + 89, 58f, 18f), prop_GlyphIndex, new GUIContent("ID:")); + + // We get Rect since a valid position may not be provided by the caller. + EditorGUI.PropertyField(new Rect(rect.x, rect.y, position.width, 49), prop_GlyphRect); + + rect.y += 45; + EditorGUI.PropertyField(rect, prop_GlyphMetrics); + + EditorGUIUtility.labelWidth = 40f; + EditorGUI.PropertyField(new Rect(rect.x, rect.y + 65, 75, 18), prop_Scale, new GUIContent("Scale:")); // new GUIContent("Scale: " + prop_Scale.floatValue + ""), style); + + EditorGUIUtility.labelWidth = 74f; + EditorGUI.PropertyField(new Rect(rect.x + 85, rect.y + 65, 95, 18), prop_AtlasIndex, new GUIContent("Atlas Index:")); // new GUIContent("Atlas Index: " + prop_AtlasIndex.intValue + ""), style); + + DrawGlyph(position, property); + } + + public override float GetPropertyHeight(SerializedProperty property, GUIContent label) + { + return 130f; + } + + void DrawGlyph(Rect position, SerializedProperty property) + { + // Get a reference to the sprite texture + TMP_FontAsset fontAsset = property.serializedObject.targetObject as TMP_FontAsset; + + if (fontAsset == null) + return; + + // Get reference to atlas texture. + int atlasIndex = property.FindPropertyRelative("m_AtlasIndex").intValue; + Texture2D atlasTexture = fontAsset.atlasTextures.Length > atlasIndex ? fontAsset.atlasTextures[atlasIndex] : null; + + if (atlasTexture == null) + return; + + Material mat; + if (((GlyphRasterModes)fontAsset.atlasRenderMode & GlyphRasterModes.RASTER_MODE_BITMAP) == GlyphRasterModes.RASTER_MODE_BITMAP) + { + mat = TMP_FontAssetEditor.internalBitmapMaterial; + + if (mat == null) + return; + + mat.mainTexture = atlasTexture; + mat.SetColor("_Color", Color.white); + } + else + { + mat = TMP_FontAssetEditor.internalSDFMaterial; + + if (mat == null) + return; + + mat.mainTexture = atlasTexture; + mat.SetFloat(ShaderUtilities.ID_GradientScale, fontAsset.atlasPadding + 1); + } + + // Draw glyph from atlas texture. + Rect glyphDrawPosition = new Rect(position.x, position.y + 2, 64, 80); + + SerializedProperty prop_GlyphRect = property.FindPropertyRelative("m_GlyphRect"); + + int glyphOriginX = prop_GlyphRect.FindPropertyRelative("m_X").intValue; + int glyphOriginY = prop_GlyphRect.FindPropertyRelative("m_Y").intValue; + int glyphWidth = prop_GlyphRect.FindPropertyRelative("m_Width").intValue; + int glyphHeight = prop_GlyphRect.FindPropertyRelative("m_Height").intValue; + + float normalizedHeight = fontAsset.faceInfo.ascentLine - fontAsset.faceInfo.descentLine; + float scale = glyphDrawPosition.width / normalizedHeight; + + // Compute the normalized texture coordinates + Rect texCoords = new Rect((float)glyphOriginX / atlasTexture.width, (float)glyphOriginY / atlasTexture.height, (float)glyphWidth / atlasTexture.width, (float)glyphHeight / atlasTexture.height); + + if (Event.current.type == EventType.Repaint) + { + glyphDrawPosition.x += (glyphDrawPosition.width - glyphWidth * scale) / 2; + glyphDrawPosition.y += (glyphDrawPosition.height - glyphHeight * scale) / 2; + glyphDrawPosition.width = glyphWidth * scale; + glyphDrawPosition.height = glyphHeight * scale; + + // Could switch to using the default material of the font asset which would require passing scale to the shader. + Graphics.DrawTexture(glyphDrawPosition, atlasTexture, texCoords, 0, 0, 0, 0, new Color(1f, 1f, 1f), mat); + } + } + + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_InputFieldEditor.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_InputFieldEditor.cs new file mode 100644 index 00000000..d50dc585 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_InputFieldEditor.cs @@ -0,0 +1,283 @@ +using UnityEngine; +using UnityEngine.UI; +using UnityEditor; +using UnityEditor.UI; +using UnityEditor.AnimatedValues; + + +namespace TMPro.EditorUtilities +{ + [CanEditMultipleObjects] + [CustomEditor(typeof(TMP_InputField), true)] + public class TMP_InputFieldEditor : SelectableEditor + { + private struct m_foldout + { // Track Inspector foldout panel states, globally. + public static bool textInput = true; + public static bool fontSettings = true; + public static bool extraSettings = true; + //public static bool shadowSetting = false; + //public static bool materialEditor = true; + } + + SerializedProperty m_TextViewport; + SerializedProperty m_TextComponent; + SerializedProperty m_Text; + SerializedProperty m_ContentType; + SerializedProperty m_LineType; + SerializedProperty m_LineLimit; + SerializedProperty m_InputType; + SerializedProperty m_CharacterValidation; + SerializedProperty m_InputValidator; + SerializedProperty m_RegexValue; + SerializedProperty m_KeyboardType; + SerializedProperty m_CharacterLimit; + SerializedProperty m_CaretBlinkRate; + SerializedProperty m_CaretWidth; + SerializedProperty m_CaretColor; + SerializedProperty m_CustomCaretColor; + SerializedProperty m_SelectionColor; + SerializedProperty m_HideMobileKeyboard; + SerializedProperty m_HideMobileInput; + SerializedProperty m_Placeholder; + SerializedProperty m_VerticalScrollbar; + SerializedProperty m_ScrollbarScrollSensitivity; + SerializedProperty m_OnValueChanged; + SerializedProperty m_OnEndEdit; + SerializedProperty m_OnSelect; + SerializedProperty m_OnDeselect; + SerializedProperty m_ReadOnly; + SerializedProperty m_RichText; + SerializedProperty m_RichTextEditingAllowed; + SerializedProperty m_ResetOnDeActivation; + SerializedProperty m_RestoreOriginalTextOnEscape; + + SerializedProperty m_OnFocusSelectAll; + SerializedProperty m_GlobalPointSize; + SerializedProperty m_GlobalFontAsset; + + AnimBool m_CustomColor; + + //TMP_InputValidator m_ValidationScript; + + protected override void OnEnable() + { + base.OnEnable(); + + m_TextViewport = serializedObject.FindProperty("m_TextViewport"); + m_TextComponent = serializedObject.FindProperty("m_TextComponent"); + m_Text = serializedObject.FindProperty("m_Text"); + m_ContentType = serializedObject.FindProperty("m_ContentType"); + m_LineType = serializedObject.FindProperty("m_LineType"); + m_LineLimit = serializedObject.FindProperty("m_LineLimit"); + m_InputType = serializedObject.FindProperty("m_InputType"); + m_CharacterValidation = serializedObject.FindProperty("m_CharacterValidation"); + m_InputValidator = serializedObject.FindProperty("m_InputValidator"); + m_RegexValue = serializedObject.FindProperty("m_RegexValue"); + m_KeyboardType = serializedObject.FindProperty("m_KeyboardType"); + m_CharacterLimit = serializedObject.FindProperty("m_CharacterLimit"); + m_CaretBlinkRate = serializedObject.FindProperty("m_CaretBlinkRate"); + m_CaretWidth = serializedObject.FindProperty("m_CaretWidth"); + m_CaretColor = serializedObject.FindProperty("m_CaretColor"); + m_CustomCaretColor = serializedObject.FindProperty("m_CustomCaretColor"); + m_SelectionColor = serializedObject.FindProperty("m_SelectionColor"); + + m_HideMobileKeyboard = serializedObject.FindProperty("m_HideSoftKeyboard"); + m_HideMobileInput = serializedObject.FindProperty("m_HideMobileInput"); + + m_Placeholder = serializedObject.FindProperty("m_Placeholder"); + m_VerticalScrollbar = serializedObject.FindProperty("m_VerticalScrollbar"); + m_ScrollbarScrollSensitivity = serializedObject.FindProperty("m_ScrollSensitivity"); + + m_OnValueChanged = serializedObject.FindProperty("m_OnValueChanged"); + m_OnEndEdit = serializedObject.FindProperty("m_OnEndEdit"); + m_OnSelect = serializedObject.FindProperty("m_OnSelect"); + m_OnDeselect = serializedObject.FindProperty("m_OnDeselect"); + m_ReadOnly = serializedObject.FindProperty("m_ReadOnly"); + m_RichText = serializedObject.FindProperty("m_RichText"); + m_RichTextEditingAllowed = serializedObject.FindProperty("m_isRichTextEditingAllowed"); + m_ResetOnDeActivation = serializedObject.FindProperty("m_ResetOnDeActivation"); + m_RestoreOriginalTextOnEscape = serializedObject.FindProperty("m_RestoreOriginalTextOnEscape"); + + m_OnFocusSelectAll = serializedObject.FindProperty("m_OnFocusSelectAll"); + m_GlobalPointSize = serializedObject.FindProperty("m_GlobalPointSize"); + m_GlobalFontAsset = serializedObject.FindProperty("m_GlobalFontAsset"); + + m_CustomColor = new AnimBool(m_CustomCaretColor.boolValue); + m_CustomColor.valueChanged.AddListener(Repaint); + } + + protected override void OnDisable() + { + base.OnDisable(); + m_CustomColor.valueChanged.RemoveListener(Repaint); + } + + public override void OnInspectorGUI() + { + serializedObject.Update(); + + base.OnInspectorGUI(); + + EditorGUILayout.Space(); + + EditorGUILayout.PropertyField(m_TextViewport); + + EditorGUILayout.PropertyField(m_TextComponent); + + TextMeshProUGUI text = null; + if (m_TextComponent != null && m_TextComponent.objectReferenceValue != null) + { + text = m_TextComponent.objectReferenceValue as TextMeshProUGUI; + //if (text.supportRichText) + //{ + // EditorGUILayout.HelpBox("Using Rich Text with input is unsupported.", MessageType.Warning); + //} + } + + EditorGUI.BeginDisabledGroup(m_TextComponent == null || m_TextComponent.objectReferenceValue == null); + + // TEXT INPUT BOX + EditorGUILayout.PropertyField(m_Text); + + // INPUT FIELD SETTINGS + #region INPUT FIELD SETTINGS + + m_foldout.fontSettings = EditorGUILayout.Foldout(m_foldout.fontSettings, "Input Field Settings", true, TMP_UIStyleManager.boldFoldout); + + if (m_foldout.fontSettings) + { + EditorGUI.indentLevel++; + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(m_GlobalFontAsset, new GUIContent("Font Asset", "Set the Font Asset for both Placeholder and Input Field text object.")); + if (EditorGUI.EndChangeCheck()) + { + TMP_InputField inputField = target as TMP_InputField; + inputField.SetGlobalFontAsset(m_GlobalFontAsset.objectReferenceValue as TMP_FontAsset); + } + + + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(m_GlobalPointSize, new GUIContent("Point Size", "Set the point size of both Placeholder and Input Field text object.")); + if (EditorGUI.EndChangeCheck()) + { + TMP_InputField inputField = target as TMP_InputField; + inputField.SetGlobalPointSize(m_GlobalPointSize.floatValue); + } + + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(m_CharacterLimit); + + EditorGUILayout.Space(); + + EditorGUILayout.PropertyField(m_ContentType); + if (!m_ContentType.hasMultipleDifferentValues) + { + EditorGUI.indentLevel++; + + if (m_ContentType.enumValueIndex == (int)TMP_InputField.ContentType.Standard || + m_ContentType.enumValueIndex == (int)TMP_InputField.ContentType.Autocorrected || + m_ContentType.enumValueIndex == (int)TMP_InputField.ContentType.Custom) + { + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(m_LineType); + if (EditorGUI.EndChangeCheck()) + { + if (text != null) + { + if (m_LineType.enumValueIndex == (int)TMP_InputField.LineType.SingleLine) + text.enableWordWrapping = false; + else + { + text.enableWordWrapping = true; + } + } + } + + if (m_LineType.enumValueIndex != (int)TMP_InputField.LineType.SingleLine) + { + EditorGUILayout.PropertyField(m_LineLimit); + } + } + + if (m_ContentType.enumValueIndex == (int)TMP_InputField.ContentType.Custom) + { + EditorGUILayout.PropertyField(m_InputType); + EditorGUILayout.PropertyField(m_KeyboardType); + EditorGUILayout.PropertyField(m_CharacterValidation); + if (m_CharacterValidation.enumValueIndex == (int)TMP_InputField.CharacterValidation.Regex) + { + EditorGUILayout.PropertyField(m_RegexValue); + } + else if (m_CharacterValidation.enumValueIndex == (int)TMP_InputField.CharacterValidation.CustomValidator) + { + EditorGUILayout.PropertyField(m_InputValidator); + } + } + + EditorGUI.indentLevel--; + } + + EditorGUILayout.Space(); + + EditorGUILayout.PropertyField(m_Placeholder); + EditorGUILayout.PropertyField(m_VerticalScrollbar); + + if (m_VerticalScrollbar.objectReferenceValue != null) + EditorGUILayout.PropertyField(m_ScrollbarScrollSensitivity); + + EditorGUILayout.PropertyField(m_CaretBlinkRate); + EditorGUILayout.PropertyField(m_CaretWidth); + + EditorGUILayout.PropertyField(m_CustomCaretColor); + + m_CustomColor.target = m_CustomCaretColor.boolValue; + + if (EditorGUILayout.BeginFadeGroup(m_CustomColor.faded)) + { + EditorGUILayout.PropertyField(m_CaretColor); + } + EditorGUILayout.EndFadeGroup(); + + EditorGUILayout.PropertyField(m_SelectionColor); + + EditorGUI.indentLevel--; + } + #endregion + + + // CONTROL SETTINGS + #region CONTROL SETTINGS + m_foldout.extraSettings = EditorGUILayout.Foldout(m_foldout.extraSettings, "Control Settings", true, TMP_UIStyleManager.boldFoldout); + + if (m_foldout.extraSettings) + { + EditorGUI.indentLevel++; + + EditorGUILayout.PropertyField(m_OnFocusSelectAll, new GUIContent("OnFocus - Select All", "Should all the text be selected when the Input Field is selected.")); + EditorGUILayout.PropertyField(m_ResetOnDeActivation, new GUIContent("Reset On DeActivation", "Should the Text and Caret position be reset when Input Field is DeActivated.")); + EditorGUILayout.PropertyField(m_RestoreOriginalTextOnEscape, new GUIContent("Restore On ESC Key", "Should the original text be restored when pressing ESC.")); + EditorGUILayout.PropertyField(m_HideMobileKeyboard, new GUIContent("Hide Soft Keyboard", "Controls the visibility of the mobile virtual keyboard.")); + EditorGUILayout.PropertyField(m_HideMobileInput, new GUIContent("Hide Mobile Input", "Controls the visibility of the editable text field above the mobile virtual keyboard. Not supported on all mobile platforms.")); + EditorGUILayout.PropertyField(m_ReadOnly); + EditorGUILayout.PropertyField(m_RichText); + EditorGUILayout.PropertyField(m_RichTextEditingAllowed, new GUIContent("Allow Rich Text Editing")); + + EditorGUI.indentLevel--; + } + #endregion + + + EditorGUILayout.Space(); + + EditorGUILayout.PropertyField(m_OnValueChanged); + EditorGUILayout.PropertyField(m_OnEndEdit); + EditorGUILayout.PropertyField(m_OnSelect); + EditorGUILayout.PropertyField(m_OnDeselect); + + EditorGUI.EndDisabledGroup(); + + serializedObject.ApplyModifiedProperties(); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_MeshRendererEditor.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_MeshRendererEditor.cs new file mode 100644 index 00000000..83d19f8c --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_MeshRendererEditor.cs @@ -0,0 +1,76 @@ +// When enabled, allows setting the material by dropping a material onto the MeshRenderer inspector component. +// The drawback is that the MeshRenderer inspector will not have properties for light probes, so if you need light probe support, do not enable this. +//#define ALLOW_MESHRENDERER_MATERIAL_DRAG_N_DROP + +using UnityEngine; +using UnityEditor; +using System.Collections; + + +namespace TMPro.EditorUtilities +{ + // Disabled for compatibility reason as lightprobe setup isn't supported due to inability to inherit from MeshRendererEditor class +#if ALLOW_MESHRENDERER_MATERIAL_DRAG_N_DROP + [CanEditMultipleObjects] + [CustomEditor(typeof(MeshRenderer))] + public class TMP_MeshRendererEditor : Editor + { + private SerializedProperty m_Materials; + + void OnEnable() + { + m_Materials = serializedObject.FindProperty("m_Materials"); + } + + + public override void OnInspectorGUI() + { + serializedObject.Update(); + + // Get a reference to the current material. + SerializedProperty material_prop = m_Materials.GetArrayElementAtIndex(0); + Material currentMaterial = material_prop.objectReferenceValue as Material; + + EditorGUI.BeginChangeCheck(); + base.OnInspectorGUI(); + if (EditorGUI.EndChangeCheck()) + { + material_prop = m_Materials.GetArrayElementAtIndex(0); + + TMP_FontAsset newFontAsset = null; + Material newMaterial = null; + + if (material_prop != null) + newMaterial = material_prop.objectReferenceValue as Material; + + // Check if the new material is referencing a different font atlas texture. + if (newMaterial != null && currentMaterial.GetInstanceID() != newMaterial.GetInstanceID()) + { + // Search for the Font Asset matching the new font atlas texture. + newFontAsset = TMP_EditorUtility.FindMatchingFontAsset(newMaterial); + } + + + GameObject[] objects = Selection.gameObjects; + + for (int i = 0; i < objects.Length; i++) + { + // Assign new font asset + if (newFontAsset != null) + { + TMP_Text textComponent = objects[i].GetComponent(); + + if (textComponent != null) + { + Undo.RecordObject(textComponent, "Font Asset Change"); + textComponent.font = newFontAsset; + } + } + + TMPro_EventManager.ON_DRAG_AND_DROP_MATERIAL_CHANGED(objects[i], currentMaterial, newMaterial); + } + } + } + } +#endif +} diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_PackageUtilities.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_PackageUtilities.cs new file mode 100644 index 00000000..5e50d76e --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_PackageUtilities.cs @@ -0,0 +1,920 @@ +using UnityEngine; +using UnityEditor; +using System; +using System.IO; +using System.Linq; +using System.Collections; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using TMPro.EditorUtilities; + + +namespace TMPro +{ + /// + /// Data structure containing the target and replacement fileIDs and GUIDs which will require remapping from previous version of TextMesh Pro to the new TextMesh Pro UPM package. + /// + [System.Serializable] + struct AssetConversionRecord + { + public string referencedResource; + public string target; + public string replacement; + } + + + /// + /// Data structure containing a list of target and replacement fileID and GUID requiring remapping from previous versions of TextMesh Pro to the new TextMesh Pro UPM package. + /// This data structure is populated with the data contained in the PackageConversionData.json file included in the package. + /// + [System.Serializable] + class AssetConversionData + { + public List assetRecords; + } + + + public class TMP_ProjectConversionUtility : EditorWindow + { + // Create Sprite Asset Editor Window + [MenuItem("Window/TextMeshPro/Project Files GUID Remapping Tool", false, 2100)] + static void ShowConverterWindow() + { + var window = GetWindow(); + window.titleContent = new GUIContent("Conversion Tool"); + window.Focus(); + } + + private static HashSet m_IgnoreAssetTypes = new HashSet() + { + typeof(AnimatorOverrideController), + typeof(AudioClip), + typeof(AvatarMask), + typeof(ComputeShader), + typeof(Cubemap), + typeof(DefaultAsset), + typeof(Flare), + typeof(Font), + typeof(GUISkin), + typeof(HumanTemplate), + typeof(LightingDataAsset), + typeof(Mesh), + typeof(MonoScript), + typeof(PhysicMaterial), + typeof(PhysicsMaterial2D), + typeof(RenderTexture), + typeof(Shader), + typeof(TerrainData), + typeof(TextAsset), + typeof(Texture2D), + typeof(Texture2DArray), + typeof(Texture3D), + typeof(UnityEditor.Animations.AnimatorController), + typeof(UnityEditorInternal.AssemblyDefinitionAsset), + typeof(UnityEngine.AI.NavMeshData), + typeof(UnityEngine.Tilemaps.Tile), + typeof(UnityEngine.U2D.SpriteAtlas), + typeof(UnityEngine.Video.VideoClip), + }; + + /// + /// + /// + struct AssetModificationRecord + { + public string assetFilePath; + public string assetDataFile; + } + + struct AssetFileRecord + { + public string assetFilePath; + public string assetMetaFilePath; + + public AssetFileRecord(string filePath, string metaFilePath) + { + this.assetFilePath = filePath; + this.assetMetaFilePath = metaFilePath; + } + } + + private static string m_ProjectPath; + private static string m_ProjectFolderToScan; + private static bool m_IsAlreadyScanningProject; + private static bool m_CancelScanProcess; + private static string k_ProjectScanReportDefaultText = "Project Scan Results\n"; + private static string k_ProjectScanLabelPrefix = "Scanning: "; + private static string m_ProjectScanResults = string.Empty; + private static Vector2 m_ProjectScanResultScrollPosition; + private static float m_ProgressPercentage = 0; + + private static int m_ScanningTotalFiles; + private static int m_RemainingFilesToScan; + private static int m_ScanningCurrentFileIndex; + private static string m_ScanningCurrentFileName; + + private static AssetConversionData m_ConversionData; + + private static List m_ModifiedAssetList = new List(); + + + void OnEnable() + { + // Set Editor Window Size + SetEditorWindowSize(); + + m_ProjectScanResults = k_ProjectScanReportDefaultText; + } + + + void OnGUI() + { + GUILayout.BeginVertical(); + { + // Scan project files and resources + GUILayout.BeginVertical(EditorStyles.helpBox); + { + GUILayout.Label("Scan Project Files", EditorStyles.boldLabel); + GUILayout.Label("Press the Scan Project Files button to begin scanning your project for files & resources that were created with a previous version of TextMesh Pro.", TMP_UIStyleManager.label); + GUILayout.Space(10f); + GUILayout.Label("Project folder to be scanned. Example \"Assets/TextMesh Pro\""); + m_ProjectFolderToScan = EditorGUILayout.TextField("Folder Path: Assets/", m_ProjectFolderToScan); + GUILayout.Space(5f); + + GUI.enabled = m_IsAlreadyScanningProject == false ? true : false; + if (GUILayout.Button("Scan Project Files")) + { + m_CancelScanProcess = false; + + // Make sure Asset Serialization mode is set to ForceText and Version Control mode to Visible Meta Files. + if (CheckProjectSerializationAndSourceControlModes() == true) + { + m_ProjectPath = Path.GetFullPath("Assets/.."); + TMP_EditorCoroutine.StartCoroutine(ScanProjectFiles()); + } + else + { + EditorUtility.DisplayDialog("Project Settings Change Required", "In menu options \"Edit - Project Settings - Editor\", please change Asset Serialization Mode to ForceText and Source Control Mode to Visible Meta Files.", "OK", string.Empty); + } + } + GUI.enabled = true; + + // Display progress bar + Rect rect = GUILayoutUtility.GetRect(0f, 20f, GUILayout.ExpandWidth(true)); + EditorGUI.ProgressBar(rect, m_ProgressPercentage, "Scan Progress (" + m_ScanningCurrentFileIndex + "/" + m_ScanningTotalFiles + ")"); + + // Display cancel button and name of file currently being scanned. + if (m_IsAlreadyScanningProject) + { + Rect cancelRect = new Rect(rect.width - 20, rect.y + 2, 20, 16); + if (GUI.Button(cancelRect, "X")) + { + m_CancelScanProcess = true; + } + GUILayout.Label(k_ProjectScanLabelPrefix + m_ScanningCurrentFileName, TMP_UIStyleManager.label); + } + else + GUILayout.Label(string.Empty); + + GUILayout.Space(5); + + // Creation Feedback + GUILayout.BeginVertical(TMP_UIStyleManager.textAreaBoxWindow, GUILayout.ExpandHeight(true)); + { + m_ProjectScanResultScrollPosition = EditorGUILayout.BeginScrollView(m_ProjectScanResultScrollPosition, GUILayout.ExpandHeight(true)); + EditorGUILayout.LabelField(m_ProjectScanResults, TMP_UIStyleManager.label); + EditorGUILayout.EndScrollView(); + } + GUILayout.EndVertical(); + GUILayout.Space(5f); + } + GUILayout.EndVertical(); + + // Scan project files and resources + GUILayout.BeginVertical(EditorStyles.helpBox); + { + GUILayout.Label("Save Modified Project Files", EditorStyles.boldLabel); + GUILayout.Label("Pressing the Save Modified Project Files button will update the files in the Project Scan Results listed above. Please make sure that you have created a backup of your project first as these file modifications are permanent and cannot be undone.", TMP_UIStyleManager.label); + GUILayout.Space(5f); + + GUI.enabled = m_IsAlreadyScanningProject == false && m_ModifiedAssetList.Count > 0 ? true : false; + if (GUILayout.Button("Save Modified Project Files")) + { + UpdateProjectFiles(); + } + GUILayout.Space(10f); + } + GUILayout.EndVertical(); + + } + GUILayout.EndVertical(); + GUILayout.Space(5f); + } + + void OnInspectorUpdate() + { + Repaint(); + } + + + /// + /// Limits the minimum size of the editor window. + /// + void SetEditorWindowSize() + { + EditorWindow editorWindow = this; + + Vector2 currentWindowSize = editorWindow.minSize; + + editorWindow.minSize = new Vector2(Mathf.Max(640, currentWindowSize.x), Mathf.Max(420, currentWindowSize.y)); + } + + + /// + /// + /// + /// + /// + private static bool ShouldIgnoreFile(string filePath) + { + string fileExtension = Path.GetExtension(filePath); + Type fileType = AssetDatabase.GetMainAssetTypeAtPath(filePath); + + if (m_IgnoreAssetTypes.Contains(fileType)) + return true; + + // Exclude FBX + if (fileType == typeof(GameObject) && fileExtension.ToLower() == ".fbx") { return true; } + return false; + } + + + private IEnumerator ScanProjectFiles() + { + m_IsAlreadyScanningProject = true; + string packageFullPath = EditorUtilities.TMP_EditorUtility.packageFullPath; + + // List containing assets that have been modified. + m_ProjectScanResults = k_ProjectScanReportDefaultText; + m_ModifiedAssetList.Clear(); + m_ProgressPercentage = 0; + + // Read Conversion Data from Json file. + if (m_ConversionData == null) + m_ConversionData = JsonUtility.FromJson(File.ReadAllText(packageFullPath + "/PackageConversionData.json")); + + // Get list of GUIDs for assets that might contain references to previous GUIDs that require updating. + string searchFolder = string.IsNullOrEmpty(m_ProjectFolderToScan) ? "Assets" : ("Assets/" + m_ProjectFolderToScan); + string[] guids = AssetDatabase.FindAssets("t:Object", new string[] { searchFolder }).Distinct().ToArray(); + + k_ProjectScanLabelPrefix = "Phase 1 - Filtering: "; + m_ScanningTotalFiles = guids.Length; + m_ScanningCurrentFileIndex = 0; + + List projectFilesToScan = new List(); + + foreach (var guid in guids) + { + if (m_CancelScanProcess) + break; + + string assetFilePath = AssetDatabase.GUIDToAssetPath(guid); + + m_ScanningCurrentFileIndex += 1; + m_ScanningCurrentFileName = assetFilePath; + m_ProgressPercentage = (float)m_ScanningCurrentFileIndex / m_ScanningTotalFiles; + + // Filter out file types we have no interest in searching + if (ShouldIgnoreFile(assetFilePath)) + continue; + + string assetMetaFilePath = AssetDatabase.GetTextMetaFilePathFromAssetPath(assetFilePath); + + projectFilesToScan.Add(new AssetFileRecord(assetFilePath, assetMetaFilePath)); + + yield return null; + } + + m_RemainingFilesToScan = m_ScanningTotalFiles = projectFilesToScan.Count; + + k_ProjectScanLabelPrefix = "Phase 2 - Scanning: "; + + for (int i = 0; i < m_ScanningTotalFiles; i++) + { + if (m_CancelScanProcess) + break; + + AssetFileRecord fileRecord = projectFilesToScan[i]; + + Task.Run(() => + { + ScanProjectFileAsync(fileRecord); + + m_ScanningCurrentFileName = fileRecord.assetFilePath; + + int completedScans = m_ScanningTotalFiles - Interlocked.Decrement(ref m_RemainingFilesToScan); + + m_ScanningCurrentFileIndex = completedScans; + m_ProgressPercentage = (float)completedScans / m_ScanningTotalFiles; + }); + + if (i % 64 == 0) + yield return new WaitForSeconds(2.0f); + + } + + while (m_RemainingFilesToScan > 0 && !m_CancelScanProcess) + yield return null; + + m_IsAlreadyScanningProject = false; + m_ScanningCurrentFileName = string.Empty; + } + + + static void ScanProjectFileAsync(AssetFileRecord fileRecord) + { + if (m_CancelScanProcess) + return; + + // Read the asset data file + string assetDataFile = string.Empty; + bool hasFileChanged = false; + + try + { + assetDataFile = File.ReadAllText(m_ProjectPath + "/" + fileRecord.assetFilePath); + } + catch + { + // Continue to the next asset if we can't read the current one. + return; + } + + // Read the asset meta data file + string assetMetaFile = File.ReadAllText(m_ProjectPath + "/" + fileRecord.assetMetaFilePath); + bool hasMetaFileChanges = false; + + foreach (AssetConversionRecord record in m_ConversionData.assetRecords) + { + if (assetDataFile.Contains(record.target)) + { + hasFileChanged = true; + + assetDataFile = assetDataFile.Replace(record.target, record.replacement); + } + + //// Check meta file + if (assetMetaFile.Contains(record.target)) + { + hasMetaFileChanges = true; + + assetMetaFile = assetMetaFile.Replace(record.target, record.replacement); + } + } + + if (hasFileChanged) + { + AssetModificationRecord modifiedAsset; + modifiedAsset.assetFilePath = fileRecord.assetFilePath; + modifiedAsset.assetDataFile = assetDataFile; + + m_ModifiedAssetList.Add(modifiedAsset); + + m_ProjectScanResults += fileRecord.assetFilePath + "\n"; + } + + if (hasMetaFileChanges) + { + AssetModificationRecord modifiedAsset; + modifiedAsset.assetFilePath = fileRecord.assetMetaFilePath; + modifiedAsset.assetDataFile = assetMetaFile; + + m_ModifiedAssetList.Add(modifiedAsset); + + m_ProjectScanResults += fileRecord.assetMetaFilePath + "\n"; + } + } + + + /// + /// + /// + private static void ResetScanProcess() + { + m_IsAlreadyScanningProject = false; + m_ScanningCurrentFileName = string.Empty; + m_ProgressPercentage = 0; + m_ScanningCurrentFileIndex = 0; + m_ScanningTotalFiles = 0; + } + + + /// + /// + /// + private static void UpdateProjectFiles() + { + // Make sure Asset Serialization mode is set to ForceText with Visible Meta Files. + CheckProjectSerializationAndSourceControlModes(); + + string projectPath = Path.GetFullPath("Assets/.."); + + // Display dialogue to show user a list of project files that will be modified upon their consent. + if (EditorUtility.DisplayDialog("Save Modified Asset(s)?", "Are you sure you want to save all modified assets?", "YES", "NO")) + { + for (int i = 0; i < m_ModifiedAssetList.Count; i++) + { + // Make sure all file streams that might have been opened by Unity are closed. + //AssetDatabase.ReleaseCachedFileHandles(); + + //Debug.Log("Writing asset file [" + m_ModifiedAssetList[i].assetFilePath + "]."); + + File.WriteAllText(projectPath + "/" + m_ModifiedAssetList[i].assetFilePath, m_ModifiedAssetList[i].assetDataFile); + } + } + + AssetDatabase.Refresh(); + + m_ProgressPercentage = 0; + m_ProjectScanResults = k_ProjectScanReportDefaultText; + } + + + /// + /// Check project Asset Serialization and Source Control modes + /// + private static bool CheckProjectSerializationAndSourceControlModes() + { + // Check Project Asset Serialization and Visible Meta Files mode. + if (EditorSettings.serializationMode != SerializationMode.ForceText || EditorSettings.externalVersionControl != "Visible Meta Files") + { + return false; + } + + return true; + } + } + + + + public class TMP_PackageUtilities : Editor + { + + enum SaveAssetDialogueOptions { Unset = 0, Save = 1, SaveAll = 2, DoNotSave = 3 }; + + private static SerializationMode m_ProjectAssetSerializationMode; + private static string m_ProjectExternalVersionControl; + + struct AssetRemappingRecord + { + public string oldGuid; + public string newGuid; + public string assetPath; + } + + struct AssetModificationRecord + { + public string assetFilePath; + public string assetDataFile; + } + + // Create Sprite Asset Editor Window + //[MenuItem("Window/TextMeshPro/Generate New Package GUIDs", false, 1500)] + public static void GenerateNewPackageGUIDs_Menu() + { + GenerateNewPackageGUIDs(); + } + + + /// + /// + /// + [MenuItem("Window/TextMeshPro/Import TMP Essential Resources", false, 2050)] + public static void ImportProjectResourcesMenu() + { + ImportProjectResources(); + } + + + /// + /// + /// + [MenuItem("Window/TextMeshPro/Import TMP Examples and Extras", false, 2051)] + public static void ImportExamplesContentMenu() + { + ImportExtraContent(); + } + + + // Create Sprite Asset Editor Window + //[MenuItem("Window/TextMeshPro/Convert TMP Project Files to UPM", false, 1510)] + public static void ConvertProjectGUIDsMenu() + { + ConvertProjectGUIDsToUPM(); + + //GetVersionInfo(); + } + + + // Create Sprite Asset Editor Window + //[MenuItem("Window/TextMeshPro/Convert GUID (Source to DLL)", false, 2010)] + public static void ConvertGUIDFromSourceToDLLMenu() + { + //ConvertGUIDFromSourceToDLL(); + + //GetVersionInfo(); + } + + + // Create Sprite Asset Editor Window + //[MenuItem("Window/TextMeshPro/Convert GUID (DLL to Source)", false, 2020)] + public static void ConvertGUIDFromDllToSourceMenu() + { + //ConvertGUIDFromDLLToSource(); + + //GetVersionInfo(); + } + + + // Create Sprite Asset Editor Window + //[MenuItem("Window/TextMeshPro/Extract Package GUIDs", false, 1530)] + public static void ExtractPackageGUIDMenu() + { + ExtractPackageGUIDs(); + } + + + private static void GetVersionInfo() + { + string version = TMP_Settings.version; + Debug.Log("The version of this TextMesh Pro UPM package is (" + version + ")."); + } + + + /// + /// + /// + private static void ImportExtraContent() + { + string packageFullPath = EditorUtilities.TMP_EditorUtility.packageFullPath; + + AssetDatabase.ImportPackage(packageFullPath + "/Package Resources/TMP Examples & Extras.unitypackage", true); + } + + + /// + /// + /// + private static void ImportProjectResources() + { + string packageFullPath = EditorUtilities.TMP_EditorUtility.packageFullPath; + + AssetDatabase.ImportPackage(packageFullPath + "/Package Resources/TMP Essential Resources.unitypackage", true); + } + + + /// + /// + /// + private static void GenerateNewPackageGUIDs() + { + // Make sure Asset Serialization mode is set to ForceText with Visible Meta Files. + SetProjectSerializationAndSourceControlModes(); + + string projectPath = Path.GetFullPath("Assets/.."); + + // Clear existing dictionary of AssetRecords + List assetRecords = new List(); + + // Get full list of GUIDs used in the package which including folders. + string[] packageGUIDs = AssetDatabase.FindAssets("t:Object", new string[] { "Assets/Packages/com.unity.TextMeshPro" }); + + for (int i = 0; i < packageGUIDs.Length; i++) + { + // Could add a progress bar for this process (if needed) + + string guid = packageGUIDs[i]; + string assetFilePath = AssetDatabase.GUIDToAssetPath(guid); + string assetMetaFilePath = AssetDatabase.GetTextMetaFilePathFromAssetPath(assetFilePath); + //System.Type assetType = AssetDatabase.GetMainAssetTypeAtPath(assetFilePath); + + AssetRemappingRecord assetRecord; + assetRecord.oldGuid = guid; + assetRecord.assetPath = assetFilePath; + + string newGUID = GenerateUniqueGUID(); + + assetRecord.newGuid = newGUID; + + if (assetRecords.FindIndex(item => item.oldGuid == guid) != -1) + continue; + + assetRecords.Add(assetRecord); + + // Read the meta file for the given asset. + string assetMetaFile = File.ReadAllText(projectPath + "/" + assetMetaFilePath); + + assetMetaFile = assetMetaFile.Replace("guid: " + guid, "guid: " + newGUID); + + File.WriteAllText(projectPath + "/" + assetMetaFilePath, assetMetaFile); + + //Debug.Log("Asset: [" + assetFilePath + "] Type: " + assetType + " Current GUID: [" + guid + "] New GUID: [" + newGUID + "]"); + } + + AssetDatabase.Refresh(); + + // Get list of GUIDs for assets that might need references to previous GUIDs which need to be updated. + packageGUIDs = AssetDatabase.FindAssets("t:Object"); // ("t:Object", new string[] { "Assets/Asset Importer" }); + + for (int i = 0; i < packageGUIDs.Length; i++) + { + // Could add a progress bar for this process + + string guid = packageGUIDs[i]; + string assetFilePath = AssetDatabase.GUIDToAssetPath(guid); + System.Type assetType = AssetDatabase.GetMainAssetTypeAtPath(assetFilePath); + + // Filter out file types we are not interested in + if (assetType == typeof(DefaultAsset) || assetType == typeof(MonoScript) || assetType == typeof(Texture2D) || assetType == typeof(TextAsset) || assetType == typeof(Shader)) + continue; + + // Read the asset data file + string assetDataFile = File.ReadAllText(projectPath + "/" + assetFilePath); + + //Debug.Log("Searching Asset: [" + assetFilePath + "] of type: " + assetType); + + bool hasFileChanged = false; + + foreach (AssetRemappingRecord record in assetRecords) + { + if (assetDataFile.Contains(record.oldGuid)) + { + hasFileChanged = true; + + assetDataFile = assetDataFile.Replace(record.oldGuid, record.newGuid); + + Debug.Log("Replacing old GUID: [" + record.oldGuid + "] by new GUID: [" + record.newGuid + "] in asset file: [" + assetFilePath + "]."); + } + } + + if (hasFileChanged) + { + // Add file to list of changed files + File.WriteAllText(projectPath + "/" + assetFilePath, assetDataFile); + } + + } + + AssetDatabase.Refresh(); + + // Restore project Asset Serialization and Source Control modes. + RestoreProjectSerializationAndSourceControlModes(); + } + + + private static void ExtractPackageGUIDs() + { + // Make sure Asset Serialization mode is set to ForceText with Visible Meta Files. + SetProjectSerializationAndSourceControlModes(); + + string projectPath = Path.GetFullPath("Assets/.."); + + // Create new instance of AssetConversionData file + AssetConversionData data = new AssetConversionData(); + data.assetRecords = new List(); + + // Get full list of GUIDs used in the package which including folders. + string[] packageGUIDs = AssetDatabase.FindAssets("t:Object", new string[] { "Assets/Packages/com.unity.TextMeshPro" }); + + for (int i = 0; i < packageGUIDs.Length; i++) + { + // Could add a progress bar for this process (if needed) + + string guid = packageGUIDs[i]; + string assetFilePath = AssetDatabase.GUIDToAssetPath(guid); + //string assetMetaFilePath = AssetDatabase.GetTextMetaFilePathFromAssetPath(assetFilePath); + + //ObjectIdentifier[] localIdentifider = BundleBuildInterface.GetPlayerObjectIdentifiersInAsset(new GUID(guid), BuildTarget.NoTarget); + //System.Type[] types = BundleBuildInterface.GetTypeForObjects(localIdentifider); + + System.Type assetType = AssetDatabase.GetMainAssetTypeAtPath(assetFilePath); + + // Filter out file types we are not interested in + if (assetType == typeof(DefaultAsset)) + continue; + + string newGuid = GenerateUniqueGUID(); + + AssetConversionRecord record; + record.referencedResource = Path.GetFileName(assetFilePath); + record.target = "fileID: 2108210716, guid: " + newGuid; + + record.replacement = "fileID: 11500000, guid: " + guid; + + //if (m_AssetRecords.FindIndex(item => item.oldGuid == guid) != -1) + // continue; + + data.assetRecords.Add(record); + + // Read the meta file for the given asset. + //string assetMetaFile = File.ReadAllText(projectPath + "/" + assetMetaFilePath); + + //assetMetaFile = assetMetaFile.Replace("guid: " + guid, "guid: " + newGUID); + + //File.WriteAllText(projectPath + "/" + assetMetaFilePath, assetMetaFile); + + Debug.Log("Asset: [" + Path.GetFileName(assetFilePath) + "] Type: " + assetType + " Current GUID: [" + guid + "] New GUID: [" + newGuid + "]"); + } + + // Write new information into JSON file + string dataFile = JsonUtility.ToJson(data, true); + + File.WriteAllText(projectPath + "/Assets/Packages/com.unity.TextMeshPro/PackageConversionData.json", dataFile); + + // Restore project Asset Serialization and Source Control modes. + RestoreProjectSerializationAndSourceControlModes(); + } + + + /// + /// + /// + private static void ConvertProjectGUIDsToUPM() + { + // Make sure Asset Serialization mode is set to ForceText with Visible Meta Files. + SetProjectSerializationAndSourceControlModes(); + + string projectPath = Path.GetFullPath("Assets/.."); + string packageFullPath = EditorUtilities.TMP_EditorUtility.packageFullPath; + + // List containing assets that have been modified. + List modifiedAssetList = new List(); + + // Read Conversion Data from Json file. + AssetConversionData conversionData = JsonUtility.FromJson(File.ReadAllText(packageFullPath + "/PackageConversionData.json")); + + // Get list of GUIDs for assets that might contain references to previous GUIDs that require updating. + string[] projectGUIDs = AssetDatabase.FindAssets("t:Object"); + + for (int i = 0; i < projectGUIDs.Length; i++) + { + // Could add a progress bar for this process + + string guid = projectGUIDs[i]; + string assetFilePath = AssetDatabase.GUIDToAssetPath(guid); + System.Type assetType = AssetDatabase.GetMainAssetTypeAtPath(assetFilePath); + + // Filter out file types we are not interested in + if (assetType == typeof(DefaultAsset) || assetType == typeof(MonoScript) || assetType == typeof(Texture2D) || assetType == typeof(TextAsset) || assetType == typeof(Shader)) + continue; + + // Read the asset data file + string assetDataFile = File.ReadAllText(projectPath + "/" + assetFilePath); + + //Debug.Log("Searching Asset: [" + assetFilePath + "] of type: " + assetType); + + bool hasFileChanged = false; + + foreach (AssetConversionRecord record in conversionData.assetRecords) + { + if (assetDataFile.Contains(record.target)) + { + hasFileChanged = true; + + assetDataFile = assetDataFile.Replace(record.target, record.replacement); + + Debug.Log("Replacing Reference to [" + record.referencedResource + "] using [" + record.target + "] with [" + record.replacement + "] in asset file: [" + assetFilePath + "]."); + } + } + + if (hasFileChanged) + { + Debug.Log("Adding [" + assetFilePath + "] to list of assets to be modified."); + + AssetModificationRecord modifiedAsset; + modifiedAsset.assetFilePath = assetFilePath; + modifiedAsset.assetDataFile = assetDataFile; + + modifiedAssetList.Add(modifiedAsset); + } + + } + + // Scan project meta files to update GUIDs of assets whose GUID has changed. + projectGUIDs = AssetDatabase.FindAssets("t:Object"); + + for (int i = 0; i < projectGUIDs.Length; i++) + { + string guid = projectGUIDs[i]; + string assetFilePath = AssetDatabase.GUIDToAssetPath(guid); + string assetMetaFilePath = AssetDatabase.GetTextMetaFilePathFromAssetPath(assetFilePath); + + // Read the asset meta data file + string assetMetaFile = File.ReadAllText(projectPath + "/" + assetMetaFilePath); + + bool hasFileChanged = false; + + foreach (AssetConversionRecord record in conversionData.assetRecords) + { + if (assetMetaFile.Contains(record.target)) + { + hasFileChanged = true; + + assetMetaFile = assetMetaFile.Replace(record.target, record.replacement); + + Debug.Log("Replacing Reference to [" + record.referencedResource + "] using [" + record.target + "] with [" + record.replacement + "] in asset file: [" + assetMetaFilePath + "]."); + } + } + + if (hasFileChanged) + { + Debug.Log("Adding [" + assetMetaFilePath + "] to list of meta files to be modified."); + + AssetModificationRecord modifiedAsset; + modifiedAsset.assetFilePath = assetMetaFilePath; + modifiedAsset.assetDataFile = assetMetaFile; + + modifiedAssetList.Add(modifiedAsset); + } + } + + // Display dialogue to show user a list of project files that will be modified upon their consent. + if (EditorUtility.DisplayDialog("Save Modified Asset(s)?", "Are you sure you want to save all modified assets?", "YES", "NO")) + { + for (int i = 0; i < modifiedAssetList.Count; i++) + { + // Make sure all file streams that might have been opened by Unity are closed. + //AssetDatabase.ReleaseCachedFileHandles(); + + Debug.Log("Writing asset file [" + modifiedAssetList[i].assetFilePath + "]."); + + //File.WriteAllText(projectPath + "/" + modifiedAssetList[i].assetFilePath, modifiedAssetList[i].assetDataFile); + } + + } + + AssetDatabase.Refresh(); + + // Restore project Asset Serialization and Source Control modes. + RestoreProjectSerializationAndSourceControlModes(); + } + + + /// + /// + /// + /// + private static string GenerateUniqueGUID() + { + string monoGuid = System.Guid.NewGuid().ToString(); + + char[] charGuid = new char[32]; + int index = 0; + for (int i = 0; i < monoGuid.Length; i++) + { + if (monoGuid[i] != '-') + charGuid[index++] = monoGuid[i]; + } + + string guid = new string(charGuid); + + // Make sure new GUID is not already used by some other asset. + if (AssetDatabase.GUIDToAssetPath(guid) != string.Empty) + guid = GenerateUniqueGUID(); + + return guid; + } + + + /// + /// Change project asset serialization mode to ForceText (if necessary) + /// + private static void SetProjectSerializationAndSourceControlModes() + { + // Make sure Asset Serialization mode is set to ForceText with Visible Meta Files. + m_ProjectAssetSerializationMode = EditorSettings.serializationMode; + if (m_ProjectAssetSerializationMode != SerializationMode.ForceText) + UnityEditor.EditorSettings.serializationMode = SerializationMode.ForceText; + + m_ProjectExternalVersionControl = EditorSettings.externalVersionControl; + if (m_ProjectExternalVersionControl != "Visible Meta Files") + UnityEditor.EditorSettings.externalVersionControl = "Visible Meta Files"; + } + + + /// + /// Revert potential change to asset serialization mode (if necessary) + /// + private static void RestoreProjectSerializationAndSourceControlModes() + { + // Make sure Asset Serialization mode is set to ForceText with Visible Meta Files. + if (m_ProjectAssetSerializationMode != EditorSettings.serializationMode) + EditorSettings.serializationMode = m_ProjectAssetSerializationMode; + + if (m_ProjectExternalVersionControl != EditorSettings.externalVersionControl) + EditorSettings.externalVersionControl = m_ProjectExternalVersionControl; + } + + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_PostBuildProcessHandler.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_PostBuildProcessHandler.cs new file mode 100644 index 00000000..a8b800ac --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_PostBuildProcessHandler.cs @@ -0,0 +1,63 @@ +using UnityEngine; +using UnityEditor; +using UnityEditor.Callbacks; +using System.IO; + + +namespace TMPro +{ + public class TMP_PostBuildProcessHandler + { + [PostProcessBuildAttribute(10000)] + public static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject) + { + // Check if TMP Essential Resource are present in user project. + if (target == BuildTarget.iOS && File.Exists(GetEssentialProjectResourcesPath() + "/Resources/TMP Settings.asset") && TMP_Settings.enableEmojiSupport) + { + string file = Path.Combine(pathToBuiltProject, "Classes/UI/Keyboard.mm"); + string content = File.ReadAllText(file); + content = content.Replace("FILTER_EMOJIS_IOS_KEYBOARD 1", "FILTER_EMOJIS_IOS_KEYBOARD 0"); + File.WriteAllText(file, content); + } + } + + + private static string GetEssentialProjectResourcesPath() + { + // Find the potential location of the TextMesh Pro folder in the user project. + string projectPath = Path.GetFullPath("Assets/.."); + if (Directory.Exists(projectPath)) + { + // Search for default location of TMP Essential Resources + if (Directory.Exists(projectPath + "/Assets/TextMesh Pro/Resources")) + { + return "Assets/TextMesh Pro"; + } + + // Search for potential alternative locations in the user project + string[] matchingPaths = Directory.GetDirectories(projectPath, "TextMesh Pro", SearchOption.AllDirectories); + projectPath = ValidateLocation(matchingPaths, projectPath); + if (projectPath != null) return projectPath; + } + + return null; + } + + + private static string ValidateLocation(string[] paths, string projectPath) + { + for (int i = 0; i < paths.Length; i++) + { + // Check if any of the matching directories contain a GUISkins directory. + if (Directory.Exists(paths[i] + "/Resources")) + { + string folderPath = paths[i].Replace(projectPath, ""); + folderPath = folderPath.TrimStart('\\', '/'); + return folderPath; + } + } + + return null; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_ProjectTextSettings.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_ProjectTextSettings.cs new file mode 100644 index 00000000..b8695be2 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_ProjectTextSettings.cs @@ -0,0 +1,43 @@ +#if !UNITY_2018_3_OR_NEWER +using UnityEditor; + +namespace TMPro +{ + + public static class TMP_ProjectTextSettings + { + // Open Project Text Settings + [MenuItem("Edit/Project Settings/TextMeshPro Settings", false, 309)] + public static void SelectProjectTextSettings() + { + TMP_Settings textSettings = TMP_Settings.instance; + + if (textSettings) + { + Selection.activeObject = textSettings; + + // TODO: Do we want to ping the Project Text Settings asset in the Project Inspector + EditorUtility.FocusProjectWindow(); + EditorGUIUtility.PingObject(textSettings); + } + else + TMPro_EventManager.RESOURCE_LOAD_EVENT.Add(ON_RESOURCES_LOADED); + } + + + // Event received when TMP resources have been loaded. + static void ON_RESOURCES_LOADED() + { + TMPro_EventManager.RESOURCE_LOAD_EVENT.Remove(ON_RESOURCES_LOADED); + + TMP_Settings textSettings = TMP_Settings.instance; + + Selection.activeObject = textSettings; + + // TODO: Do we want to ping the Project Text Settings asset in the Project Inspector + EditorUtility.FocusProjectWindow(); + EditorGUIUtility.PingObject(textSettings); + } + } +} +#endif \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_ResourcesLoader.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_ResourcesLoader.cs new file mode 100644 index 00000000..090bd774 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_ResourcesLoader.cs @@ -0,0 +1,68 @@ +using UnityEditor; +using UnityEngine; +using System.Collections; + +namespace TMPro.EditorUtilities +{ + + //[InitializeOnLoad] + class TMP_ResourcesLoader + { + + /// + /// Function to pre-load the TMP Resources + /// + public static void LoadTextMeshProResources() + { + //TMP_Settings.LoadDefaultSettings(); + //TMP_StyleSheet.LoadDefaultStyleSheet(); + } + + + static TMP_ResourcesLoader() + { + //Debug.Log("Loading TMP Resources..."); + + // Get current targetted platform + + + //string Settings = PlayerSettings.GetScriptingDefineSymbolsForGroup(BuildTargetGroup.Standalone); + //TMPro.TMP_Settings.LoadDefaultSettings(); + //TMPro.TMP_StyleSheet.LoadDefaultStyleSheet(); + } + + + + //[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] + //static void OnBeforeSceneLoaded() + //{ + //Debug.Log("Before scene is loaded."); + + // //TMPro.TMP_Settings.LoadDefaultSettings(); + // //TMPro.TMP_StyleSheet.LoadDefaultStyleSheet(); + + // //ShaderVariantCollection collection = new ShaderVariantCollection(); + // //Shader s0 = Shader.Find("TextMeshPro/Mobile/Distance Field"); + // //ShaderVariantCollection.ShaderVariant tmp_Variant = new ShaderVariantCollection.ShaderVariant(s0, UnityEngine.Rendering.PassType.Normal, string.Empty); + + // //collection.Add(tmp_Variant); + // //collection.WarmUp(); + //} + + } + + //static class TMP_ProjectSettings + //{ + // [InitializeOnLoadMethod] + // static void SetProjectDefineSymbols() + // { + // string currentBuildSettings = PlayerSettings.GetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup); + + // //Check for and inject TMP_INSTALLED + // if (!currentBuildSettings.Contains("TMP_PRESENT")) + // { + // PlayerSettings.SetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup, currentBuildSettings + ";TMP_PRESENT"); + // } + // } + //} +} diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_SDFShaderGUI.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_SDFShaderGUI.cs new file mode 100644 index 00000000..2728f26f --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_SDFShaderGUI.cs @@ -0,0 +1,442 @@ +using UnityEngine; +using UnityEditor; + +namespace TMPro.EditorUtilities +{ + public class TMP_SDFShaderGUI : TMP_BaseShaderGUI + { + static ShaderFeature s_OutlineFeature, s_UnderlayFeature, s_BevelFeature, s_GlowFeature, s_MaskFeature; + + static bool s_Face = true, s_Outline = true, s_Underlay, s_Lighting, s_Glow, s_Bevel, s_Light, s_Bump, s_Env; + + static string[] + s_FaceUvSpeedNames = { "_FaceUVSpeedX", "_FaceUVSpeedY" }, + s_OutlineUvSpeedNames = { "_OutlineUVSpeedX", "_OutlineUVSpeedY" }; + + static TMP_SDFShaderGUI() + { + s_OutlineFeature = new ShaderFeature() + { + undoLabel = "Outline", + keywords = new[] { "OUTLINE_ON" } + }; + + s_UnderlayFeature = new ShaderFeature() + { + undoLabel = "Underlay", + keywords = new[] { "UNDERLAY_ON", "UNDERLAY_INNER" }, + label = new GUIContent("Underlay Type"), + keywordLabels = new[] + { + new GUIContent("None"), new GUIContent("Normal"), new GUIContent("Inner") + } + }; + + s_BevelFeature = new ShaderFeature() + { + undoLabel = "Bevel", + keywords = new[] { "BEVEL_ON" } + }; + + s_GlowFeature = new ShaderFeature() + { + undoLabel = "Glow", + keywords = new[] { "GLOW_ON" } + }; + + s_MaskFeature = new ShaderFeature() + { + undoLabel = "Mask", + keywords = new[] { "MASK_HARD", "MASK_SOFT" }, + label = new GUIContent("Mask"), + keywordLabels = new[] + { + new GUIContent("Mask Off"), new GUIContent("Mask Hard"), new GUIContent("Mask Soft") + } + }; + } + + protected override void DoGUI() + { + s_Face = BeginPanel("Face", s_Face); + if (s_Face) + { + DoFacePanel(); + } + + EndPanel(); + + s_Outline = m_Material.HasProperty(ShaderUtilities.ID_OutlineTex) ? BeginPanel("Outline", s_Outline) : BeginPanel("Outline", s_OutlineFeature, s_Outline); + if (s_Outline) + { + DoOutlinePanel(); + } + + EndPanel(); + + if (m_Material.HasProperty(ShaderUtilities.ID_UnderlayColor)) + { + s_Underlay = BeginPanel("Underlay", s_UnderlayFeature, s_Underlay); + if (s_Underlay) + { + DoUnderlayPanel(); + } + + EndPanel(); + } + + if (m_Material.HasProperty("_SpecularColor")) + { + s_Lighting = BeginPanel("Lighting", s_BevelFeature, s_Lighting); + if (s_Lighting) + { + s_Bevel = BeginPanel("Bevel", s_Bevel); + if (s_Bevel) + { + DoBevelPanel(); + } + + EndPanel(); + + s_Light = BeginPanel("Local Lighting", s_Light); + if (s_Light) + { + DoLocalLightingPanel(); + } + + EndPanel(); + + s_Bump = BeginPanel("Bump Map", s_Bump); + if (s_Bump) + { + DoBumpMapPanel(); + } + + EndPanel(); + + s_Env = BeginPanel("Environment Map", s_Env); + if (s_Env) + { + DoEnvMapPanel(); + } + + EndPanel(); + } + + EndPanel(); + } + else if (m_Material.HasProperty("_SpecColor")) + { + s_Bevel = BeginPanel("Bevel", s_Bevel); + if (s_Bevel) + { + DoBevelPanel(); + } + + EndPanel(); + + s_Light = BeginPanel("Surface Lighting", s_Light); + if (s_Light) + { + DoSurfaceLightingPanel(); + } + + EndPanel(); + + s_Bump = BeginPanel("Bump Map", s_Bump); + if (s_Bump) + { + DoBumpMapPanel(); + } + + EndPanel(); + + s_Env = BeginPanel("Environment Map", s_Env); + if (s_Env) + { + DoEnvMapPanel(); + } + + EndPanel(); + } + + if (m_Material.HasProperty(ShaderUtilities.ID_GlowColor)) + { + s_Glow = BeginPanel("Glow", s_GlowFeature, s_Glow); + if (s_Glow) + { + DoGlowPanel(); + } + + EndPanel(); + } + + s_DebugExtended = BeginPanel("Debug Settings", s_DebugExtended); + if (s_DebugExtended) + { + DoDebugPanel(); + } + + EndPanel(); + } + + void DoFacePanel() + { + EditorGUI.indentLevel += 1; + DoColor("_FaceColor", "Color"); + if (m_Material.HasProperty(ShaderUtilities.ID_FaceTex)) + { + if (m_Material.HasProperty("_FaceUVSpeedX")) + { + DoTexture2D("_FaceTex", "Texture", true, s_FaceUvSpeedNames); + } + else + { + DoTexture2D("_FaceTex", "Texture", true); + } + } + + DoSlider("_OutlineSoftness", "Softness"); + DoSlider("_FaceDilate", "Dilate"); + if (m_Material.HasProperty(ShaderUtilities.ID_Shininess)) + { + DoSlider("_FaceShininess", "Gloss"); + } + + EditorGUI.indentLevel -= 1; + EditorGUILayout.Space(); + } + + void DoOutlinePanel() + { + EditorGUI.indentLevel += 1; + DoColor("_OutlineColor", "Color"); + if (m_Material.HasProperty(ShaderUtilities.ID_OutlineTex)) + { + if (m_Material.HasProperty("_OutlineUVSpeedX")) + { + DoTexture2D("_OutlineTex", "Texture", true, s_OutlineUvSpeedNames); + } + else + { + DoTexture2D("_OutlineTex", "Texture", true); + } + } + + DoSlider("_OutlineWidth", "Thickness"); + if (m_Material.HasProperty("_OutlineShininess")) + { + DoSlider("_OutlineShininess", "Gloss"); + } + + EditorGUI.indentLevel -= 1; + EditorGUILayout.Space(); + } + + void DoUnderlayPanel() + { + EditorGUI.indentLevel += 1; + s_UnderlayFeature.DoPopup(m_Editor, m_Material); + DoColor("_UnderlayColor", "Color"); + DoSlider("_UnderlayOffsetX", "Offset X"); + DoSlider("_UnderlayOffsetY", "Offset Y"); + DoSlider("_UnderlayDilate", "Dilate"); + DoSlider("_UnderlaySoftness", "Softness"); + EditorGUI.indentLevel -= 1; + EditorGUILayout.Space(); + } + + static GUIContent[] s_BevelTypeLabels = + { + new GUIContent("Outer Bevel"), + new GUIContent("Inner Bevel") + }; + + void DoBevelPanel() + { + EditorGUI.indentLevel += 1; + DoPopup("_ShaderFlags", "Type", s_BevelTypeLabels); + DoSlider("_Bevel", "Amount"); + DoSlider("_BevelOffset", "Offset"); + DoSlider("_BevelWidth", "Width"); + DoSlider("_BevelRoundness", "Roundness"); + DoSlider("_BevelClamp", "Clamp"); + EditorGUI.indentLevel -= 1; + EditorGUILayout.Space(); + } + + void DoLocalLightingPanel() + { + EditorGUI.indentLevel += 1; + DoSlider("_LightAngle", "Light Angle"); + DoColor("_SpecularColor", "Specular Color"); + DoSlider("_SpecularPower", "Specular Power"); + DoSlider("_Reflectivity", "Reflectivity Power"); + DoSlider("_Diffuse", "Diffuse Shadow"); + DoSlider("_Ambient", "Ambient Shadow"); + EditorGUI.indentLevel -= 1; + EditorGUILayout.Space(); + } + + void DoSurfaceLightingPanel() + { + EditorGUI.indentLevel += 1; + DoColor("_SpecColor", "Specular Color"); + EditorGUI.indentLevel -= 1; + EditorGUILayout.Space(); + } + + void DoBumpMapPanel() + { + EditorGUI.indentLevel += 1; + DoTexture2D("_BumpMap", "Texture"); + DoSlider("_BumpFace", "Face"); + DoSlider("_BumpOutline", "Outline"); + EditorGUI.indentLevel -= 1; + EditorGUILayout.Space(); + } + + void DoEnvMapPanel() + { + EditorGUI.indentLevel += 1; + DoColor("_ReflectFaceColor", "Face Color"); + DoColor("_ReflectOutlineColor", "Outline Color"); + DoCubeMap("_Cube", "Texture"); + DoVector3("_EnvMatrixRotation", "Rotation"); + EditorGUI.indentLevel -= 1; + EditorGUILayout.Space(); + } + + void DoGlowPanel() + { + EditorGUI.indentLevel += 1; + DoColor("_GlowColor", "Color"); + DoSlider("_GlowOffset", "Offset"); + DoSlider("_GlowInner", "Inner"); + DoSlider("_GlowOuter", "Outer"); + DoSlider("_GlowPower", "Power"); + EditorGUI.indentLevel -= 1; + EditorGUILayout.Space(); + } + + void DoDebugPanel() + { + EditorGUI.indentLevel += 1; + DoTexture2D("_MainTex", "Font Atlas"); + DoFloat("_GradientScale", "Gradient Scale"); + DoFloat("_TextureWidth", "Texture Width"); + DoFloat("_TextureHeight", "Texture Height"); + EditorGUILayout.Space(); + DoFloat("_ScaleX", "Scale X"); + DoFloat("_ScaleY", "Scale Y"); + + if (m_Material.HasProperty(ShaderUtilities.ID_Sharpness)) + DoSlider("_Sharpness", "Sharpness"); + + DoSlider("_PerspectiveFilter", "Perspective Filter"); + EditorGUILayout.Space(); + DoFloat("_VertexOffsetX", "Offset X"); + DoFloat("_VertexOffsetY", "Offset Y"); + + if (m_Material.HasProperty(ShaderUtilities.ID_MaskCoord)) + { + EditorGUILayout.Space(); + s_MaskFeature.ReadState(m_Material); + s_MaskFeature.DoPopup(m_Editor, m_Material); + if (s_MaskFeature.Active) + { + DoMaskSubgroup(); + } + + EditorGUILayout.Space(); + DoVector("_ClipRect", "Clip Rect", s_LbrtVectorLabels); + } + else if (m_Material.HasProperty("_MaskTex")) + { + DoMaskTexSubgroup(); + } + else if (m_Material.HasProperty(ShaderUtilities.ID_MaskSoftnessX)) + { + EditorGUILayout.Space(); + DoFloat("_MaskSoftnessX", "Softness X"); + DoFloat("_MaskSoftnessY", "Softness Y"); + DoVector("_ClipRect", "Clip Rect", s_LbrtVectorLabels); + } + + if (m_Material.HasProperty(ShaderUtilities.ID_StencilID)) + { + EditorGUILayout.Space(); + DoFloat("_Stencil", "Stencil ID"); + DoFloat("_StencilComp", "Stencil Comp"); + } + + EditorGUILayout.Space(); + + EditorGUI.BeginChangeCheck(); + bool useRatios = EditorGUILayout.Toggle("Use Ratios", !m_Material.IsKeywordEnabled("RATIOS_OFF")); + if (EditorGUI.EndChangeCheck()) + { + m_Editor.RegisterPropertyChangeUndo("Use Ratios"); + if (useRatios) + { + m_Material.DisableKeyword("RATIOS_OFF"); + } + else + { + m_Material.EnableKeyword("RATIOS_OFF"); + } + } + + EditorGUI.BeginDisabledGroup(true); + DoFloat("_ScaleRatioA", "Scale Ratio A"); + DoFloat("_ScaleRatioB", "Scale Ratio B"); + DoFloat("_ScaleRatioC", "Scale Ratio C"); + EditorGUI.EndDisabledGroup(); + EditorGUI.indentLevel -= 1; + EditorGUILayout.Space(); + } + + void DoMaskSubgroup() + { + DoVector("_MaskCoord", "Mask Bounds", s_XywhVectorLabels); + if (Selection.activeGameObject != null) + { + Renderer renderer = Selection.activeGameObject.GetComponent(); + if (renderer != null) + { + Rect rect = EditorGUILayout.GetControlRect(); + rect.x += EditorGUIUtility.labelWidth; + rect.width -= EditorGUIUtility.labelWidth; + if (GUI.Button(rect, "Match Renderer Bounds")) + { + FindProperty("_MaskCoord", m_Properties).vectorValue = new Vector4( + 0, + 0, + Mathf.Round(renderer.bounds.extents.x * 1000) / 1000, + Mathf.Round(renderer.bounds.extents.y * 1000) / 1000 + ); + } + } + } + + if (s_MaskFeature.State == 1) + { + DoFloat("_MaskSoftnessX", "Softness X"); + DoFloat("_MaskSoftnessY", "Softness Y"); + } + } + + void DoMaskTexSubgroup() + { + EditorGUILayout.Space(); + DoTexture2D("_MaskTex", "Mask Texture"); + DoToggle("_MaskInverse", "Inverse Mask"); + DoColor("_MaskEdgeColor", "Edge Color"); + DoSlider("_MaskEdgeSoftness", "Edge Softness"); + DoSlider("_MaskWipeControl", "Wipe Position"); + DoFloat("_MaskSoftnessX", "Softness X"); + DoFloat("_MaskSoftnessY", "Softness Y"); + DoVector("_ClipRect", "Clip Rect", s_LbrtVectorLabels); + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_SerializedPropertyHolder.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_SerializedPropertyHolder.cs new file mode 100644 index 00000000..2ba34d69 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_SerializedPropertyHolder.cs @@ -0,0 +1,14 @@ +using UnityEngine; +using UnityEditor; + +namespace TMPro +{ + class TMP_SerializedPropertyHolder : ScriptableObject + { + public TMP_FontAsset fontAsset; + public uint firstCharacter; + public uint secondCharacter; + + public TMP_GlyphPairAdjustmentRecord glyphPairAdjustmentRecord = new TMP_GlyphPairAdjustmentRecord(new TMP_GlyphAdjustmentRecord(), new TMP_GlyphAdjustmentRecord()); + } +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_SettingsEditor.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_SettingsEditor.cs new file mode 100644 index 00000000..571c9cd3 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_SettingsEditor.cs @@ -0,0 +1,341 @@ +using System.Collections.Generic; +using UnityEngine; +using UnityEditor; +using UnityEditorInternal; + +#pragma warning disable 0414 // Disabled a few warnings for not yet implemented features. + +namespace TMPro.EditorUtilities +{ + [CustomEditor(typeof(TMP_Settings))] + public class TMP_SettingsEditor : Editor + { + internal class Styles + { + public static readonly GUIContent defaultFontAssetLabel = new GUIContent("Default Font Asset", "The Font Asset that will be assigned by default to newly created text objects when no Font Asset is specified."); + public static readonly GUIContent defaultFontAssetPathLabel = new GUIContent("Path: Resources/", "The relative path to a Resources folder where the Font Assets and Material Presets are located.\nExample \"Fonts & Materials/\""); + + public static readonly GUIContent fallbackFontAssetsLabel = new GUIContent("Fallback Font Assets", "The Font Assets that will be searched to locate and replace missing characters from a given Font Asset."); + public static readonly GUIContent fallbackFontAssetsListLabel = new GUIContent("Fallback Font Assets List", "The Font Assets that will be searched to locate and replace missing characters from a given Font Asset."); + + public static readonly GUIContent fallbackMaterialSettingsLabel = new GUIContent("Fallback Material Settings"); + public static readonly GUIContent matchMaterialPresetLabel = new GUIContent("Match Material Presets"); + + public static readonly GUIContent containerDefaultSettingsLabel = new GUIContent("Text Container Default Settings"); + + public static readonly GUIContent textMeshProLabel = new GUIContent("TextMeshPro"); + public static readonly GUIContent textMeshProUiLabel = new GUIContent("TextMeshPro UI"); + public static readonly GUIContent enableRaycastTarget = new GUIContent("Enable Raycast Target"); + public static readonly GUIContent autoSizeContainerLabel = new GUIContent("Auto Size Text Container", "Set the size of the text container to match the text."); + + public static readonly GUIContent textComponentDefaultSettingsLabel = new GUIContent("Text Component Default Settings"); + public static readonly GUIContent defaultFontSize = new GUIContent("Default Font Size"); + public static readonly GUIContent autoSizeRatioLabel = new GUIContent("Text Auto Size Ratios"); + public static readonly GUIContent minLabel = new GUIContent("Min"); + public static readonly GUIContent maxLabel = new GUIContent("Max"); + + public static readonly GUIContent wordWrappingLabel = new GUIContent("Word Wrapping"); + public static readonly GUIContent kerningLabel = new GUIContent("Kerning"); + public static readonly GUIContent extraPaddingLabel = new GUIContent("Extra Padding"); + public static readonly GUIContent tintAllSpritesLabel = new GUIContent("Tint All Sprites"); + public static readonly GUIContent parseEscapeCharactersLabel = new GUIContent("Parse Escape Sequence"); + + public static readonly GUIContent dynamicFontSystemSettingsLabel = new GUIContent("Dynamic Font System Settings"); + public static readonly GUIContent getFontFeaturesAtRuntime = new GUIContent("Get Font Features at Runtime", "Determines if Glyph Adjustment Data will be retrieved from font files at runtime when new characters and glyphs are added to font assets."); + + public static readonly GUIContent missingGlyphLabel = new GUIContent("Replacement Character", "The character to be displayed when the requested character is not found in any font asset or fallbacks."); + public static readonly GUIContent disableWarningsLabel = new GUIContent("Disable warnings", "Disable warning messages in the Console."); + + public static readonly GUIContent defaultSpriteAssetLabel = new GUIContent("Default Sprite Asset", "The Sprite Asset that will be assigned by default when using the tag when no Sprite Asset is specified."); + public static readonly GUIContent enableEmojiSupportLabel = new GUIContent("iOS Emoji Support", "Enables Emoji support for Touch Screen Keyboards on target devices."); + public static readonly GUIContent spriteAssetsPathLabel = new GUIContent("Path: Resources/", "The relative path to a Resources folder where the Sprite Assets are located.\nExample \"Sprite Assets/\""); + + public static readonly GUIContent defaultStyleSheetLabel = new GUIContent("Default Style Sheet", "The Style Sheet that will be used for all text objects in this project."); + + public static readonly GUIContent colorGradientPresetsLabel = new GUIContent("Color Gradient Presets", "The relative path to a Resources folder where the Color Gradient Presets are located.\nExample \"Color Gradient Presets/\""); + public static readonly GUIContent colorGradientsPathLabel = new GUIContent("Path: Resources/", "The relative path to a Resources folder where the Color Gradient Presets are located.\nExample \"Color Gradient Presets/\""); + + public static readonly GUIContent lineBreakingLabel = new GUIContent("Line Breaking for Asian languages", "The text assets that contain the Leading and Following characters which define the rules for line breaking with Asian languages."); + } + + SerializedProperty m_PropFontAsset; + SerializedProperty m_PropDefaultFontAssetPath; + SerializedProperty m_PropDefaultFontSize; + SerializedProperty m_PropDefaultAutoSizeMinRatio; + SerializedProperty m_PropDefaultAutoSizeMaxRatio; + SerializedProperty m_PropDefaultTextMeshProTextContainerSize; + SerializedProperty m_PropDefaultTextMeshProUITextContainerSize; + SerializedProperty m_PropAutoSizeTextContainer; + SerializedProperty m_PropEnableRaycastTarget; + + SerializedProperty m_PropSpriteAsset; + SerializedProperty m_PropSpriteAssetPath; + SerializedProperty m_PropEnableEmojiSupport; + SerializedProperty m_PropStyleSheet; + ReorderableList m_List; + + SerializedProperty m_PropColorGradientPresetsPath; + + SerializedProperty m_PropMatchMaterialPreset; + SerializedProperty m_PropWordWrapping; + SerializedProperty m_PropKerning; + SerializedProperty m_PropExtraPadding; + SerializedProperty m_PropTintAllSprites; + SerializedProperty m_PropParseEscapeCharacters; + SerializedProperty m_PropMissingGlyphCharacter; + + SerializedProperty m_GetFontFeaturesAtRuntime; + + SerializedProperty m_PropWarningsDisabled; + + SerializedProperty m_PropLeadingCharacters; + SerializedProperty m_PropFollowingCharacters; + + public void OnEnable() + { + if (target == null) + return; + + m_PropFontAsset = serializedObject.FindProperty("m_defaultFontAsset"); + m_PropDefaultFontAssetPath = serializedObject.FindProperty("m_defaultFontAssetPath"); + m_PropDefaultFontSize = serializedObject.FindProperty("m_defaultFontSize"); + m_PropDefaultAutoSizeMinRatio = serializedObject.FindProperty("m_defaultAutoSizeMinRatio"); + m_PropDefaultAutoSizeMaxRatio = serializedObject.FindProperty("m_defaultAutoSizeMaxRatio"); + m_PropDefaultTextMeshProTextContainerSize = serializedObject.FindProperty("m_defaultTextMeshProTextContainerSize"); + m_PropDefaultTextMeshProUITextContainerSize = serializedObject.FindProperty("m_defaultTextMeshProUITextContainerSize"); + m_PropAutoSizeTextContainer = serializedObject.FindProperty("m_autoSizeTextContainer"); + m_PropEnableRaycastTarget = serializedObject.FindProperty("m_EnableRaycastTarget"); + + m_PropSpriteAsset = serializedObject.FindProperty("m_defaultSpriteAsset"); + m_PropSpriteAssetPath = serializedObject.FindProperty("m_defaultSpriteAssetPath"); + m_PropEnableEmojiSupport = serializedObject.FindProperty("m_enableEmojiSupport"); + m_PropStyleSheet = serializedObject.FindProperty("m_defaultStyleSheet"); + m_PropColorGradientPresetsPath = serializedObject.FindProperty("m_defaultColorGradientPresetsPath"); + + m_List = new ReorderableList(serializedObject, serializedObject.FindProperty("m_fallbackFontAssets"), true, true, true, true); + + m_List.drawElementCallback = (rect, index, isActive, isFocused) => + { + var element = m_List.serializedProperty.GetArrayElementAtIndex(index); + rect.y += 2; + EditorGUI.PropertyField(new Rect(rect.x, rect.y, rect.width, EditorGUIUtility.singleLineHeight), element, GUIContent.none); + }; + + m_List.drawHeaderCallback = rect => + { + EditorGUI.LabelField(rect, Styles.fallbackFontAssetsListLabel); + }; + + m_PropMatchMaterialPreset = serializedObject.FindProperty("m_matchMaterialPreset"); + + m_PropWordWrapping = serializedObject.FindProperty("m_enableWordWrapping"); + m_PropKerning = serializedObject.FindProperty("m_enableKerning"); + m_PropExtraPadding = serializedObject.FindProperty("m_enableExtraPadding"); + m_PropTintAllSprites = serializedObject.FindProperty("m_enableTintAllSprites"); + m_PropParseEscapeCharacters = serializedObject.FindProperty("m_enableParseEscapeCharacters"); + m_PropMissingGlyphCharacter = serializedObject.FindProperty("m_missingGlyphCharacter"); + + m_PropWarningsDisabled = serializedObject.FindProperty("m_warningsDisabled"); + + m_GetFontFeaturesAtRuntime = serializedObject.FindProperty("m_GetFontFeaturesAtRuntime"); + + m_PropLeadingCharacters = serializedObject.FindProperty("m_leadingCharacters"); + m_PropFollowingCharacters = serializedObject.FindProperty("m_followingCharacters"); + } + + public override void OnInspectorGUI() + { + serializedObject.Update(); + + float labelWidth = EditorGUIUtility.labelWidth; + float fieldWidth = EditorGUIUtility.fieldWidth; + + // TextMeshPro Font Info Panel + EditorGUI.indentLevel = 0; + + // FONT ASSET + EditorGUILayout.BeginVertical(EditorStyles.helpBox); + GUILayout.Label(Styles.defaultFontAssetLabel, EditorStyles.boldLabel); + EditorGUI.indentLevel = 1; + EditorGUILayout.PropertyField(m_PropFontAsset, Styles.defaultFontAssetLabel); + EditorGUILayout.PropertyField(m_PropDefaultFontAssetPath, Styles.defaultFontAssetPathLabel); + EditorGUI.indentLevel = 0; + + EditorGUILayout.Space(); + EditorGUILayout.EndVertical(); + + // FALLBACK FONT ASSETs + EditorGUILayout.BeginVertical(EditorStyles.helpBox); + GUILayout.Label(Styles.fallbackFontAssetsLabel, EditorStyles.boldLabel); + m_List.DoLayoutList(); + + GUILayout.Label(Styles.fallbackMaterialSettingsLabel, EditorStyles.boldLabel); + EditorGUI.indentLevel = 1; + EditorGUILayout.PropertyField(m_PropMatchMaterialPreset, Styles.matchMaterialPresetLabel); + EditorGUI.indentLevel = 0; + + EditorGUILayout.Space(); + EditorGUILayout.EndVertical(); + + // MISSING GLYPHS + EditorGUILayout.BeginVertical(EditorStyles.helpBox); + GUILayout.Label(Styles.dynamicFontSystemSettingsLabel, EditorStyles.boldLabel); + EditorGUI.indentLevel = 1; + EditorGUILayout.PropertyField(m_GetFontFeaturesAtRuntime, Styles.getFontFeaturesAtRuntime); + EditorGUILayout.PropertyField(m_PropMissingGlyphCharacter, Styles.missingGlyphLabel); + EditorGUILayout.PropertyField(m_PropWarningsDisabled, Styles.disableWarningsLabel); + EditorGUI.indentLevel = 0; + + EditorGUILayout.Space(); + EditorGUILayout.EndVertical(); + + // TEXT OBJECT DEFAULT PROPERTIES + EditorGUILayout.BeginVertical(EditorStyles.helpBox); + GUILayout.Label(Styles.containerDefaultSettingsLabel, EditorStyles.boldLabel); + EditorGUI.indentLevel = 1; + + EditorGUILayout.PropertyField(m_PropDefaultTextMeshProTextContainerSize, Styles.textMeshProLabel); + EditorGUILayout.PropertyField(m_PropDefaultTextMeshProUITextContainerSize, Styles.textMeshProUiLabel); + EditorGUILayout.PropertyField(m_PropEnableRaycastTarget, Styles.enableRaycastTarget); + EditorGUILayout.PropertyField(m_PropAutoSizeTextContainer, Styles.autoSizeContainerLabel); + EditorGUI.indentLevel = 0; + + EditorGUILayout.Space(); + + GUILayout.Label(Styles.textComponentDefaultSettingsLabel, EditorStyles.boldLabel); + EditorGUI.indentLevel = 1; + EditorGUILayout.PropertyField(m_PropDefaultFontSize, Styles.defaultFontSize); + + EditorGUILayout.BeginHorizontal(); + { + EditorGUILayout.PrefixLabel(Styles.autoSizeRatioLabel); + EditorGUIUtility.labelWidth = 32; + EditorGUIUtility.fieldWidth = 10; + + EditorGUI.indentLevel = 0; + EditorGUILayout.PropertyField(m_PropDefaultAutoSizeMinRatio, Styles.minLabel); + EditorGUILayout.PropertyField(m_PropDefaultAutoSizeMaxRatio, Styles.maxLabel); + EditorGUI.indentLevel = 1; + } + EditorGUILayout.EndHorizontal(); + + EditorGUIUtility.labelWidth = labelWidth; + EditorGUIUtility.fieldWidth = fieldWidth; + + EditorGUILayout.PropertyField(m_PropWordWrapping, Styles.wordWrappingLabel); + EditorGUILayout.PropertyField(m_PropKerning, Styles.kerningLabel); + + EditorGUILayout.PropertyField(m_PropExtraPadding, Styles.extraPaddingLabel); + EditorGUILayout.PropertyField(m_PropTintAllSprites, Styles.tintAllSpritesLabel); + + EditorGUILayout.PropertyField(m_PropParseEscapeCharacters, Styles.parseEscapeCharactersLabel); + + EditorGUI.indentLevel = 0; + + EditorGUILayout.Space(); + EditorGUILayout.EndVertical(); + + // SPRITE ASSET + EditorGUILayout.BeginVertical(EditorStyles.helpBox); + GUILayout.Label(Styles.defaultSpriteAssetLabel, EditorStyles.boldLabel); + EditorGUI.indentLevel = 1; + EditorGUILayout.PropertyField(m_PropSpriteAsset, Styles.defaultSpriteAssetLabel); + EditorGUILayout.PropertyField(m_PropEnableEmojiSupport, Styles.enableEmojiSupportLabel); + EditorGUILayout.PropertyField(m_PropSpriteAssetPath, Styles.spriteAssetsPathLabel); + EditorGUI.indentLevel = 0; + + EditorGUILayout.Space(); + EditorGUILayout.EndVertical(); + + // STYLE SHEET + EditorGUILayout.BeginVertical(EditorStyles.helpBox); + GUILayout.Label(Styles.defaultStyleSheetLabel, EditorStyles.boldLabel); + EditorGUI.indentLevel = 1; + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(m_PropStyleSheet, Styles.defaultStyleSheetLabel); + if (EditorGUI.EndChangeCheck()) + { + serializedObject.ApplyModifiedProperties(); + TMP_StyleSheet.UpdateStyleSheet(); + } + EditorGUI.indentLevel = 0; + + EditorGUILayout.Space(); + EditorGUILayout.EndVertical(); + + // COLOR GRADIENT PRESETS + EditorGUILayout.BeginVertical(EditorStyles.helpBox); + GUILayout.Label(Styles.colorGradientPresetsLabel, EditorStyles.boldLabel); + EditorGUI.indentLevel = 1; + EditorGUILayout.PropertyField(m_PropColorGradientPresetsPath, Styles.colorGradientsPathLabel); + EditorGUI.indentLevel = 0; + + EditorGUILayout.Space(); + EditorGUILayout.EndVertical(); + + // LINE BREAKING RULE + EditorGUILayout.BeginVertical(EditorStyles.helpBox); + GUILayout.Label(Styles.lineBreakingLabel, EditorStyles.boldLabel); + EditorGUI.indentLevel = 1; + EditorGUILayout.PropertyField(m_PropLeadingCharacters); + EditorGUILayout.PropertyField(m_PropFollowingCharacters); + EditorGUI.indentLevel = 0; + + EditorGUILayout.Space(); + EditorGUILayout.EndVertical(); + + if (serializedObject.ApplyModifiedProperties()) + { + EditorUtility.SetDirty(target); + TMPro_EventManager.ON_TMP_SETTINGS_CHANGED(); + } + } + } + +#if UNITY_2018_3_OR_NEWER + class TMP_ResourceImporterProvider : SettingsProvider + { + TMP_PackageResourceImporter m_ResourceImporter; + + public TMP_ResourceImporterProvider() + : base("Project/TextMesh Pro", SettingsScope.Project) + { + } + + public override void OnGUI(string searchContext) + { + // Lazy creation that supports domain reload + if (m_ResourceImporter == null) + m_ResourceImporter = new TMP_PackageResourceImporter(); + + m_ResourceImporter.OnGUI(); + } + + public override void OnDeactivate() + { + if (m_ResourceImporter != null) + m_ResourceImporter.OnDestroy(); + } + + static UnityEngine.Object GetTMPSettings() + { + return Resources.Load("TMP Settings"); + } + + [SettingsProviderGroup] + static SettingsProvider[] CreateTMPSettingsProvider() + { + var providers = new List { new TMP_ResourceImporterProvider() }; + + if (GetTMPSettings() != null) + { + var provider = new AssetSettingsProvider("Project/TextMesh Pro/Settings", GetTMPSettings); + provider.PopulateSearchKeywordsFromGUIContentProperties(); + providers.Add(provider); + } + + return providers.ToArray(); + } + } +#endif +} diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_SpriteAssetEditor.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_SpriteAssetEditor.cs new file mode 100644 index 00000000..4df588ef --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_SpriteAssetEditor.cs @@ -0,0 +1,896 @@ +using UnityEngine; +using UnityEngine.TextCore; +using UnityEditor; +using UnityEditorInternal; +using System.Collections.Generic; + + + + +namespace TMPro.EditorUtilities +{ + + [CustomEditor(typeof(TMP_SpriteAsset))] + public class TMP_SpriteAssetEditor : Editor + { + struct UI_PanelState + { + public static bool spriteAssetInfoPanel = true; + public static bool fallbackSpriteAssetPanel = true; + public static bool spriteCharacterTablePanel; + public static bool spriteGlyphTablePanel; + } + + private static string[] s_UiStateLabel = new string[] { "(Click to collapse) ", "(Click to expand) " }; + + int m_moveToIndex; + int m_selectedElement = -1; + int m_CurrentCharacterPage; + int m_CurrentGlyphPage; + + const string k_UndoRedo = "UndoRedoPerformed"; + + string m_CharacterSearchPattern; + List m_CharacterSearchList; + bool m_IsCharacterSearchDirty; + + string m_GlyphSearchPattern; + List m_GlyphSearchList; + bool m_IsGlyphSearchDirty; + + SerializedProperty m_spriteAtlas_prop; + SerializedProperty m_material_prop; + SerializedProperty m_SpriteCharacterTableProperty; + SerializedProperty m_SpriteGlyphTableProperty; + ReorderableList m_fallbackSpriteAssetList; + + TMP_SpriteAsset m_SpriteAsset; + + bool isAssetDirty; + + float m_xOffset; + float m_yOffset; + float m_xAdvance; + float m_scale; + + public void OnEnable() + { + m_SpriteAsset = target as TMP_SpriteAsset; + + m_spriteAtlas_prop = serializedObject.FindProperty("spriteSheet"); + m_material_prop = serializedObject.FindProperty("material"); + m_SpriteCharacterTableProperty = serializedObject.FindProperty("m_SpriteCharacterTable"); + m_SpriteGlyphTableProperty = serializedObject.FindProperty("m_SpriteGlyphTable"); + + // Fallback TMP Sprite Asset list + m_fallbackSpriteAssetList = new ReorderableList(serializedObject, serializedObject.FindProperty("fallbackSpriteAssets"), true, true, true, true); + + m_fallbackSpriteAssetList.drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) => + { + var element = m_fallbackSpriteAssetList.serializedProperty.GetArrayElementAtIndex(index); + rect.y += 2; + EditorGUI.PropertyField(new Rect(rect.x, rect.y, rect.width, EditorGUIUtility.singleLineHeight), element, GUIContent.none); + }; + + m_fallbackSpriteAssetList.drawHeaderCallback = rect => + { + EditorGUI.LabelField(rect, new GUIContent("Fallback Sprite Asset List", "Select the Sprite Assets that will be searched and used as fallback when a given sprite is missing from this sprite asset.")); + }; + } + + + public override void OnInspectorGUI() + { + + //Debug.Log("OnInspectorGUI Called."); + Event currentEvent = Event.current; + string evt_cmd = currentEvent.commandName; // Get Current Event CommandName to check for Undo Events + + serializedObject.Update(); + + Rect rect; + + // TEXTMESHPRO SPRITE INFO PANEL + GUILayout.Label("Sprite Info", EditorStyles.boldLabel); + EditorGUI.indentLevel = 1; + + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(m_spriteAtlas_prop , new GUIContent("Sprite Atlas")); + if (EditorGUI.EndChangeCheck()) + { + // Assign the new sprite atlas texture to the current material + Texture2D tex = m_spriteAtlas_prop.objectReferenceValue as Texture2D; + if (tex != null) + { + Material mat = m_material_prop.objectReferenceValue as Material; + if (mat != null) + mat.mainTexture = tex; + } + } + + EditorGUILayout.PropertyField(m_material_prop, new GUIContent("Default Material")); + + EditorGUILayout.Space(); + + // FALLBACK SPRITE ASSETS + EditorGUI.indentLevel = 0; + UI_PanelState.fallbackSpriteAssetPanel = EditorGUILayout.Foldout(UI_PanelState.fallbackSpriteAssetPanel, new GUIContent("Fallback Sprite Assets", "Select the Sprite Assets that will be searched and used as fallback when a given sprite is missing from this sprite asset."), true, TMP_UIStyleManager.boldFoldout); + + if (UI_PanelState.fallbackSpriteAssetPanel) + { + m_fallbackSpriteAssetList.DoLayoutList(); + } + + // SPRITE CHARACTER TABLE + #region Display Sprite Character Table + EditorGUI.indentLevel = 0; + rect = EditorGUILayout.GetControlRect(false, 24); + + if (GUI.Button(rect, new GUIContent("Sprite Character Table", "List of sprite characters contained in this sprite asset."), TMP_UIStyleManager.sectionHeader)) + UI_PanelState.spriteCharacterTablePanel = !UI_PanelState.spriteCharacterTablePanel; + + GUI.Label(rect, (UI_PanelState.spriteCharacterTablePanel ? "" : s_UiStateLabel[1]), TMP_UIStyleManager.rightLabel); + + if (UI_PanelState.spriteCharacterTablePanel) + { + int arraySize = m_SpriteCharacterTableProperty.arraySize; + int itemsPerPage = 10; + + // Display Glyph Management Tools + EditorGUILayout.BeginVertical(EditorStyles.helpBox, GUILayout.ExpandWidth(true)); + { + // Search Bar implementation + #region DISPLAY SEARCH BAR + EditorGUILayout.BeginHorizontal(); + { + EditorGUIUtility.labelWidth = 110f; + EditorGUI.BeginChangeCheck(); + string searchPattern = EditorGUILayout.TextField("Sprite Search", m_CharacterSearchPattern, "SearchTextField"); + if (EditorGUI.EndChangeCheck() || m_IsCharacterSearchDirty) + { + if (string.IsNullOrEmpty(searchPattern) == false) + { + //GUIUtility.keyboardControl = 0; + m_CharacterSearchPattern = searchPattern.ToLower(System.Globalization.CultureInfo.InvariantCulture).Trim(); + + // Search Glyph Table for potential matches + SearchCharacterTable(m_CharacterSearchPattern, ref m_CharacterSearchList); + } + else + m_CharacterSearchPattern = null; + + m_IsCharacterSearchDirty = false; + } + + string styleName = string.IsNullOrEmpty(m_CharacterSearchPattern) ? "SearchCancelButtonEmpty" : "SearchCancelButton"; + if (GUILayout.Button(GUIContent.none, styleName)) + { + GUIUtility.keyboardControl = 0; + m_CharacterSearchPattern = string.Empty; + } + } + EditorGUILayout.EndHorizontal(); + #endregion + + // Display Page Navigation + if (!string.IsNullOrEmpty(m_CharacterSearchPattern)) + arraySize = m_CharacterSearchList.Count; + + // Display Page Navigation + DisplayPageNavigation(ref m_CurrentCharacterPage, arraySize, itemsPerPage); + } + EditorGUILayout.EndVertical(); + + if (arraySize > 0) + { + // Display each SpriteInfo entry using the SpriteInfo property drawer. + for (int i = itemsPerPage * m_CurrentCharacterPage; i < arraySize && i < itemsPerPage * (m_CurrentCharacterPage + 1); i++) + { + // Define the start of the selection region of the element. + Rect elementStartRegion = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true)); + + int elementIndex = i; + if (!string.IsNullOrEmpty(m_CharacterSearchPattern)) + elementIndex = m_CharacterSearchList[i]; + + SerializedProperty spriteCharacterProperty = m_SpriteCharacterTableProperty.GetArrayElementAtIndex(elementIndex); + + EditorGUILayout.BeginVertical(EditorStyles.helpBox); + { + EditorGUI.BeginDisabledGroup(i != m_selectedElement); + { + EditorGUILayout.PropertyField(spriteCharacterProperty); + } + EditorGUI.EndDisabledGroup(); + } + EditorGUILayout.EndVertical(); + + // Define the end of the selection region of the element. + Rect elementEndRegion = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true)); + + // Check for Item selection + Rect selectionArea = new Rect(elementStartRegion.x, elementStartRegion.y, elementEndRegion.width, elementEndRegion.y - elementStartRegion.y); + if (DoSelectionCheck(selectionArea)) + { + if (m_selectedElement == i) + { + m_selectedElement = -1; + } + else + { + m_selectedElement = i; + GUIUtility.keyboardControl = 0; + } + } + + // Draw & Handle Section Area + if (m_selectedElement == i) + { + // Draw selection highlight + TMP_EditorUtility.DrawBox(selectionArea, 2f, new Color32(40, 192, 255, 255)); + + // Draw options to MoveUp, MoveDown, Add or Remove Sprites + Rect controlRect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight * 1f); + controlRect.width /= 8; + + // Move sprite up. + bool guiEnabled = GUI.enabled; + if (i == 0) { GUI.enabled = false; } + if (GUI.Button(controlRect, "Up")) + { + SwapCharacterElements(i, i - 1); + } + GUI.enabled = guiEnabled; + + // Move sprite down. + controlRect.x += controlRect.width; + if (i == arraySize - 1) { GUI.enabled = false; } + if (GUI.Button(controlRect, "Down")) + { + SwapCharacterElements(i, i + 1); + } + GUI.enabled = guiEnabled; + + // Move sprite to new index + controlRect.x += controlRect.width * 2; + //if (i == arraySize - 1) { GUI.enabled = false; } + m_moveToIndex = EditorGUI.IntField(controlRect, m_moveToIndex); + controlRect.x -= controlRect.width; + if (GUI.Button(controlRect, "Goto")) + { + MoveCharacterToIndex(i, m_moveToIndex); + } + //controlRect.x += controlRect.width; + GUI.enabled = guiEnabled; + + // Add new Sprite + controlRect.x += controlRect.width * 4; + if (GUI.Button(controlRect, "+")) + { + m_SpriteCharacterTableProperty.arraySize += 1; + + int index = m_SpriteCharacterTableProperty.arraySize - 1; + + SerializedProperty spriteInfo_prop = m_SpriteCharacterTableProperty.GetArrayElementAtIndex(index); + + // Copy properties of the selected element + CopyCharacterSerializedProperty(m_SpriteCharacterTableProperty.GetArrayElementAtIndex(elementIndex), ref spriteInfo_prop); + + //spriteInfo_prop.FindPropertyRelative("m_Index").intValue = index; + serializedObject.ApplyModifiedProperties(); + + m_IsCharacterSearchDirty = true; + } + + // Delete selected Sprite + controlRect.x += controlRect.width; + if (m_selectedElement == -1) GUI.enabled = false; + if (GUI.Button(controlRect, "-")) + { + m_SpriteCharacterTableProperty.DeleteArrayElementAtIndex(elementIndex); + + m_selectedElement = -1; + serializedObject.ApplyModifiedProperties(); + + m_IsCharacterSearchDirty = true; + + return; + } + + + } + } + } + + DisplayPageNavigation(ref m_CurrentCharacterPage, arraySize, itemsPerPage); + + EditorGUIUtility.labelWidth = 40f; + EditorGUIUtility.fieldWidth = 20f; + + GUILayout.Space(5f); + + // GLOBAL TOOLS + #region Global Tools + /* + GUI.enabled = true; + EditorGUILayout.BeginVertical(EditorStyles.helpBox); + rect = EditorGUILayout.GetControlRect(false, 40); + + float width = (rect.width - 75f) / 4; + EditorGUI.LabelField(rect, "Global Offsets & Scale", EditorStyles.boldLabel); + + + rect.x += 70; + bool old_ChangedState = GUI.changed; + + GUI.changed = false; + m_xOffset = EditorGUI.FloatField(new Rect(rect.x + 5f + width * 0, rect.y + 20, width - 5f, 18), new GUIContent("OX:"), m_xOffset); + if (GUI.changed) UpdateGlobalProperty("m_HorizontalBearingX", m_xOffset); + + m_yOffset = EditorGUI.FloatField(new Rect(rect.x + 5f + width * 1, rect.y + 20, width - 5f, 18), new GUIContent("OY:"), m_yOffset); + if (GUI.changed) UpdateGlobalProperty("m_HorizontalBearingY", m_yOffset); + + m_xAdvance = EditorGUI.FloatField(new Rect(rect.x + 5f + width * 2, rect.y + 20, width - 5f, 18), new GUIContent("ADV."), m_xAdvance); + if (GUI.changed) UpdateGlobalProperty("m_HorizontalAdvance", m_xAdvance); + + m_scale = EditorGUI.FloatField(new Rect(rect.x + 5f + width * 3, rect.y + 20, width - 5f, 18), new GUIContent("SF."), m_scale); + if (GUI.changed) UpdateGlobalProperty("m_Scale", m_scale); + + EditorGUILayout.EndVertical(); + + GUI.changed = old_ChangedState; + */ + #endregion + + } + #endregion + + + // SPRITE GLYPH TABLE + #region Display Sprite Glyph Table + EditorGUI.indentLevel = 0; + rect = EditorGUILayout.GetControlRect(false, 24); + + if (GUI.Button(rect, new GUIContent("Sprite Glyph Table", "A list of the SpriteGlyphs contained in this sprite asset."), TMP_UIStyleManager.sectionHeader)) + UI_PanelState.spriteGlyphTablePanel = !UI_PanelState.spriteGlyphTablePanel; + + GUI.Label(rect, (UI_PanelState.spriteGlyphTablePanel ? "" : s_UiStateLabel[1]), TMP_UIStyleManager.rightLabel); + + if (UI_PanelState.spriteGlyphTablePanel) + { + int arraySize = m_SpriteGlyphTableProperty.arraySize; + int itemsPerPage = 10; + + // Display Glyph Management Tools + EditorGUILayout.BeginVertical(EditorStyles.helpBox, GUILayout.ExpandWidth(true)); + { + // Search Bar implementation + #region DISPLAY SEARCH BAR + EditorGUILayout.BeginHorizontal(); + { + EditorGUIUtility.labelWidth = 110f; + EditorGUI.BeginChangeCheck(); + string searchPattern = EditorGUILayout.TextField("Sprite Search", m_GlyphSearchPattern, "SearchTextField"); + if (EditorGUI.EndChangeCheck() || m_IsGlyphSearchDirty) + { + if (string.IsNullOrEmpty(searchPattern) == false) + { + //GUIUtility.keyboardControl = 0; + m_GlyphSearchPattern = searchPattern.ToLower(System.Globalization.CultureInfo.InvariantCulture).Trim(); + + // Search Glyph Table for potential matches + SearchCharacterTable(m_GlyphSearchPattern, ref m_GlyphSearchList); + } + else + m_GlyphSearchPattern = null; + + m_IsGlyphSearchDirty = false; + } + + string styleName = string.IsNullOrEmpty(m_GlyphSearchPattern) ? "SearchCancelButtonEmpty" : "SearchCancelButton"; + if (GUILayout.Button(GUIContent.none, styleName)) + { + GUIUtility.keyboardControl = 0; + m_GlyphSearchPattern = string.Empty; + } + } + EditorGUILayout.EndHorizontal(); + #endregion + + // Display Page Navigation + if (!string.IsNullOrEmpty(m_GlyphSearchPattern)) + arraySize = m_GlyphSearchList.Count; + + // Display Page Navigation + DisplayPageNavigation(ref m_CurrentGlyphPage, arraySize, itemsPerPage); + } + EditorGUILayout.EndVertical(); + + if (arraySize > 0) + { + // Display each SpriteInfo entry using the SpriteInfo property drawer. + for (int i = itemsPerPage * m_CurrentGlyphPage; i < arraySize && i < itemsPerPage * (m_CurrentGlyphPage + 1); i++) + { + // Define the start of the selection region of the element. + Rect elementStartRegion = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true)); + + int elementIndex = i; + if (!string.IsNullOrEmpty(m_GlyphSearchPattern)) + elementIndex = m_GlyphSearchList[i]; + + SerializedProperty spriteGlyphProperty = m_SpriteGlyphTableProperty.GetArrayElementAtIndex(elementIndex); + + EditorGUILayout.BeginVertical(EditorStyles.helpBox); + { + EditorGUI.BeginDisabledGroup(i != m_selectedElement); + { + EditorGUILayout.PropertyField(spriteGlyphProperty); + } + EditorGUI.EndDisabledGroup(); + } + EditorGUILayout.EndVertical(); + + // Define the end of the selection region of the element. + Rect elementEndRegion = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true)); + + // Check for Item selection + Rect selectionArea = new Rect(elementStartRegion.x, elementStartRegion.y, elementEndRegion.width, elementEndRegion.y - elementStartRegion.y); + if (DoSelectionCheck(selectionArea)) + { + if (m_selectedElement == i) + { + m_selectedElement = -1; + } + else + { + m_selectedElement = i; + GUIUtility.keyboardControl = 0; + } + } + + // Draw & Handle Section Area + if (m_selectedElement == i) + { + // Draw selection highlight + TMP_EditorUtility.DrawBox(selectionArea, 2f, new Color32(40, 192, 255, 255)); + + // Draw options to MoveUp, MoveDown, Add or Remove Sprites + Rect controlRect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight * 1f); + controlRect.width /= 8; + + // Move sprite up. + bool guiEnabled = GUI.enabled; + if (i == 0) { GUI.enabled = false; } + if (GUI.Button(controlRect, "Up")) + { + SwapGlyphElements(i, i - 1); + } + GUI.enabled = guiEnabled; + + // Move sprite down. + controlRect.x += controlRect.width; + if (i == arraySize - 1) { GUI.enabled = false; } + if (GUI.Button(controlRect, "Down")) + { + SwapGlyphElements(i, i + 1); + } + GUI.enabled = guiEnabled; + + // Move sprite to new index + controlRect.x += controlRect.width * 2; + //if (i == arraySize - 1) { GUI.enabled = false; } + m_moveToIndex = EditorGUI.IntField(controlRect, m_moveToIndex); + controlRect.x -= controlRect.width; + if (GUI.Button(controlRect, "Goto")) + { + MoveGlyphToIndex(i, m_moveToIndex); + } + //controlRect.x += controlRect.width; + GUI.enabled = guiEnabled; + + // Add new Sprite + controlRect.x += controlRect.width * 4; + if (GUI.Button(controlRect, "+")) + { + m_SpriteGlyphTableProperty.arraySize += 1; + + int index = m_SpriteGlyphTableProperty.arraySize - 1; + + SerializedProperty newSpriteGlyphProperty = m_SpriteGlyphTableProperty.GetArrayElementAtIndex(index); + + // Copy properties of the selected element + CopyGlyphSerializedProperty(m_SpriteGlyphTableProperty.GetArrayElementAtIndex(elementIndex), ref newSpriteGlyphProperty); + + newSpriteGlyphProperty.FindPropertyRelative("m_Index").intValue = index; + + serializedObject.ApplyModifiedProperties(); + + m_IsGlyphSearchDirty = true; + + //m_SpriteAsset.UpdateLookupTables(); + } + + // Delete selected Sprite + controlRect.x += controlRect.width; + if (m_selectedElement == -1) GUI.enabled = false; + if (GUI.Button(controlRect, "-")) + { + SerializedProperty selectedSpriteGlyphProperty = m_SpriteGlyphTableProperty.GetArrayElementAtIndex(elementIndex); + + int selectedGlyphIndex = selectedSpriteGlyphProperty.FindPropertyRelative("m_Index").intValue; + + m_SpriteGlyphTableProperty.DeleteArrayElementAtIndex(elementIndex); + + // Remove all Sprite Characters referencing this glyph. + for (int j = 0; j < m_SpriteCharacterTableProperty.arraySize; j++) + { + int glyphIndex = m_SpriteCharacterTableProperty.GetArrayElementAtIndex(j).FindPropertyRelative("m_GlyphIndex").intValue; + + if (glyphIndex == selectedGlyphIndex) + { + // Remove character + m_SpriteCharacterTableProperty.DeleteArrayElementAtIndex(j); + } + } + + m_selectedElement = -1; + serializedObject.ApplyModifiedProperties(); + + m_IsGlyphSearchDirty = true; + + //m_SpriteAsset.UpdateLookupTables(); + + return; + } + + + } + } + } + + DisplayPageNavigation(ref m_CurrentGlyphPage, arraySize, itemsPerPage); + + EditorGUIUtility.labelWidth = 40f; + EditorGUIUtility.fieldWidth = 20f; + + GUILayout.Space(5f); + + // GLOBAL TOOLS + #region Global Tools + GUI.enabled = true; + EditorGUILayout.BeginVertical(EditorStyles.helpBox); + rect = EditorGUILayout.GetControlRect(false, 40); + + float width = (rect.width - 75f) / 4; + EditorGUI.LabelField(rect, "Global Offsets & Scale", EditorStyles.boldLabel); + + + rect.x += 70; + bool old_ChangedState = GUI.changed; + + GUI.changed = false; + m_xOffset = EditorGUI.FloatField(new Rect(rect.x + 5f + width * 0, rect.y + 20, width - 5f, 18), new GUIContent("OX:"), m_xOffset); + if (GUI.changed) UpdateGlobalProperty("m_HorizontalBearingX", m_xOffset); + + m_yOffset = EditorGUI.FloatField(new Rect(rect.x + 5f + width * 1, rect.y + 20, width - 5f, 18), new GUIContent("OY:"), m_yOffset); + if (GUI.changed) UpdateGlobalProperty("m_HorizontalBearingY", m_yOffset); + + m_xAdvance = EditorGUI.FloatField(new Rect(rect.x + 5f + width * 2, rect.y + 20, width - 5f, 18), new GUIContent("ADV."), m_xAdvance); + if (GUI.changed) UpdateGlobalProperty("m_HorizontalAdvance", m_xAdvance); + + m_scale = EditorGUI.FloatField(new Rect(rect.x + 5f + width * 3, rect.y + 20, width - 5f, 18), new GUIContent("SF."), m_scale); + if (GUI.changed) UpdateGlobalProperty("m_Scale", m_scale); + + EditorGUILayout.EndVertical(); + #endregion + + GUI.changed = old_ChangedState; + + } + #endregion + + + if (serializedObject.ApplyModifiedProperties() || evt_cmd == k_UndoRedo || isAssetDirty) + { + if (m_SpriteAsset.m_IsSpriteAssetLookupTablesDirty || evt_cmd == k_UndoRedo) + m_SpriteAsset.UpdateLookupTables(); + + TMPro_EventManager.ON_SPRITE_ASSET_PROPERTY_CHANGED(true, m_SpriteAsset); + + isAssetDirty = false; + EditorUtility.SetDirty(target); + } + + // Clear selection if mouse event was not consumed. + GUI.enabled = true; + if (currentEvent.type == EventType.MouseDown && currentEvent.button == 0) + m_selectedElement = -1; + + } + + + /// + /// + /// + /// + /// + void DisplayPageNavigation(ref int currentPage, int arraySize, int itemsPerPage) + { + Rect pagePos = EditorGUILayout.GetControlRect(false, 20); + pagePos.width /= 3; + + int shiftMultiplier = Event.current.shift ? 10 : 1; // Page + Shift goes 10 page forward + + // Previous Page + GUI.enabled = currentPage > 0; + + if (GUI.Button(pagePos, "Previous Page")) + { + currentPage -= 1 * shiftMultiplier; + //m_isNewPage = true; + } + + // Page Counter + GUI.enabled = true; + pagePos.x += pagePos.width; + int totalPages = (int)(arraySize / (float)itemsPerPage + 0.999f); + GUI.Label(pagePos, "Page " + (currentPage + 1) + " / " + totalPages, TMP_UIStyleManager.centeredLabel); + + // Next Page + pagePos.x += pagePos.width; + GUI.enabled = itemsPerPage * (currentPage + 1) < arraySize; + + if (GUI.Button(pagePos, "Next Page")) + { + currentPage += 1 * shiftMultiplier; + //m_isNewPage = true; + } + + // Clamp page range + currentPage = Mathf.Clamp(currentPage, 0, arraySize / itemsPerPage); + + GUI.enabled = true; + } + + + /// + /// Method to update the properties of all sprites + /// + /// + /// + void UpdateGlobalProperty(string property, float value) + { + int arraySize = m_SpriteGlyphTableProperty.arraySize; + + for (int i = 0; i < arraySize; i++) + { + // Get a reference to the sprite glyph. + SerializedProperty spriteGlyphProperty = m_SpriteGlyphTableProperty.GetArrayElementAtIndex(i); + + if (property == "m_Scale") + { + spriteGlyphProperty.FindPropertyRelative(property).floatValue = value; + } + else + { + SerializedProperty glyphMetricsProperty = spriteGlyphProperty.FindPropertyRelative("m_Metrics"); + glyphMetricsProperty.FindPropertyRelative(property).floatValue = value; + } + } + + GUI.changed = false; + } + + // Check if any of the Style elements were clicked on. + private bool DoSelectionCheck(Rect selectionArea) + { + Event currentEvent = Event.current; + + switch (currentEvent.type) + { + case EventType.MouseDown: + if (selectionArea.Contains(currentEvent.mousePosition) && currentEvent.button == 0) + { + currentEvent.Use(); + return true; + } + break; + } + + return false; + } + + + /// + /// Swap the sprite item at the currently selected array index to another index. + /// + /// Selected index. + /// New index. + void SwapCharacterElements(int selectedIndex, int newIndex) + { + m_SpriteCharacterTableProperty.MoveArrayElement(selectedIndex, newIndex); + m_selectedElement = newIndex; + m_IsCharacterSearchDirty = true; + m_SpriteAsset.m_IsSpriteAssetLookupTablesDirty = true; + } + + /// + /// Move Sprite Element at selected index to another index and reorder sprite list. + /// + /// + /// + void MoveCharacterToIndex(int selectedIndex, int newIndex) + { + int arraySize = m_SpriteCharacterTableProperty.arraySize; + + if (newIndex >= arraySize) + newIndex = arraySize - 1; + + m_SpriteCharacterTableProperty.MoveArrayElement(selectedIndex, newIndex); + + m_selectedElement = newIndex; + m_IsCharacterSearchDirty = true; + m_SpriteAsset.m_IsSpriteAssetLookupTablesDirty = true; + + // TODO: Need to handle switching pages if the character or glyph is moved to a different page. + } + + /// + /// + /// + /// + /// + void SwapGlyphElements(int selectedIndex, int newIndex) + { + m_SpriteGlyphTableProperty.MoveArrayElement(selectedIndex, newIndex); + m_selectedElement = newIndex; + m_IsGlyphSearchDirty = true; + m_SpriteAsset.m_IsSpriteAssetLookupTablesDirty = true; + } + + /// + /// Move Sprite Element at selected index to another index and reorder sprite list. + /// + /// + /// + void MoveGlyphToIndex(int selectedIndex, int newIndex) + { + int arraySize = m_SpriteGlyphTableProperty.arraySize; + + if (newIndex >= arraySize) + newIndex = arraySize - 1; + + m_SpriteGlyphTableProperty.MoveArrayElement(selectedIndex, newIndex); + + m_selectedElement = newIndex; + m_IsGlyphSearchDirty = true; + m_SpriteAsset.m_IsSpriteAssetLookupTablesDirty = true; + + // TODO: Need to handle switching pages if the character or glyph is moved to a different page. + } + + + /// + /// + /// + /// + /// + void CopyCharacterSerializedProperty(SerializedProperty source, ref SerializedProperty target) + { + target.FindPropertyRelative("m_Name").stringValue = source.FindPropertyRelative("m_Name").stringValue; + target.FindPropertyRelative("m_HashCode").intValue = source.FindPropertyRelative("m_HashCode").intValue; + target.FindPropertyRelative("m_Unicode").intValue = source.FindPropertyRelative("m_Unicode").intValue; + target.FindPropertyRelative("m_GlyphIndex").intValue = source.FindPropertyRelative("m_GlyphIndex").intValue; + target.FindPropertyRelative("m_Scale").floatValue = source.FindPropertyRelative("m_Scale").floatValue; + } + + void CopyGlyphSerializedProperty(SerializedProperty srcGlyph, ref SerializedProperty dstGlyph) + { + // TODO : Should make a generic function which copies each of the properties. + + // Index + dstGlyph.FindPropertyRelative("m_Index").intValue = srcGlyph.FindPropertyRelative("m_Index").intValue; + + // GlyphMetrics + SerializedProperty srcGlyphMetrics = srcGlyph.FindPropertyRelative("m_Metrics"); + SerializedProperty dstGlyphMetrics = dstGlyph.FindPropertyRelative("m_Metrics"); + + dstGlyphMetrics.FindPropertyRelative("m_Width").floatValue = srcGlyphMetrics.FindPropertyRelative("m_Width").floatValue; + dstGlyphMetrics.FindPropertyRelative("m_Height").floatValue = srcGlyphMetrics.FindPropertyRelative("m_Height").floatValue; + dstGlyphMetrics.FindPropertyRelative("m_HorizontalBearingX").floatValue = srcGlyphMetrics.FindPropertyRelative("m_HorizontalBearingX").floatValue; + dstGlyphMetrics.FindPropertyRelative("m_HorizontalBearingY").floatValue = srcGlyphMetrics.FindPropertyRelative("m_HorizontalBearingY").floatValue; + dstGlyphMetrics.FindPropertyRelative("m_HorizontalAdvance").floatValue = srcGlyphMetrics.FindPropertyRelative("m_HorizontalAdvance").floatValue; + + // GlyphRect + SerializedProperty srcGlyphRect = srcGlyph.FindPropertyRelative("m_GlyphRect"); + SerializedProperty dstGlyphRect = dstGlyph.FindPropertyRelative("m_GlyphRect"); + + dstGlyphRect.FindPropertyRelative("m_X").intValue = srcGlyphRect.FindPropertyRelative("m_X").intValue; + dstGlyphRect.FindPropertyRelative("m_Y").intValue = srcGlyphRect.FindPropertyRelative("m_Y").intValue; + dstGlyphRect.FindPropertyRelative("m_Width").intValue = srcGlyphRect.FindPropertyRelative("m_Width").intValue; + dstGlyphRect.FindPropertyRelative("m_Height").intValue = srcGlyphRect.FindPropertyRelative("m_Height").intValue; + + dstGlyph.FindPropertyRelative("m_Scale").floatValue = srcGlyph.FindPropertyRelative("m_Scale").floatValue; + dstGlyph.FindPropertyRelative("m_AtlasIndex").intValue = srcGlyph.FindPropertyRelative("m_AtlasIndex").intValue; + } + + + /// + /// + /// + /// + /// + void SearchCharacterTable(string searchPattern, ref List searchResults) + { + if (searchResults == null) searchResults = new List(); + searchResults.Clear(); + + int arraySize = m_SpriteCharacterTableProperty.arraySize; + + for (int i = 0; i < arraySize; i++) + { + SerializedProperty sourceSprite = m_SpriteCharacterTableProperty.GetArrayElementAtIndex(i); + + // Check for potential match against array index + if (i.ToString().Contains(searchPattern)) + { + searchResults.Add(i); + continue; + } + + // Check for potential match against decimal id + int id = sourceSprite.FindPropertyRelative("m_GlyphIndex").intValue; + if (id.ToString().Contains(searchPattern)) + { + searchResults.Add(i); + continue; + } + + // Check for potential match against name + string name = sourceSprite.FindPropertyRelative("m_Name").stringValue.ToLower(System.Globalization.CultureInfo.InvariantCulture).Trim(); + if (name.Contains(searchPattern)) + { + searchResults.Add(i); + continue; + } + } + } + + void SearchGlyphTable(string searchPattern, ref List searchResults) + { + if (searchResults == null) searchResults = new List(); + searchResults.Clear(); + + int arraySize = m_SpriteGlyphTableProperty.arraySize; + + for (int i = 0; i < arraySize; i++) + { + SerializedProperty sourceSprite = m_SpriteGlyphTableProperty.GetArrayElementAtIndex(i); + + // Check for potential match against array index + if (i.ToString().Contains(searchPattern)) + { + searchResults.Add(i); + continue; + } + + // Check for potential match against decimal id + int id = sourceSprite.FindPropertyRelative("m_GlyphIndex").intValue; + if (id.ToString().Contains(searchPattern)) + { + searchResults.Add(i); + continue; + } + + // Check for potential match against name + string name = sourceSprite.FindPropertyRelative("m_Name").stringValue.ToLower(System.Globalization.CultureInfo.InvariantCulture).Trim(); + if (name.Contains(searchPattern)) + { + searchResults.Add(i); + continue; + } + } + } + + } +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_SpriteAssetImporter.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_SpriteAssetImporter.cs new file mode 100644 index 00000000..dc4f0932 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_SpriteAssetImporter.cs @@ -0,0 +1,232 @@ +using UnityEngine; +using UnityEditor; +using System.IO; +using System.Collections.Generic; +using TMPro.EditorUtilities; +using TMPro.SpriteAssetUtilities; + +namespace TMPro +{ + public class TMP_SpriteAssetImporter : EditorWindow + { + // Create Sprite Asset Editor Window + [MenuItem("Window/TextMeshPro/Sprite Importer", false, 2026)] + public static void ShowFontAtlasCreatorWindow() + { + var window = GetWindow(); + window.titleContent = new GUIContent("Sprite Importer"); + window.Focus(); + } + + Texture2D m_SpriteAtlas; + SpriteAssetImportFormats m_SpriteDataFormat = SpriteAssetImportFormats.TexturePacker; + TextAsset m_JsonFile; + + string m_CreationFeedback; + + TMP_SpriteAsset m_SpriteAsset; + List m_SpriteInfoList = new List(); + + + void OnEnable() + { + // Set Editor Window Size + SetEditorWindowSize(); + } + + public void OnGUI() + { + DrawEditorPanel(); + } + + + void DrawEditorPanel() + { + // label + GUILayout.Label("Import Settings", EditorStyles.boldLabel); + + EditorGUI.BeginChangeCheck(); + + // Sprite Texture Selection + m_JsonFile = EditorGUILayout.ObjectField("Sprite Data Source", m_JsonFile, typeof(TextAsset), false) as TextAsset; + + m_SpriteDataFormat = (SpriteAssetImportFormats)EditorGUILayout.EnumPopup("Import Format", m_SpriteDataFormat); + + // Sprite Texture Selection + m_SpriteAtlas = EditorGUILayout.ObjectField("Sprite Texture Atlas", m_SpriteAtlas, typeof(Texture2D), false) as Texture2D; + + if (EditorGUI.EndChangeCheck()) + { + m_CreationFeedback = string.Empty; + } + + GUILayout.Space(10); + + GUI.enabled = m_JsonFile != null && m_SpriteAtlas != null && m_SpriteDataFormat == SpriteAssetImportFormats.TexturePacker; + + // Create Sprite Asset + if (GUILayout.Button("Create Sprite Asset")) + { + m_CreationFeedback = string.Empty; + + // Read json data file + if (m_JsonFile != null && m_SpriteDataFormat == SpriteAssetImportFormats.TexturePacker) + { + TexturePacker.SpriteDataObject sprites = JsonUtility.FromJson(m_JsonFile.text); + + if (sprites != null && sprites.frames != null && sprites.frames.Count > 0) + { + int spriteCount = sprites.frames.Count; + + // Update import results + m_CreationFeedback = "Import Results\n--------------------\n"; + m_CreationFeedback += "" + spriteCount + " Sprites were imported from file."; + + // Create sprite info list + m_SpriteInfoList = CreateSpriteInfoList(sprites); + } + } + + } + + GUI.enabled = true; + + // Creation Feedback + GUILayout.Space(5); + GUILayout.BeginVertical(EditorStyles.helpBox, GUILayout.Height(60)); + { + EditorGUILayout.LabelField(m_CreationFeedback, TMP_UIStyleManager.label); + } + GUILayout.EndVertical(); + + GUILayout.Space(5); + GUI.enabled = m_JsonFile != null && m_SpriteAtlas && m_SpriteInfoList != null && m_SpriteInfoList.Count > 0; // Enable Save Button if font_Atlas is not Null. + if (GUILayout.Button("Save Sprite Asset") && m_JsonFile != null) + { + string filePath = EditorUtility.SaveFilePanel("Save Sprite Asset File", new FileInfo(AssetDatabase.GetAssetPath(m_JsonFile)).DirectoryName, m_JsonFile.name, "asset"); + + if (filePath.Length == 0) + return; + + SaveSpriteAsset(filePath); + } + GUI.enabled = true; + } + + + /// + /// + /// + List CreateSpriteInfoList(TexturePacker.SpriteDataObject spriteDataObject) + { + List importedSprites = spriteDataObject.frames; + + List spriteInfoList = new List(); + + for (int i = 0; i < importedSprites.Count; i++) + { + TMP_Sprite sprite = new TMP_Sprite(); + + sprite.id = i; + sprite.name = Path.GetFileNameWithoutExtension(importedSprites[i].filename) ?? ""; + sprite.hashCode = TMP_TextUtilities.GetSimpleHashCode(sprite.name); + + // Attempt to extract Unicode value from name + int unicode; + int indexOfSeperator = sprite.name.IndexOf('-'); + if (indexOfSeperator != -1) + unicode = TMP_TextUtilities.StringHexToInt(sprite.name.Substring(indexOfSeperator + 1)); + else + unicode = TMP_TextUtilities.StringHexToInt(sprite.name); + + sprite.unicode = unicode; + + sprite.x = importedSprites[i].frame.x; + sprite.y = m_SpriteAtlas.height - (importedSprites[i].frame.y + importedSprites[i].frame.h); + sprite.width = importedSprites[i].frame.w; + sprite.height = importedSprites[i].frame.h; + + //Calculate sprite pivot position + sprite.pivot = importedSprites[i].pivot; + + // Properties the can be modified + sprite.xAdvance = sprite.width; + sprite.scale = 1.0f; + sprite.xOffset = 0 - (sprite.width * sprite.pivot.x); + sprite.yOffset = sprite.height - (sprite.height * sprite.pivot.y); + + spriteInfoList.Add(sprite); + } + + return spriteInfoList; + } + + + /// + /// + /// + /// + void SaveSpriteAsset(string filePath) + { + filePath = filePath.Substring(0, filePath.Length - 6); // Trim file extension from filePath. + + string dataPath = Application.dataPath; + + if (filePath.IndexOf(dataPath, System.StringComparison.InvariantCultureIgnoreCase) == -1) + { + Debug.LogError("You're saving the font asset in a directory outside of this project folder. This is not supported. Please select a directory under \"" + dataPath + "\""); + return; + } + + string relativeAssetPath = filePath.Substring(dataPath.Length - 6); + string dirName = Path.GetDirectoryName(relativeAssetPath); + string fileName = Path.GetFileNameWithoutExtension(relativeAssetPath); + string pathNoExt = dirName + "/" + fileName; + + + // Create new Sprite Asset using this texture + m_SpriteAsset = CreateInstance(); + AssetDatabase.CreateAsset(m_SpriteAsset, pathNoExt + ".asset"); + + // Compute the hash code for the sprite asset. + m_SpriteAsset.hashCode = TMP_TextUtilities.GetSimpleHashCode(m_SpriteAsset.name); + + // Assign new Sprite Sheet texture to the Sprite Asset. + m_SpriteAsset.spriteSheet = m_SpriteAtlas; + m_SpriteAsset.spriteInfoList = m_SpriteInfoList; + + // Add new default material for sprite asset. + AddDefaultMaterial(m_SpriteAsset); + } + + + /// + /// Create and add new default material to sprite asset. + /// + /// + static void AddDefaultMaterial(TMP_SpriteAsset spriteAsset) + { + Shader shader = Shader.Find("TextMeshPro/Sprite"); + Material material = new Material(shader); + material.SetTexture(ShaderUtilities.ID_MainTex, spriteAsset.spriteSheet); + + spriteAsset.material = material; + material.hideFlags = HideFlags.HideInHierarchy; + AssetDatabase.AddObjectToAsset(material, spriteAsset); + } + + + /// + /// Limits the minimum size of the editor window. + /// + void SetEditorWindowSize() + { + EditorWindow editorWindow = this; + + Vector2 currentWindowSize = editorWindow.minSize; + + editorWindow.minSize = new Vector2(Mathf.Max(230, currentWindowSize.x), Mathf.Max(300, currentWindowSize.y)); + } + + } +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_SpriteAssetMenu.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_SpriteAssetMenu.cs new file mode 100644 index 00000000..5155e1a1 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_SpriteAssetMenu.cs @@ -0,0 +1,329 @@ +using UnityEngine; +using UnityEngine.TextCore; +using UnityEditor; +using System.Linq; +using System.IO; +using System.Collections; +using System.Collections.Generic; + + +namespace TMPro.EditorUtilities +{ + + public static class TMP_SpriteAssetMenu + { + // Add a Context Menu to the Sprite Asset Editor Panel to Create and Add a Default Material. + [MenuItem("CONTEXT/TMP_SpriteAsset/Add Default Material", false, 2200)] + static void CopyTexture(MenuCommand command) + { + TMP_SpriteAsset spriteAsset = (TMP_SpriteAsset)command.context; + + // Make sure the sprite asset already contains a default material + if (spriteAsset != null && spriteAsset.material == null) + { + // Add new default material for sprite asset. + AddDefaultMaterial(spriteAsset); + } + } + + // Add a Context Menu to the Sprite Asset Editor Panel to update existing sprite assets. + [MenuItem("CONTEXT/TMP_SpriteAsset/Update Sprite Asset", false, 2100)] + static void UpdateSpriteAsset(MenuCommand command) + { + TMP_SpriteAsset spriteAsset = (TMP_SpriteAsset)command.context; + + if (spriteAsset == null) + return; + + // Get a list of all the sprites contained in the texture referenced by the sprite asset. + // This only works if the texture is set to sprite mode. + string filePath = AssetDatabase.GetAssetPath(spriteAsset.spriteSheet); + + if (string.IsNullOrEmpty(filePath)) + return; + + // Get all the Sprites sorted Left to Right / Top to Bottom + Sprite[] sprites = AssetDatabase.LoadAllAssetsAtPath(filePath).Select(x => x as Sprite).Where(x => x != null).OrderByDescending(x => x.rect.y).ThenBy(x => x.rect.x).ToArray(); + + List spriteGlyphTable = spriteAsset.spriteGlyphTable; + + // Finding available glyph indexes to insert new glyphs into. + var tempGlyphTable = spriteGlyphTable.OrderBy(glyph => glyph.index).ToList(); + List availableGlyphIndexes = new List(); + + int elementIndex = 0; + for (uint i = 0; i < tempGlyphTable[tempGlyphTable.Count - 1].index; i++) + { + uint currentElementIndex = tempGlyphTable[elementIndex].index; + + if (i == currentElementIndex) + elementIndex += 1; + else + availableGlyphIndexes.Add(i); + } + + // Iterate over each of the sprites in the texture to try to match them to existing sprites in the sprite asset. + for (int i = 0; i < sprites.Length; i++) + { + int id = sprites[i].GetInstanceID(); + + int glyphIndex = spriteGlyphTable.FindIndex(item => item.sprite.GetInstanceID() == id); + + if (glyphIndex == -1) + { + // Add new Sprite Glyph to the table + Sprite sprite = sprites[i]; + + TMP_SpriteGlyph spriteGlyph = new TMP_SpriteGlyph(); + + // Get available glyph index + if (availableGlyphIndexes.Count > 0) + { + spriteGlyph.index = availableGlyphIndexes[0]; + availableGlyphIndexes.RemoveAt(0); + } + else + spriteGlyph.index = (uint)spriteGlyphTable.Count; + + spriteGlyph.metrics = new GlyphMetrics(sprite.rect.width, sprite.rect.height, -sprite.pivot.x, sprite.rect.height - sprite.pivot.y, sprite.rect.width); + spriteGlyph.glyphRect = new GlyphRect(sprite.rect); + spriteGlyph.scale = 1.0f; + spriteGlyph.sprite = sprite; + + spriteGlyphTable.Add(spriteGlyph); + + TMP_SpriteCharacter spriteCharacter = new TMP_SpriteCharacter(0, spriteGlyph); + spriteCharacter.name = sprite.name; + spriteCharacter.scale = 1.0f; + + spriteAsset.spriteCharacterTable.Add(spriteCharacter); + } + else + { + // Look for changes in existing Sprite Glyph + Sprite sprite = sprites[i]; + + TMP_SpriteGlyph spriteGlyph = spriteGlyphTable[glyphIndex]; + + // We only update changes to the sprite position / glyph rect. + if (spriteGlyph.glyphRect.x != sprite.rect.x || spriteGlyph.glyphRect.y != sprite.rect.y || spriteGlyph.glyphRect.width != sprite.rect.width || spriteGlyph.glyphRect.height != sprite.rect.height) + spriteGlyph.glyphRect = new GlyphRect(sprite.rect); + } + } + + // Sort glyph table by glyph index + spriteAsset.SortGlyphTable(); + spriteAsset.UpdateLookupTables(); + TMPro_EventManager.ON_SPRITE_ASSET_PROPERTY_CHANGED(true, spriteAsset); + } + + + [MenuItem("Assets/Create/TextMeshPro/Sprite Asset", false, 110)] + public static void CreateSpriteAsset() + { + Object target = Selection.activeObject; + + // Make sure the selection is a texture. + if (target == null || target.GetType() != typeof(Texture2D)) + { + Debug.LogWarning("A texture which contains sprites must first be selected in order to create a TextMesh Pro Sprite Asset."); + return; + } + + Texture2D sourceTex = target as Texture2D; + + // Get the path to the selected texture. + string filePathWithName = AssetDatabase.GetAssetPath(sourceTex); + string fileNameWithExtension = Path.GetFileName(filePathWithName); + string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filePathWithName); + string filePath = filePathWithName.Replace(fileNameWithExtension, ""); + + // Check if Sprite Asset already exists + TMP_SpriteAsset spriteAsset = AssetDatabase.LoadAssetAtPath(filePath + fileNameWithoutExtension + ".asset", typeof(TMP_SpriteAsset)) as TMP_SpriteAsset; + bool isNewAsset = spriteAsset == null ? true : false; + + if (isNewAsset) + { + // Create new Sprite Asset using this texture + spriteAsset = ScriptableObject.CreateInstance(); + AssetDatabase.CreateAsset(spriteAsset, filePath + fileNameWithoutExtension + ".asset"); + + spriteAsset.version = "1.1.0"; + + // Compute the hash code for the sprite asset. + spriteAsset.hashCode = TMP_TextUtilities.GetSimpleHashCode(spriteAsset.name); + + // Assign new Sprite Sheet texture to the Sprite Asset. + spriteAsset.spriteSheet = sourceTex; + + List spriteGlyphTable = new List(); + List spriteCharacterTable = new List(); + + PopulateSpriteTables(sourceTex, ref spriteCharacterTable, ref spriteGlyphTable); + + spriteAsset.spriteCharacterTable = spriteCharacterTable; + spriteAsset.spriteGlyphTable = spriteGlyphTable; + + // Add new default material for sprite asset. + AddDefaultMaterial(spriteAsset); + } + //else + //{ + // spriteAsset.spriteInfoList = UpdateSpriteInfo(spriteAsset); + + // // Make sure the sprite asset already contains a default material + // if (spriteAsset.material == null) + // { + // // Add new default material for sprite asset. + // AddDefaultMaterial(spriteAsset); + // } + + //} + + // Update Lookup tables. + spriteAsset.UpdateLookupTables(); + + // Get the Sprites contained in the Sprite Sheet + EditorUtility.SetDirty(spriteAsset); + + //spriteAsset.sprites = sprites; + + // Set source texture back to Not Readable. + //texImporter.isReadable = false; + + + AssetDatabase.SaveAssets(); + + AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(spriteAsset)); // Re-import font asset to get the new updated version. + + //AssetDatabase.Refresh(); + } + + + private static void PopulateSpriteTables(Texture source, ref List spriteCharacterTable, ref List spriteGlyphTable) + { + //Debug.Log("Creating new Sprite Asset."); + + string filePath = AssetDatabase.GetAssetPath(source); + + // Get all the Sprites sorted by Index + Sprite[] sprites = AssetDatabase.LoadAllAssetsAtPath(filePath).Select(x => x as Sprite).Where(x => x != null).OrderByDescending(x => x.rect.y).ThenBy(x => x.rect.x).ToArray(); + + for (int i = 0; i < sprites.Length; i++) + { + Sprite sprite = sprites[i]; + + TMP_SpriteGlyph spriteGlyph = new TMP_SpriteGlyph(); + spriteGlyph.index = (uint)i; + spriteGlyph.metrics = new GlyphMetrics(sprite.rect.width, sprite.rect.height, -sprite.pivot.x, sprite.rect.height - sprite.pivot.y, sprite.rect.width); + spriteGlyph.glyphRect = new GlyphRect(sprite.rect); + spriteGlyph.scale = 1.0f; + spriteGlyph.sprite = sprite; + + spriteGlyphTable.Add(spriteGlyph); + + TMP_SpriteCharacter spriteCharacter = new TMP_SpriteCharacter(0, spriteGlyph); + spriteCharacter.name = sprite.name; + spriteCharacter.scale = 1.0f; + + spriteCharacterTable.Add(spriteCharacter); + } + } + + + /// + /// Create and add new default material to sprite asset. + /// + /// + private static void AddDefaultMaterial(TMP_SpriteAsset spriteAsset) + { + Shader shader = Shader.Find("TextMeshPro/Sprite"); + Material material = new Material(shader); + material.SetTexture(ShaderUtilities.ID_MainTex, spriteAsset.spriteSheet); + + spriteAsset.material = material; + material.hideFlags = HideFlags.HideInHierarchy; + AssetDatabase.AddObjectToAsset(material, spriteAsset); + } + + + // Update existing SpriteInfo + private static List UpdateSpriteInfo(TMP_SpriteAsset spriteAsset) + { + //Debug.Log("Updating Sprite Asset."); + + string filePath = AssetDatabase.GetAssetPath(spriteAsset.spriteSheet); + + // Get all the Sprites sorted Left to Right / Top to Bottom + Sprite[] sprites = AssetDatabase.LoadAllAssetsAtPath(filePath).Select(x => x as Sprite).Where(x => x != null).OrderByDescending(x => x.rect.y).ThenBy(x => x.rect.x).ToArray(); + + for (int i = 0; i < sprites.Length; i++) + { + Sprite sprite = sprites[i]; + + // Check if the sprite is already contained in the SpriteInfoList + int index = -1; + if (spriteAsset.spriteInfoList.Count > i && spriteAsset.spriteInfoList[i].sprite != null) + index = spriteAsset.spriteInfoList.FindIndex(item => item.sprite.GetInstanceID() == sprite.GetInstanceID()); + + // Use existing SpriteInfo if it already exists + TMP_Sprite spriteInfo = index == -1 ? new TMP_Sprite() : spriteAsset.spriteInfoList[index]; + + Rect spriteRect = sprite.rect; + spriteInfo.x = spriteRect.x; + spriteInfo.y = spriteRect.y; + spriteInfo.width = spriteRect.width; + spriteInfo.height = spriteRect.height; + + // Get Sprite Pivot + Vector2 pivot = new Vector2(0 - (sprite.bounds.min.x) / (sprite.bounds.extents.x * 2), 0 - (sprite.bounds.min.y) / (sprite.bounds.extents.y * 2)); + + // The position of the pivot influences the Offset position. + spriteInfo.pivot = new Vector2(0 - pivot.x * spriteRect.width, spriteRect.height - pivot.y * spriteRect.height); + + if (index == -1) + { + // Find the next available index for this Sprite + int[] ids = spriteAsset.spriteInfoList.Select(item => item.id).ToArray(); + + int id = 0; + for (int j = 0; j < ids.Length; j++ ) + { + if (ids[0] != 0) break; + + if (j > 0 && (ids[j] - ids[j - 1]) > 1) + { + id = ids[j - 1] + 1; + break; + } + + id = j + 1; + } + + spriteInfo.sprite = sprite; + spriteInfo.name = sprite.name; + spriteInfo.hashCode = TMP_TextUtilities.GetSimpleHashCode(spriteInfo.name); + spriteInfo.id = id; + spriteInfo.xAdvance = spriteRect.width; + spriteInfo.scale = 1.0f; + + spriteInfo.xOffset = spriteInfo.pivot.x; + spriteInfo.yOffset = spriteInfo.pivot.y; + + spriteAsset.spriteInfoList.Add(spriteInfo); + + // Sort the Sprites by ID + spriteAsset.spriteInfoList = spriteAsset.spriteInfoList.OrderBy(s => s.id).ToList(); + } + else + { + spriteAsset.spriteInfoList[index] = spriteInfo; + } + } + + return spriteAsset.spriteInfoList; + } + + + } +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_SpriteCharacterPropertyDrawer.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_SpriteCharacterPropertyDrawer.cs new file mode 100644 index 00000000..abe49a68 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_SpriteCharacterPropertyDrawer.cs @@ -0,0 +1,225 @@ +using UnityEngine; +using UnityEngine.TextCore; +using UnityEditor; +using System.Collections; + + +namespace TMPro.EditorUtilities +{ + + [CustomPropertyDrawer(typeof(TMP_SpriteCharacter))] + public class TMP_SpriteCharacterPropertyDrawer : PropertyDrawer + { + int m_GlyphSelectedForEditing = -1; + + public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) + { + SerializedProperty prop_SpriteName = property.FindPropertyRelative("m_Name"); + SerializedProperty prop_SpriteNameHashCode = property.FindPropertyRelative("m_HashCode"); + SerializedProperty prop_SpriteUnicode = property.FindPropertyRelative("m_Unicode"); + SerializedProperty prop_SpriteGlyphIndex = property.FindPropertyRelative("m_GlyphIndex"); + SerializedProperty prop_SpriteScale = property.FindPropertyRelative("m_Scale"); + + + GUIStyle style = new GUIStyle(EditorStyles.label); + style.richText = true; + + EditorGUIUtility.labelWidth = 40f; + EditorGUIUtility.fieldWidth = 50; + + Rect rect = new Rect(position.x + 60, position.y, position.width, 49); + + // Display non-editable fields + if (GUI.enabled == false) + { + // Sprite Character Index + int.TryParse(property.displayName.Split(' ')[1], out int spriteCharacterIndex); + EditorGUI.LabelField(new Rect(rect.x, rect.y, 75f, 18), new GUIContent("Index: " + spriteCharacterIndex + ""), style); + + EditorGUI.LabelField(new Rect(rect.x + 75f, rect.y, 120f, 18), new GUIContent("Unicode: 0x" + prop_SpriteUnicode.intValue.ToString("X") + ""), style); + EditorGUI.LabelField(new Rect(rect.x + 195f, rect.y, rect.width - 255, 18), new GUIContent("Name: " + prop_SpriteName.stringValue + ""), style); + + EditorGUI.LabelField(new Rect(rect.x, rect.y + 18, 120, 18), new GUIContent("Glyph ID: " + prop_SpriteGlyphIndex.intValue + ""), style); + + // Draw Sprite Glyph (if exists) + DrawSpriteGlyph(position, property); + + EditorGUI.LabelField(new Rect(rect.x, rect.y + 36, 80, 18), new GUIContent("Scale: " + prop_SpriteScale.floatValue + ""), style); + } + else // Display editable fields + { + // Get a reference to the underlying Sprite Asset + TMP_SpriteAsset spriteAsset = property.serializedObject.targetObject as TMP_SpriteAsset; + + // Sprite Character Index + int.TryParse(property.displayName.Split(' ')[1], out int spriteCharacterIndex); + + EditorGUI.LabelField(new Rect(rect.x, rect.y, 75f, 18), new GUIContent("Index: " + spriteCharacterIndex + ""), style); + + EditorGUIUtility.labelWidth = 55f; + GUI.SetNextControlName("Unicode Input"); + EditorGUI.BeginChangeCheck(); + string unicode = EditorGUI.DelayedTextField(new Rect(rect.x + 75f, rect.y, 120, 18), "Unicode:", prop_SpriteUnicode.intValue.ToString("X")); + + if (GUI.GetNameOfFocusedControl() == "Unicode Input") + { + //Filter out unwanted characters. + char chr = Event.current.character; + if ((chr < '0' || chr > '9') && (chr < 'a' || chr > 'f') && (chr < 'A' || chr > 'F')) + { + Event.current.character = '\0'; + } + } + + if (EditorGUI.EndChangeCheck()) + { + // Update Unicode value + prop_SpriteUnicode.intValue = TMP_TextUtilities.StringHexToInt(unicode); + spriteAsset.m_IsSpriteAssetLookupTablesDirty = true; + } + + EditorGUIUtility.labelWidth = 41f; + EditorGUI.BeginChangeCheck(); + EditorGUI.DelayedTextField(new Rect(rect.x + 195f, rect.y, rect.width - 255, 18), prop_SpriteName, new GUIContent("Name:")); + if (EditorGUI.EndChangeCheck()) + { + // Recompute hashCode for new name + prop_SpriteNameHashCode.intValue = TMP_TextUtilities.GetSimpleHashCode(prop_SpriteName.stringValue); + spriteAsset.m_IsSpriteAssetLookupTablesDirty = true; + } + + EditorGUIUtility.labelWidth = 59f; + EditorGUI.BeginChangeCheck(); + EditorGUI.DelayedIntField(new Rect(rect.x, rect.y + 18, 100, 18), prop_SpriteGlyphIndex, new GUIContent("Glyph ID:")); + if (EditorGUI.EndChangeCheck()) + { + spriteAsset.m_IsSpriteAssetLookupTablesDirty = true; + } + + // Draw Sprite Glyph (if exists) + DrawSpriteGlyph(position, property); + + int glyphIndex = prop_SpriteGlyphIndex.intValue; + + // Reset glyph selection if new character has been selected. + if (GUI.enabled && m_GlyphSelectedForEditing != glyphIndex) + m_GlyphSelectedForEditing = -1; + + // Display button to edit the glyph data. + if (GUI.Button(new Rect(rect.x + 120, rect.y + 18, 75, 18), new GUIContent("Edit Glyph"))) + { + if (m_GlyphSelectedForEditing == -1) + m_GlyphSelectedForEditing = glyphIndex; + else + m_GlyphSelectedForEditing = -1; + + // Button clicks should not result in potential change. + GUI.changed = false; + } + + // Show the glyph property drawer if selected + if (glyphIndex == m_GlyphSelectedForEditing && GUI.enabled) + { + if (spriteAsset != null) + { + // Lookup glyph and draw glyph (if available) + int elementIndex = spriteAsset.spriteGlyphTable.FindIndex(item => item.index == glyphIndex); + + if (elementIndex != -1) + { + // Get a reference to the Sprite Glyph Table + SerializedProperty prop_SpriteGlyphTable = property.serializedObject.FindProperty("m_SpriteGlyphTable"); + + SerializedProperty prop_SpriteGlyph = prop_SpriteGlyphTable.GetArrayElementAtIndex(elementIndex); + SerializedProperty prop_GlyphMetrics = prop_SpriteGlyph.FindPropertyRelative("m_Metrics"); + SerializedProperty prop_GlyphRect = prop_SpriteGlyph.FindPropertyRelative("m_GlyphRect"); + + Rect newRect = EditorGUILayout.GetControlRect(false, 115); + EditorGUI.DrawRect(new Rect(newRect.x + 62, newRect.y - 20, newRect.width - 62, newRect.height - 5), new Color(0.1f, 0.1f, 0.1f, 0.45f)); + EditorGUI.DrawRect(new Rect(newRect.x + 63, newRect.y - 19, newRect.width - 64, newRect.height - 7), new Color(0.3f, 0.3f, 0.3f, 0.8f)); + + // Display GlyphRect + newRect.x += 65; + newRect.y -= 18; + newRect.width += 5; + EditorGUI.PropertyField(newRect, prop_GlyphRect); + + // Display GlyphMetrics + newRect.y += 45; + EditorGUI.PropertyField(newRect, prop_GlyphMetrics); + + rect.y += 120; + } + } + } + + EditorGUIUtility.labelWidth = 39f; + EditorGUI.PropertyField(new Rect(rect.x, rect.y + 36, 80, 18), prop_SpriteScale, new GUIContent("Scale:")); + } + } + + + public override float GetPropertyHeight(SerializedProperty property, GUIContent label) + { + return 58; + } + + + void DrawSpriteGlyph(Rect position, SerializedProperty property) + { + // Get a reference to the sprite glyph table + TMP_SpriteAsset spriteAsset = property.serializedObject.targetObject as TMP_SpriteAsset; + + if (spriteAsset == null) + return; + + int glyphIndex = property.FindPropertyRelative("m_GlyphIndex").intValue; + + // Lookup glyph and draw glyph (if available) + int elementIndex = spriteAsset.spriteGlyphTable.FindIndex(item => item.index == glyphIndex); + + if (elementIndex != -1) + { + // Get a reference to the Sprite Glyph Table + SerializedProperty prop_SpriteGlyphTable = property.serializedObject.FindProperty("m_SpriteGlyphTable"); + SerializedProperty prop_SpriteGlyph = prop_SpriteGlyphTable.GetArrayElementAtIndex(elementIndex); + SerializedProperty prop_GlyphRect = prop_SpriteGlyph.FindPropertyRelative("m_GlyphRect"); + + // Get a reference to the sprite texture + Texture tex = spriteAsset.spriteSheet; + + // Return if we don't have a texture assigned to the sprite asset. + if (tex == null) + { + Debug.LogWarning("Please assign a valid Sprite Atlas texture to the [" + spriteAsset.name + "] Sprite Asset.", spriteAsset); + return; + } + + Vector2 spriteTexPosition = new Vector2(position.x, position.y); + Vector2 spriteSize = new Vector2(48, 48); + Vector2 alignmentOffset = new Vector2((58 - spriteSize.x) / 2, (58 - spriteSize.y) / 2); + + float x = prop_GlyphRect.FindPropertyRelative("m_X").intValue; + float y = prop_GlyphRect.FindPropertyRelative("m_Y").intValue; + float spriteWidth = prop_GlyphRect.FindPropertyRelative("m_Width").intValue; + float spriteHeight = prop_GlyphRect.FindPropertyRelative("m_Height").intValue; + + if (spriteWidth >= spriteHeight) + { + spriteSize.y = spriteHeight * spriteSize.x / spriteWidth; + spriteTexPosition.y += (spriteSize.x - spriteSize.y) / 2; + } + else + { + spriteSize.x = spriteWidth * spriteSize.y / spriteHeight; + spriteTexPosition.x += (spriteSize.y - spriteSize.x) / 2; + } + + // Compute the normalized texture coordinates + Rect texCoords = new Rect(x / tex.width, y / tex.height, spriteWidth / tex.width, spriteHeight / tex.height); + GUI.DrawTextureWithTexCoords(new Rect(spriteTexPosition.x + alignmentOffset.x, spriteTexPosition.y + alignmentOffset.y, spriteSize.x, spriteSize.y), tex, texCoords, true); + } + } + + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_SpriteGlyphPropertyDrawer.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_SpriteGlyphPropertyDrawer.cs new file mode 100644 index 00000000..06f527ec --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_SpriteGlyphPropertyDrawer.cs @@ -0,0 +1,93 @@ +using UnityEngine; +using UnityEngine.TextCore; +using UnityEditor; +using System.Collections; + + +namespace TMPro.EditorUtilities +{ + + [CustomPropertyDrawer(typeof(TMP_SpriteGlyph))] + public class TMP_SpriteGlyphPropertyDrawer : PropertyDrawer + { + public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) + { + SerializedProperty prop_GlyphIndex = property.FindPropertyRelative("m_Index"); + SerializedProperty prop_GlyphMetrics = property.FindPropertyRelative("m_Metrics"); + SerializedProperty prop_GlyphRect = property.FindPropertyRelative("m_GlyphRect"); + SerializedProperty prop_Scale = property.FindPropertyRelative("m_Scale"); + SerializedProperty prop_AtlasIndex = property.FindPropertyRelative("m_AtlasIndex"); + + GUIStyle style = new GUIStyle(EditorStyles.label); + style.richText = true; + + Rect rect = new Rect(position.x + 70, position.y, position.width, 49); + + // Draw GlyphRect + EditorGUI.PropertyField(rect, prop_GlyphRect); + + // Draw GlyphMetrics + rect.y += 45; + EditorGUI.PropertyField(rect, prop_GlyphMetrics); + + EditorGUIUtility.labelWidth = 40f; + EditorGUI.PropertyField(new Rect(rect.x, rect.y + 65, 75, 18), prop_Scale, new GUIContent("Scale:")); + + EditorGUIUtility.labelWidth = 74f; + EditorGUI.PropertyField(new Rect(rect.x + 85, rect.y + 65, 95, 18), prop_AtlasIndex, new GUIContent("Atlas Index:")); + + DrawGlyph(position, property); + + int.TryParse(property.displayName.Split(' ')[1], out int spriteCharacterIndex); + float labelWidthIndex = GUI.skin.label.CalcSize(new GUIContent("#" + spriteCharacterIndex)).x; + EditorGUI.LabelField(new Rect(position.x, position.y + 5, 64f, 18f), new GUIContent("#" + spriteCharacterIndex), style); + + float labelWidthID = GUI.skin.label.CalcSize(new GUIContent("ID: " + prop_GlyphIndex.intValue)).x; + EditorGUI.LabelField(new Rect(position.x + (64 - labelWidthID) / 2, position.y + 110, 64f, 18f), new GUIContent("ID: " + prop_GlyphIndex.intValue + ""), style); + } + + void DrawGlyph(Rect position, SerializedProperty property) + { + // Get a reference to the sprite texture + Texture tex = (property.serializedObject.targetObject as TMP_SpriteAsset).spriteSheet; + + // Return if we don't have a texture assigned to the sprite asset. + if (tex == null) + { + Debug.LogWarning("Please assign a valid Sprite Atlas texture to the [" + property.serializedObject.targetObject.name + "] Sprite Asset.", property.serializedObject.targetObject); + return; + } + + Vector2 spriteTexPosition = new Vector2(position.x, position.y); + Vector2 spriteSize = new Vector2(65, 65); + + SerializedProperty prop_GlyphRect = property.FindPropertyRelative("m_GlyphRect"); + + int spriteImageX = prop_GlyphRect.FindPropertyRelative("m_X").intValue; + int spriteImageY = prop_GlyphRect.FindPropertyRelative("m_Y").intValue; + int spriteImageWidth = prop_GlyphRect.FindPropertyRelative("m_Width").intValue; + int spriteImageHeight = prop_GlyphRect.FindPropertyRelative("m_Height").intValue; + + if (spriteImageWidth >= spriteImageHeight) + { + spriteSize.y = spriteImageHeight * spriteSize.x / spriteImageWidth; + spriteTexPosition.y += (spriteSize.x - spriteSize.y) / 2; + } + else + { + spriteSize.x = spriteImageWidth * spriteSize.y / spriteImageHeight; + spriteTexPosition.x += (spriteSize.y - spriteSize.x) / 2; + } + + // Compute the normalized texture coordinates + Rect texCoords = new Rect((float)spriteImageX / tex.width, (float)spriteImageY / tex.height, (float)spriteImageWidth / tex.width, (float)spriteImageHeight / tex.height); + GUI.DrawTextureWithTexCoords(new Rect(spriteTexPosition.x + 5, spriteTexPosition.y + 32f, spriteSize.x, spriteSize.y), tex, texCoords, true); + } + + public override float GetPropertyHeight(SerializedProperty property, GUIContent label) + { + return 130f; + } + + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_StyleAssetMenu.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_StyleAssetMenu.cs new file mode 100644 index 00000000..0ae9c386 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_StyleAssetMenu.cs @@ -0,0 +1,49 @@ +using UnityEngine; +using UnityEditor; +using System.IO; +using System.Collections; + + +namespace TMPro.EditorUtilities +{ + + public static class TMP_StyleAssetMenu + { + + [MenuItem("Assets/Create/TextMeshPro/Style Sheet", false, 120)] + public static void CreateTextMeshProObjectPerform() + { + string filePath; + if (Selection.assetGUIDs.Length == 0) + { + // No asset selected. + filePath = "Assets"; + } + else + { + // Get the path of the selected folder or asset. + filePath = AssetDatabase.GUIDToAssetPath(Selection.assetGUIDs[0]); + + // Get the file extension of the selected asset as it might need to be removed. + string fileExtension = Path.GetExtension(filePath); + if (fileExtension != "") + { + filePath = Path.GetDirectoryName(filePath); + } + } + + + string filePathWithName = AssetDatabase.GenerateUniqueAssetPath(filePath + "/TMP StyleSheet.asset"); + + //// Create new Style Sheet Asset. + TMP_StyleSheet styleSheet = ScriptableObject.CreateInstance(); + + AssetDatabase.CreateAsset(styleSheet, filePathWithName); + + EditorUtility.SetDirty(styleSheet); + + AssetDatabase.SaveAssets(); + } + } + +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_StyleSheetEditor.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_StyleSheetEditor.cs new file mode 100644 index 00000000..2e7f6de8 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_StyleSheetEditor.cs @@ -0,0 +1,278 @@ +using UnityEngine; +using UnityEditor; + + +namespace TMPro.EditorUtilities +{ + + [CustomPropertyDrawer(typeof(TMP_Style))] + public class StyleDrawer : PropertyDrawer + { + public static readonly float height = 95f; + + public override float GetPropertyHeight(SerializedProperty property, GUIContent label) + { + return height; + } + + public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) + { + SerializedProperty nameProperty = property.FindPropertyRelative("m_Name"); + SerializedProperty hashCodeProperty = property.FindPropertyRelative("m_HashCode"); + SerializedProperty openingDefinitionProperty = property.FindPropertyRelative("m_OpeningDefinition"); + SerializedProperty closingDefinitionProperty = property.FindPropertyRelative("m_ClosingDefinition"); + SerializedProperty openingDefinitionArray = property.FindPropertyRelative("m_OpeningTagArray"); + SerializedProperty closingDefinitionArray = property.FindPropertyRelative("m_ClosingTagArray"); + + + EditorGUIUtility.labelWidth = 90; + position.height = EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing; + float labelHeight = position.height + 2f; + + EditorGUI.BeginChangeCheck(); + Rect rect0 = new Rect(position.x, position.y, (position.width) / 2 + 5, position.height); + EditorGUI.PropertyField(rect0, nameProperty); + if (EditorGUI.EndChangeCheck()) + { + // Recompute HashCode if name has changed. + hashCodeProperty.intValue = TMP_TextUtilities.GetSimpleHashCode(nameProperty.stringValue); + + property.serializedObject.ApplyModifiedProperties(); + // Dictionary needs to be updated since HashCode has changed. + TMP_StyleSheet.RefreshStyles(); + } + + // HashCode + Rect rect1 = new Rect(rect0.x + rect0.width + 5, position.y, 65, position.height); + GUI.Label(rect1, "HashCode"); + GUI.enabled = false; + rect1.x += 65; + rect1.width = position.width / 2 - 75; + EditorGUI.PropertyField(rect1, hashCodeProperty, GUIContent.none); + + GUI.enabled = true; + + // Text Tags + EditorGUI.BeginChangeCheck(); + + // Opening Tags + position.y += labelHeight; + GUI.Label(position, "Opening Tags"); + Rect textRect1 = new Rect(108, position.y, position.width - 86, 35); + openingDefinitionProperty.stringValue = EditorGUI.TextArea(textRect1, openingDefinitionProperty.stringValue); + if (EditorGUI.EndChangeCheck()) + { + // If any properties have changed, we need to update the Opening and Closing Arrays. + int size = openingDefinitionProperty.stringValue.Length; + + // Adjust array size to match new string length. + if (openingDefinitionArray.arraySize != size) openingDefinitionArray.arraySize = size; + + for (int i = 0; i < size; i++) + { + SerializedProperty element = openingDefinitionArray.GetArrayElementAtIndex(i); + element.intValue = openingDefinitionProperty.stringValue[i]; + } + } + + EditorGUI.BeginChangeCheck(); + + // Closing Tags + position.y += 38; + GUI.Label(position, "Closing Tags"); + Rect textRect2 = new Rect(108, position.y, position.width - 86, 35); + closingDefinitionProperty.stringValue = EditorGUI.TextArea(textRect2, closingDefinitionProperty.stringValue); + + if (EditorGUI.EndChangeCheck()) + { + // If any properties have changed, we need to update the Opening and Closing Arrays. + int size = closingDefinitionProperty.stringValue.Length; + + // Adjust array size to match new string length. + if (closingDefinitionArray.arraySize != size) closingDefinitionArray.arraySize = size; + + for (int i = 0; i < size; i++) + { + SerializedProperty element = closingDefinitionArray.GetArrayElementAtIndex(i); + element.intValue = closingDefinitionProperty.stringValue[i]; + } + } + + } + } + + + + [CustomEditor(typeof(TMP_StyleSheet)), CanEditMultipleObjects] + public class TMP_StyleEditor : Editor + { + + SerializedProperty m_StyleListProp; + + int m_SelectedElement = -1; + + //private Event m_CurrentEvent; + int m_Page; + + + + void OnEnable() + { + m_StyleListProp = serializedObject.FindProperty("m_StyleList"); + } + + + public override void OnInspectorGUI() + { + Event currentEvent = Event.current; + + serializedObject.Update(); + + int arraySize = m_StyleListProp.arraySize; + int itemsPerPage = (Screen.height - 178) / 111; + + if (arraySize > 0) + { + // Display each Style entry using the StyleDrawer PropertyDrawer. + for (int i = itemsPerPage * m_Page; i < arraySize && i < itemsPerPage * (m_Page + 1); i++) + { + + // Define the start of the selection region of the element. + Rect elementStartRegion = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true)); + + EditorGUILayout.BeginVertical(EditorStyles.helpBox); + + SerializedProperty spriteInfo = m_StyleListProp.GetArrayElementAtIndex(i); + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(spriteInfo); + EditorGUILayout.EndVertical(); + if (EditorGUI.EndChangeCheck()) + { + // + } + + // Define the end of the selection region of the element. + Rect elementEndRegion = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true)); + + // Check for Item selection + Rect selectionArea = new Rect(elementStartRegion.x, elementStartRegion.y, elementEndRegion.width, elementEndRegion.y - elementStartRegion.y); + if (DoSelectionCheck(selectionArea)) + { + if (m_SelectedElement == i) + { + m_SelectedElement = -1; + } + else + { + m_SelectedElement = i; + GUIUtility.keyboardControl = 0; + } + } + + // Handle Selection Highlighting + if (m_SelectedElement == i) + { + TMP_EditorUtility.DrawBox(selectionArea, 2f, new Color32(40, 192, 255, 255)); + } + } + } + + int shiftMultiplier = currentEvent.shift ? 10 : 1; // Page + Shift goes 10 page forward + + GUILayout.Space(-3f); + + Rect pagePos = EditorGUILayout.GetControlRect(false, 20); + pagePos.width /= 6; + + // Return if we can't display any items. + if (itemsPerPage == 0) return; + + + // Add new style. + pagePos.x += pagePos.width * 4; + if (GUI.Button(pagePos, "+")) + { + m_StyleListProp.arraySize += 1; + serializedObject.ApplyModifiedProperties(); + TMP_StyleSheet.RefreshStyles(); + } + + + // Delete selected style. + pagePos.x += pagePos.width; + if (m_SelectedElement == -1) GUI.enabled = false; + if (GUI.Button(pagePos, "-")) + { + if (m_SelectedElement != -1) + m_StyleListProp.DeleteArrayElementAtIndex(m_SelectedElement); + + m_SelectedElement = -1; + serializedObject.ApplyModifiedProperties(); + TMP_StyleSheet.RefreshStyles(); + } + + GUILayout.Space(5f); + + pagePos = EditorGUILayout.GetControlRect(false, 20); + pagePos.width /= 3; + + + // Previous Page + if (m_Page > 0) GUI.enabled = true; + else GUI.enabled = false; + + if (GUI.Button(pagePos, "Previous")) + m_Page -= 1 * shiftMultiplier; + + // PAGE COUNTER + GUI.enabled = true; + pagePos.x += pagePos.width; + int totalPages = (int)(arraySize / (float)itemsPerPage + 0.999f); + GUI.Label(pagePos, "Page " + (m_Page + 1) + " / " + totalPages, TMP_UIStyleManager.centeredLabel); + + // Next Page + pagePos.x += pagePos.width; + if (itemsPerPage * (m_Page + 1) < arraySize) GUI.enabled = true; + else GUI.enabled = false; + + if (GUI.Button(pagePos, "Next")) + m_Page += 1 * shiftMultiplier; + + // Clamp page range + m_Page = Mathf.Clamp(m_Page, 0, arraySize / itemsPerPage); + + + if (serializedObject.ApplyModifiedProperties()) + TMPro_EventManager.ON_TEXT_STYLE_PROPERTY_CHANGED(true); + + // Clear selection if mouse event was not consumed. + GUI.enabled = true; + if (currentEvent.type == EventType.MouseDown && currentEvent.button == 0) + m_SelectedElement = -1; + + + } + + + // Check if any of the Style elements were clicked on. + static bool DoSelectionCheck(Rect selectionArea) + { + Event currentEvent = Event.current; + + switch (currentEvent.type) + { + case EventType.MouseDown: + if (selectionArea.Contains(currentEvent.mousePosition) && currentEvent.button == 0) + { + currentEvent.Use(); + return true; + } + break; + } + + return false; + } + + } + +} diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_SubMeshUI_Editor.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_SubMeshUI_Editor.cs new file mode 100644 index 00000000..1cbea769 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_SubMeshUI_Editor.cs @@ -0,0 +1,98 @@ +using UnityEngine; +using UnityEditor; +using System.Collections; + +namespace TMPro.EditorUtilities +{ + [CustomEditor(typeof(TMP_SubMeshUI)), CanEditMultipleObjects] + public class TMP_SubMeshUI_Editor : Editor + { + private struct m_foldout + { // Track Inspector foldout panel states, globally. + //public static bool textInput = true; + public static bool fontSettings = true; + //public static bool extraSettings = false; + //public static bool shadowSetting = false; + //public static bool materialEditor = true; + } + + private SerializedProperty fontAsset_prop; + private SerializedProperty spriteAsset_prop; + + private TMP_SubMeshUI m_SubMeshComponent; + + private CanvasRenderer m_canvasRenderer; + private Editor m_materialEditor; + private Material m_targetMaterial; + + + public void OnEnable() + { + fontAsset_prop = serializedObject.FindProperty("m_fontAsset"); + spriteAsset_prop = serializedObject.FindProperty("m_spriteAsset"); + + m_SubMeshComponent = target as TMP_SubMeshUI; + //m_rectTransform = m_SubMeshComponent.rectTransform; + m_canvasRenderer = m_SubMeshComponent.canvasRenderer; + + + // Create new Material Editor if one does not exists + if (m_canvasRenderer != null && m_canvasRenderer.GetMaterial() != null) + { + m_materialEditor = Editor.CreateEditor(m_canvasRenderer.GetMaterial()); + m_targetMaterial = m_canvasRenderer.GetMaterial(); + } + } + + + public void OnDisable() + { + // Destroy material editor if one exists + if (m_materialEditor != null) + { + //Debug.Log("Destroying Inline Material Editor."); + DestroyImmediate(m_materialEditor); + } + } + + + + public override void OnInspectorGUI() + { + GUI.enabled = false; + EditorGUILayout.PropertyField(fontAsset_prop); + EditorGUILayout.PropertyField(spriteAsset_prop); + GUI.enabled = true; + + EditorGUILayout.Space(); + + // If a Custom Material Editor exists, we use it. + if (m_canvasRenderer != null && m_canvasRenderer.GetMaterial() != null) + { + Material mat = m_canvasRenderer.GetMaterial(); + + //Debug.Log(mat + " " + m_targetMaterial); + + if (mat != m_targetMaterial) + { + // Destroy previous Material Instance + //Debug.Log("New Material has been assigned."); + m_targetMaterial = mat; + DestroyImmediate(m_materialEditor); + } + + + if (m_materialEditor == null) + { + m_materialEditor = Editor.CreateEditor(mat); + } + + m_materialEditor.DrawHeader(); + + + m_materialEditor.OnInspectorGUI(); + } + } + + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_SubMesh_Editor.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_SubMesh_Editor.cs new file mode 100644 index 00000000..b5a3cc7c --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_SubMesh_Editor.cs @@ -0,0 +1,76 @@ +using UnityEngine; +using UnityEditor; +using System.Collections; + +namespace TMPro.EditorUtilities +{ + [CustomEditor(typeof(TMP_SubMesh)), CanEditMultipleObjects] + public class TMP_SubMesh_Editor : Editor + { + private struct m_foldout + { // Track Inspector foldout panel states, globally. + //public static bool textInput = true; + public static bool fontSettings = true; + //public static bool extraSettings = false; + //public static bool shadowSetting = false; + //public static bool materialEditor = true; + } + + private SerializedProperty fontAsset_prop; + private SerializedProperty spriteAsset_prop; + + private TMP_SubMesh m_SubMeshComponent; + private Renderer m_Renderer; + + public void OnEnable() + { + fontAsset_prop = serializedObject.FindProperty("m_fontAsset"); + spriteAsset_prop = serializedObject.FindProperty("m_spriteAsset"); + + m_SubMeshComponent = target as TMP_SubMesh; + + m_Renderer = m_SubMeshComponent.renderer; + } + + + public override void OnInspectorGUI() + { + EditorGUI.indentLevel = 0; + + GUI.enabled = false; + EditorGUILayout.PropertyField(fontAsset_prop); + EditorGUILayout.PropertyField(spriteAsset_prop); + GUI.enabled = true; + + EditorGUI.BeginChangeCheck(); + + // SORTING LAYERS + var sortingLayerNames = SortingLayerHelper.sortingLayerNames; + + // Look up the layer name using the current layer ID + string oldName = SortingLayerHelper.GetSortingLayerNameFromID(m_Renderer.sortingLayerID); + + // Use the name to look up our array index into the names list + int oldLayerIndex = System.Array.IndexOf(sortingLayerNames, oldName); + + // Show the pop-up for the names + int newLayerIndex = EditorGUILayout.Popup("Sorting Layer", oldLayerIndex, sortingLayerNames); + + // If the index changes, look up the ID for the new index to store as the new ID + if (newLayerIndex != oldLayerIndex) + { + //Undo.RecordObject(renderer, "Edit Sorting Layer"); + m_Renderer.sortingLayerID = SortingLayerHelper.GetSortingLayerIDForIndex(newLayerIndex); + //EditorUtility.SetDirty(renderer); + } + + // Expose the manual sorting order + int newSortingLayerOrder = EditorGUILayout.IntField("Order in Layer", m_Renderer.sortingOrder); + if (newSortingLayerOrder != m_Renderer.sortingOrder) + { + //Undo.RecordObject(renderer, "Edit Sorting Order"); + m_Renderer.sortingOrder = newSortingLayerOrder; + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_TextAlignmentDrawer.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_TextAlignmentDrawer.cs new file mode 100644 index 00000000..dbb271c5 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_TextAlignmentDrawer.cs @@ -0,0 +1,119 @@ +using UnityEngine; +using UnityEditor; + +namespace TMPro.EditorUtilities +{ + + [CustomPropertyDrawer(typeof(TextAlignmentOptions))] + public class TMP_TextAlignmentDrawer : PropertyDrawer + { + const int k_AlignmentButtonWidth = 24; + const int k_AlignmentButtonHeight = 20; + const int k_WideViewWidth = 504; + const int k_ControlsSpacing = 6; + const int k_GroupWidth = k_AlignmentButtonWidth * 6; + static readonly int k_TextAlignmentHash = "DoTextAligmentControl".GetHashCode(); + + public override float GetPropertyHeight(SerializedProperty property, GUIContent label) + { + return EditorGUIUtility.currentViewWidth > k_WideViewWidth ? k_AlignmentButtonHeight : k_AlignmentButtonHeight * 2 + 3; + } + + public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) + { + var id = GUIUtility.GetControlID(k_TextAlignmentHash, FocusType.Keyboard, position); + + EditorGUI.BeginProperty(position, label, property); + { + var controlArea = EditorGUI.PrefixLabel(position, id, label); + + var horizontalAligment = new Rect(controlArea.x, controlArea.y, k_GroupWidth, k_AlignmentButtonHeight); + var verticalAligment = new Rect(!(EditorGUIUtility.currentViewWidth > k_WideViewWidth) ? controlArea.x : horizontalAligment.xMax + k_ControlsSpacing, !(EditorGUIUtility.currentViewWidth > k_WideViewWidth) ? controlArea.y + k_AlignmentButtonHeight + 3 : controlArea.y, k_GroupWidth, k_AlignmentButtonHeight); + + EditorGUI.BeginChangeCheck(); + + var selectedHorizontal = DoHorizontalAligmentControl(horizontalAligment, property); + var selectedVertical = DoVerticalAligmentControl(verticalAligment, property); + + if (EditorGUI.EndChangeCheck()) + { + var value = (0x1 << selectedHorizontal) | (0x100 << selectedVertical); + property.intValue = value; + } + } + EditorGUI.EndProperty(); + } + + static int DoHorizontalAligmentControl(Rect position, SerializedProperty alignment) + { + var selected = TMP_EditorUtility.GetHorizontalAlignmentGridValue(alignment.intValue); + + var values = new bool[6]; + + values[selected] = true; + + if (alignment.hasMultipleDifferentValues) + { + foreach (var obj in alignment.serializedObject.targetObjects) + { + var text = obj as TMP_Text; + if (text != null) + { + values[TMP_EditorUtility.GetHorizontalAlignmentGridValue((int)text.alignment)] = true; + } + } + } + + position.width = k_AlignmentButtonWidth; + + for (var i = 0; i < values.Length; i++) + { + var oldValue = values[i]; + var newValue = TMP_EditorUtility.EditorToggle(position, oldValue, TMP_UIStyleManager.alignContentA[i], i == 0 ? TMP_UIStyleManager.alignmentButtonLeft : (i == 5 ? TMP_UIStyleManager.alignmentButtonRight : TMP_UIStyleManager.alignmentButtonMid)); + if (newValue != oldValue) + { + selected = i; + } + position.x += position.width; + } + + return selected; + } + + static int DoVerticalAligmentControl(Rect position, SerializedProperty alignment) + { + var selected = TMP_EditorUtility.GetVerticalAlignmentGridValue(alignment.intValue); + + var values = new bool[6]; + + values[selected] = true; + + if (alignment.hasMultipleDifferentValues) + { + foreach (var obj in alignment.serializedObject.targetObjects) + { + var text = obj as TMP_Text; + if (text != null) + { + values[TMP_EditorUtility.GetVerticalAlignmentGridValue((int)text.alignment)] = true; + } + } + } + + position.width = k_AlignmentButtonWidth; + + for (var i = 0; i < values.Length; i++) + { + var oldValue = values[i]; + var newValue = TMP_EditorUtility.EditorToggle(position, oldValue, TMP_UIStyleManager.alignContentB[i], i == 0 ? TMP_UIStyleManager.alignmentButtonLeft : (i == 5 ? TMP_UIStyleManager.alignmentButtonRight : TMP_UIStyleManager.alignmentButtonMid)); + if (newValue != oldValue) + { + selected = i; + } + position.x += position.width; + } + + return selected; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_UIStyleManager.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_UIStyleManager.cs new file mode 100644 index 00000000..0a94a997 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_UIStyleManager.cs @@ -0,0 +1,134 @@ +using UnityEngine; +using UnityEditor; +using System.Collections; + + +namespace TMPro.EditorUtilities +{ + + public static class TMP_UIStyleManager + { + public static GUIStyle label; + public static GUIStyle textAreaBoxWindow; + public static GUIStyle boldFoldout; + public static GUIStyle panelTitle; + public static GUIStyle sectionHeader; + public static GUIStyle centeredLabel; + public static GUIStyle rightLabel; + public static GUIStyle wrappingTextArea; + + public static GUIStyle alignmentButtonLeft; + public static GUIStyle alignmentButtonMid; + public static GUIStyle alignmentButtonRight; + + // Alignment Button Textures + public static Texture2D alignLeft; + public static Texture2D alignCenter; + public static Texture2D alignRight; + public static Texture2D alignJustified; + public static Texture2D alignFlush; + public static Texture2D alignGeoCenter; + public static Texture2D alignTop; + public static Texture2D alignMiddle; + public static Texture2D alignBottom; + public static Texture2D alignBaseline; + public static Texture2D alignMidline; + public static Texture2D alignCapline; + public static Texture2D sectionHeaderTexture; + + public static GUIContent[] alignContentA; + public static GUIContent[] alignContentB; + + static TMP_UIStyleManager() + { + // Find to location of the TextMesh Pro Asset Folder (as users may have moved it) + var tmproAssetFolderPath = TMP_EditorUtility.packageRelativePath; + + if (EditorGUIUtility.isProSkin) + { + alignLeft = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignLeft.psd", typeof(Texture2D)) as Texture2D; + alignCenter = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignCenter.psd", typeof(Texture2D)) as Texture2D; + alignRight = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignRight.psd", typeof(Texture2D)) as Texture2D; + alignJustified = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignJustified.psd", typeof(Texture2D)) as Texture2D; + alignFlush = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignFlush.psd", typeof(Texture2D)) as Texture2D; + alignGeoCenter = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignCenterGeo.psd", typeof(Texture2D)) as Texture2D; + alignTop = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignTop.psd", typeof(Texture2D)) as Texture2D; + alignMiddle = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignMiddle.psd", typeof(Texture2D)) as Texture2D; + alignBottom = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignBottom.psd", typeof(Texture2D)) as Texture2D; + alignBaseline = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignBaseLine.psd", typeof(Texture2D)) as Texture2D; + alignMidline = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignMidLine.psd", typeof(Texture2D)) as Texture2D; + alignCapline = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignCapLine.psd", typeof(Texture2D)) as Texture2D; + sectionHeaderTexture = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/SectionHeader_Dark.psd", typeof(Texture2D)) as Texture2D; + } + else + { + alignLeft = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignLeft_Light.psd", typeof(Texture2D)) as Texture2D; + alignCenter = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignCenter_Light.psd", typeof(Texture2D)) as Texture2D; + alignRight = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignRight_Light.psd", typeof(Texture2D)) as Texture2D; + alignJustified = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignJustified_Light.psd", typeof(Texture2D)) as Texture2D; + alignFlush = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignFlush_Light.psd", typeof(Texture2D)) as Texture2D; + alignGeoCenter = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignCenterGeo_Light.psd", typeof(Texture2D)) as Texture2D; + alignTop = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignTop_Light.psd", typeof(Texture2D)) as Texture2D; + alignMiddle = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignMiddle_Light.psd", typeof(Texture2D)) as Texture2D; + alignBottom = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignBottom_Light.psd", typeof(Texture2D)) as Texture2D; + alignBaseline = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignBaseLine_Light.psd", typeof(Texture2D)) as Texture2D; + alignMidline = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignMidLine_Light.psd", typeof(Texture2D)) as Texture2D; + alignCapline = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignCapLine_Light.psd", typeof(Texture2D)) as Texture2D; + sectionHeaderTexture = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/SectionHeader_Light.psd", typeof(Texture2D)) as Texture2D; + } + + label = new GUIStyle(EditorStyles.label) { richText = true, wordWrap = true, stretchWidth = true }; + textAreaBoxWindow = new GUIStyle(EditorStyles.textArea) { richText = true }; + boldFoldout = new GUIStyle(EditorStyles.foldout) { fontStyle = FontStyle.Bold }; + panelTitle = new GUIStyle(EditorStyles.label) { fontStyle = FontStyle.Bold }; + + sectionHeader = new GUIStyle(EditorStyles.label) { fixedHeight = 22, richText = true, border = new RectOffset(9, 9, 0, 0), overflow = new RectOffset(9, 0, 0, 0), padding = new RectOffset(0, 0, 4, 0) }; + sectionHeader.normal.background = sectionHeaderTexture; + + centeredLabel = new GUIStyle(EditorStyles.label) { alignment = TextAnchor.MiddleCenter}; + rightLabel = new GUIStyle(EditorStyles.label) { alignment = TextAnchor.MiddleRight, richText = true }; + + + alignmentButtonLeft = new GUIStyle(EditorStyles.miniButtonLeft); + alignmentButtonLeft.padding.left = 4; + alignmentButtonLeft.padding.right = 4; + alignmentButtonLeft.padding.top = 2; + alignmentButtonLeft.padding.bottom = 2; + + alignmentButtonMid = new GUIStyle(EditorStyles.miniButtonMid); + alignmentButtonMid.padding.left = 4; + alignmentButtonMid.padding.right = 4; + alignmentButtonLeft.padding.top = 2; + alignmentButtonLeft.padding.bottom = 2; + + alignmentButtonRight = new GUIStyle(EditorStyles.miniButtonRight); + alignmentButtonRight.padding.left = 4; + alignmentButtonRight.padding.right = 4; + alignmentButtonLeft.padding.top = 2; + alignmentButtonLeft.padding.bottom = 2; + + wrappingTextArea = new GUIStyle(EditorStyles.textArea); + wrappingTextArea.wordWrap = true; + + alignContentA = new [] + { + new GUIContent(alignLeft, "Left"), + new GUIContent(alignCenter, "Center"), + new GUIContent(alignRight, "Right"), + new GUIContent(alignJustified, "Justified"), + new GUIContent(alignFlush, "Flush"), + new GUIContent(alignGeoCenter, "Geometry Center") + }; + + alignContentB = new [] + { + new GUIContent(alignTop, "Top"), + new GUIContent(alignMiddle, "Middle"), + new GUIContent(alignBottom, "Bottom"), + new GUIContent(alignBaseline, "Baseline"), + new GUIContent(alignMidline, "Midline"), + new GUIContent(alignCapline, "Capline") + }; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_UiEditorPanel.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_UiEditorPanel.cs new file mode 100644 index 00000000..87181650 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_UiEditorPanel.cs @@ -0,0 +1,91 @@ +using UnityEngine; +using UnityEngine.UI; +using UnityEditor; + +namespace TMPro.EditorUtilities +{ + + [CustomEditor(typeof(TextMeshProUGUI), true), CanEditMultipleObjects] + public class TMP_UiEditorPanel : TMP_BaseEditorPanel + { + static readonly GUIContent k_RaycastTargetLabel = new GUIContent("Raycast Target", "Whether the text blocks raycasts from the Graphic Raycaster."); + + SerializedProperty m_RaycastTargetProp; + + protected override void OnEnable() + { + base.OnEnable(); + m_RaycastTargetProp = serializedObject.FindProperty("m_RaycastTarget"); + } + + protected override void DrawExtraSettings() + { + Foldout.extraSettings = EditorGUILayout.Foldout(Foldout.extraSettings, k_ExtraSettingsLabel, true, TMP_UIStyleManager.boldFoldout); + if (Foldout.extraSettings) + { + EditorGUI.indentLevel += 1; + + DrawMargins(); + + DrawGeometrySorting(); + + DrawRichText(); + + DrawRaycastTarget(); + + DrawParsing(); + + DrawKerning(); + + DrawPadding(); + + EditorGUI.indentLevel -= 1; + } + } + + protected void DrawRaycastTarget() + { + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(m_RaycastTargetProp, k_RaycastTargetLabel); + if (EditorGUI.EndChangeCheck()) + { + // Change needs to propagate to the child sub objects. + Graphic[] graphicComponents = m_TextComponent.GetComponentsInChildren(); + for (int i = 1; i < graphicComponents.Length; i++) + graphicComponents[i].raycastTarget = m_RaycastTargetProp.boolValue; + + m_HavePropertiesChanged = true; + } + } + + // Method to handle multi object selection + protected override bool IsMixSelectionTypes() + { + GameObject[] objects = Selection.gameObjects; + if (objects.Length > 1) + { + for (int i = 0; i < objects.Length; i++) + { + if (objects[i].GetComponent() == null) + return true; + } + } + return false; + } + protected override void OnUndoRedo() + { + int undoEventId = Undo.GetCurrentGroup(); + int lastUndoEventId = s_EventId; + + if (undoEventId != lastUndoEventId) + { + for (int i = 0; i < targets.Length; i++) + { + //Debug.Log("Undo & Redo Performed detected in Editor Panel. Event ID:" + Undo.GetCurrentGroup()); + TMPro_EventManager.ON_TEXTMESHPRO_UGUI_PROPERTY_CHANGED(true, targets[i] as TextMeshProUGUI); + s_EventId = undoEventId; + } + } + } + } +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMPro_ContextMenus.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMPro_ContextMenus.cs new file mode 100644 index 00000000..8d65b706 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMPro_ContextMenus.cs @@ -0,0 +1,341 @@ +using UnityEngine; +using UnityEditor; +using System.IO; +using System.Collections; + + +namespace TMPro.EditorUtilities +{ + + public class TMP_ContextMenus : Editor + { + + private static Texture m_copiedTexture; + + private static Material m_copiedProperties; + private static Material m_copiedAtlasProperties; + + + // Add a Context Menu to the Texture Editor Panel to allow Copy / Paste of Texture. + [MenuItem("CONTEXT/Texture/Copy", false, 2000)] + static void CopyTexture(MenuCommand command) + { + m_copiedTexture = command.context as Texture; + } + + + // Select the currently assigned material or material preset. + [MenuItem("CONTEXT/Material/Select Material", false, 500)] + static void SelectMaterial(MenuCommand command) + { + Material mat = command.context as Material; + + // Select current material + EditorUtility.FocusProjectWindow(); + EditorGUIUtility.PingObject(mat); + } + + + // Add a Context Menu to allow easy duplication of the Material. + [MenuItem("CONTEXT/Material/Create Material Preset", false)] + static void DuplicateMaterial(MenuCommand command) + { + // Get the type of text object + // If material is not a base material, we get material leaks... + + Material source_Mat = (Material)command.context; + if (!EditorUtility.IsPersistent(source_Mat)) + { + Debug.LogWarning("Material is an instance and cannot be converted into a permanent asset."); + return; + } + + + string assetPath = AssetDatabase.GetAssetPath(source_Mat).Split('.')[0]; + + Material duplicate = new Material(source_Mat); + + // Need to manually copy the shader keywords + duplicate.shaderKeywords = source_Mat.shaderKeywords; + + AssetDatabase.CreateAsset(duplicate, AssetDatabase.GenerateUniqueAssetPath(assetPath + ".mat")); + + // Assign duplicate Material to selected object (if one is) + if (Selection.activeGameObject != null) + { + TMP_Text textObject = Selection.activeGameObject.GetComponent(); + if (textObject != null) + { + textObject.fontSharedMaterial = duplicate; + } + else + { + TMP_SubMesh subMeshObject = Selection.activeGameObject.GetComponent(); + + if (subMeshObject != null) + subMeshObject.sharedMaterial = duplicate; + else + { + TMP_SubMeshUI subMeshUIObject = Selection.activeGameObject.GetComponent(); + + if (subMeshUIObject != null) + subMeshUIObject.sharedMaterial = duplicate; + } + } + } + + // Ping newly created Material Preset. + EditorUtility.FocusProjectWindow(); + EditorGUIUtility.PingObject(duplicate); + } + + + //[MenuItem("CONTEXT/MaterialComponent/Copy Material Properties", false)] + [MenuItem("CONTEXT/Material/Copy Material Properties", false)] + static void CopyMaterialProperties(MenuCommand command) + { + Material mat = null; + if (command.context.GetType() == typeof(Material)) + mat = (Material)command.context; + else + { + mat = Selection.activeGameObject.GetComponent().GetMaterial(); + } + + m_copiedProperties = new Material(mat); + + m_copiedProperties.shaderKeywords = mat.shaderKeywords; + + m_copiedProperties.hideFlags = HideFlags.DontSave; + } + + + // PASTE MATERIAL + //[MenuItem("CONTEXT/MaterialComponent/Paste Material Properties", false)] + [MenuItem("CONTEXT/Material/Paste Material Properties", false)] + static void PasteMaterialProperties(MenuCommand command) + { + + if (m_copiedProperties == null) + { + Debug.LogWarning("No Material Properties to Paste. Use Copy Material Properties first."); + return; + } + + Material mat = null; + if (command.context.GetType() == typeof(Material)) + mat = (Material)command.context; + else + { + mat = Selection.activeGameObject.GetComponent().GetMaterial(); + } + + Undo.RecordObject(mat, "Paste Material"); + + ShaderUtilities.GetShaderPropertyIDs(); // Make sure we have valid Property IDs + if (mat.HasProperty(ShaderUtilities.ID_GradientScale)) + { + // Preserve unique SDF properties from destination material. + m_copiedProperties.SetTexture(ShaderUtilities.ID_MainTex, mat.GetTexture(ShaderUtilities.ID_MainTex)); + m_copiedProperties.SetFloat(ShaderUtilities.ID_GradientScale, mat.GetFloat(ShaderUtilities.ID_GradientScale)); + m_copiedProperties.SetFloat(ShaderUtilities.ID_TextureWidth, mat.GetFloat(ShaderUtilities.ID_TextureWidth)); + m_copiedProperties.SetFloat(ShaderUtilities.ID_TextureHeight, mat.GetFloat(ShaderUtilities.ID_TextureHeight)); + } + + EditorShaderUtilities.CopyMaterialProperties(m_copiedProperties, mat); + + // Copy ShaderKeywords from one material to the other. + mat.shaderKeywords = m_copiedProperties.shaderKeywords; + + // Let TextMeshPro Objects that this mat has changed. + TMPro_EventManager.ON_MATERIAL_PROPERTY_CHANGED(true, mat); + } + + + // Enable Resetting of Material properties without losing unique properties of the font atlas. + [MenuItem("CONTEXT/Material/Reset", false, 2100)] + static void ResetSettings(MenuCommand command) + { + + Material mat = null; + if (command.context.GetType() == typeof(Material)) + mat = (Material)command.context; + else + { + mat = Selection.activeGameObject.GetComponent().GetMaterial(); + } + + Undo.RecordObject(mat, "Reset Material"); + + ShaderUtilities.GetShaderPropertyIDs(); // Make sure we have valid Property IDs + if (mat.HasProperty(ShaderUtilities.ID_GradientScale)) + { + // Copy unique properties of the SDF Material + var texture = mat.GetTexture(ShaderUtilities.ID_MainTex); + var gradientScale = mat.GetFloat(ShaderUtilities.ID_GradientScale); + var texWidth = mat.GetFloat(ShaderUtilities.ID_TextureWidth); + var texHeight = mat.GetFloat(ShaderUtilities.ID_TextureHeight); + + var stencilId = 0.0f; + var stencilComp = 0.0f; + + if (mat.HasProperty(ShaderUtilities.ID_StencilID)) + { + stencilId = mat.GetFloat(ShaderUtilities.ID_StencilID); + stencilComp = mat.GetFloat(ShaderUtilities.ID_StencilComp); + } + + var normalWeight = mat.GetFloat(ShaderUtilities.ID_WeightNormal); + var boldWeight = mat.GetFloat(ShaderUtilities.ID_WeightBold); + + // Reset the material + Unsupported.SmartReset(mat); + + // Reset ShaderKeywords + mat.shaderKeywords = new string[0]; // { "BEVEL_OFF", "GLOW_OFF", "UNDERLAY_OFF" }; + + // Copy unique material properties back to the material. + mat.SetTexture(ShaderUtilities.ID_MainTex, texture); + mat.SetFloat(ShaderUtilities.ID_GradientScale, gradientScale); + mat.SetFloat(ShaderUtilities.ID_TextureWidth, texWidth); + mat.SetFloat(ShaderUtilities.ID_TextureHeight, texHeight); + + if (mat.HasProperty(ShaderUtilities.ID_StencilID)) + { + mat.SetFloat(ShaderUtilities.ID_StencilID, stencilId); + mat.SetFloat(ShaderUtilities.ID_StencilComp, stencilComp); + } + + mat.SetFloat(ShaderUtilities.ID_WeightNormal, normalWeight); + mat.SetFloat(ShaderUtilities.ID_WeightBold, boldWeight); + } + else + { + Unsupported.SmartReset(mat); + } + + TMPro_EventManager.ON_MATERIAL_PROPERTY_CHANGED(true, mat); + } + + + + //This function is used for debugging and fixing potentially broken font atlas links. + [MenuItem("CONTEXT/Material/Copy Atlas", false, 2000)] + static void CopyAtlas(MenuCommand command) + { + Material mat = command.context as Material; + + m_copiedAtlasProperties = new Material(mat); + m_copiedAtlasProperties.hideFlags = HideFlags.DontSave; + } + + + // This function is used for debugging and fixing potentially broken font atlas links + [MenuItem("CONTEXT/Material/Paste Atlas", false, 2001)] + static void PasteAtlas(MenuCommand command) + { + Material mat = command.context as Material; + + if (m_copiedAtlasProperties != null) + { + Undo.RecordObject(mat, "Paste Texture"); + + ShaderUtilities.GetShaderPropertyIDs(); // Make sure we have valid Property IDs + mat.SetTexture(ShaderUtilities.ID_MainTex, m_copiedAtlasProperties.GetTexture(ShaderUtilities.ID_MainTex)); + mat.SetFloat(ShaderUtilities.ID_GradientScale, m_copiedAtlasProperties.GetFloat(ShaderUtilities.ID_GradientScale)); + mat.SetFloat(ShaderUtilities.ID_TextureWidth, m_copiedAtlasProperties.GetFloat(ShaderUtilities.ID_TextureWidth)); + mat.SetFloat(ShaderUtilities.ID_TextureHeight, m_copiedAtlasProperties.GetFloat(ShaderUtilities.ID_TextureHeight)); + } + else if (m_copiedTexture != null) + { + Undo.RecordObject(mat, "Paste Texture"); + + mat.SetTexture(ShaderUtilities.ID_MainTex, m_copiedTexture); + } + + //DestroyImmediate(m_copiedAtlasProperties); + } + + + // Context Menus for TMPro Font Assets + //This function is used for debugging and fixing potentially broken font atlas links. + [MenuItem("CONTEXT/TMP_FontAsset/Extract Atlas", false, 2100)] + static void ExtractAtlas(MenuCommand command) + { + TMP_FontAsset font = command.context as TMP_FontAsset; + + string fontPath = AssetDatabase.GetAssetPath(font); + string texPath = Path.GetDirectoryName(fontPath) + "/" + Path.GetFileNameWithoutExtension(fontPath) + " Atlas.png"; + + // Create a Serialized Object of the texture to allow us to make it readable. + SerializedObject texprop = new SerializedObject(font.material.GetTexture(ShaderUtilities.ID_MainTex)); + texprop.FindProperty("m_IsReadable").boolValue = true; + texprop.ApplyModifiedProperties(); + + // Create a copy of the texture. + Texture2D tex = Instantiate(font.material.GetTexture(ShaderUtilities.ID_MainTex)) as Texture2D; + + // Set the texture to not readable again. + texprop.FindProperty("m_IsReadable").boolValue = false; + texprop.ApplyModifiedProperties(); + + Debug.Log(texPath); + // Saving File for Debug + var pngData = tex.EncodeToPNG(); + File.WriteAllBytes(texPath, pngData); + + AssetDatabase.Refresh(); + DestroyImmediate(tex); + } + + /// + /// + /// + /// + [MenuItem("CONTEXT/TMP_FontAsset/Update Atlas Texture...", false, 2000)] + static void RegenerateFontAsset(MenuCommand command) + { + TMP_FontAsset fontAsset = command.context as TMP_FontAsset; + + if (fontAsset != null) + { + TMPro_FontAssetCreatorWindow.ShowFontAtlasCreatorWindow(fontAsset); + } + } + + + /// + /// Clear Font Asset Data + /// + /// + [MenuItem("CONTEXT/TMP_FontAsset/Reset", false, 100)] + static void ClearFontAssetData(MenuCommand command) + { + TMP_FontAsset fontAsset = command.context as TMP_FontAsset; + + if (fontAsset != null && Selection.activeObject != fontAsset) + { + Selection.activeObject = fontAsset; + } + + fontAsset.ClearFontAssetData(true); + + TMPro_EventManager.ON_FONT_PROPERTY_CHANGED(true, fontAsset); + } + + + [MenuItem("CONTEXT/TrueTypeFontImporter/Create TMP Font Asset...", false, 200)] + static void CreateFontAsset(MenuCommand command) + { + TrueTypeFontImporter importer = command.context as TrueTypeFontImporter; + + if (importer != null) + { + Font sourceFontFile = AssetDatabase.LoadAssetAtPath(importer.assetPath); + + if (sourceFontFile) + TMPro_FontAssetCreatorWindow.ShowFontAtlasCreatorWindow(sourceFontFile); + } + } + } +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMPro_CreateObjectMenu.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMPro_CreateObjectMenu.cs new file mode 100644 index 00000000..a7c1cc15 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMPro_CreateObjectMenu.cs @@ -0,0 +1,311 @@ +using UnityEngine; +using UnityEditor; +using UnityEditor.SceneManagement; +using UnityEditor.Experimental.SceneManagement; +using UnityEngine.SceneManagement; +using UnityEngine.UI; +using UnityEngine.EventSystems; + + +namespace TMPro.EditorUtilities +{ + public static class TMPro_CreateObjectMenu + { + + /// + /// Create a TextMeshPro object that works with the Mesh Renderer + /// + /// + [MenuItem("GameObject/3D Object/Text - TextMeshPro", false, 30)] + static void CreateTextMeshProObjectPerform(MenuCommand command) + { + GameObject go = new GameObject("Text (TMP)"); + + // Add support for new prefab mode + StageUtility.PlaceGameObjectInCurrentStage(go); + + TextMeshPro textMeshPro = go.AddComponent(); + textMeshPro.text = "Sample text"; + textMeshPro.alignment = TextAlignmentOptions.TopLeft; + + Undo.RegisterCreatedObjectUndo((Object)go, "Create " + go.name); + + GameObject contextObject = command.context as GameObject; + if (contextObject != null) + { + GameObjectUtility.SetParentAndAlign(go, contextObject); + Undo.SetTransformParent(go.transform, contextObject.transform, "Parent " + go.name); + } + + Selection.activeGameObject = go; + } + + + /// + /// Create a TextMeshPro object that works with the CanvasRenderer + /// + /// + [MenuItem("GameObject/UI/Text - TextMeshPro", false, 2001)] + static void CreateTextMeshProGuiObjectPerform(MenuCommand menuCommand) + { + GameObject go = TMP_DefaultControls.CreateText(GetStandardResources()); + + // Override text color and font size + TMP_Text textComponent = go.GetComponent(); + textComponent.color = Color.white; + if (textComponent.m_isWaitingOnResourceLoad == false) + textComponent.fontSize = TMP_Settings.defaultFontSize; + + PlaceUIElementRoot(go, menuCommand); + } + + [MenuItem("GameObject/UI/Button - TextMeshPro", false, 2031)] + static public void AddButton(MenuCommand menuCommand) + { + GameObject go = TMP_DefaultControls.CreateButton(GetStandardResources()); + + // Override font size + TMP_Text textComponent = go.GetComponentInChildren(); + textComponent.fontSize = 24; + + PlaceUIElementRoot(go, menuCommand); + } + + + + [MenuItem("GameObject/UI/Input Field - TextMeshPro", false, 2037)] + static void AddTextMeshProInputField(MenuCommand menuCommand) + { + GameObject go = TMP_DefaultControls.CreateInputField(GetStandardResources()); + PlaceUIElementRoot(go, menuCommand); + } + + + [MenuItem("GameObject/UI/Dropdown - TextMeshPro", false, 2036)] + static public void AddDropdown(MenuCommand menuCommand) + { + GameObject go = TMP_DefaultControls.CreateDropdown(GetStandardResources()); + PlaceUIElementRoot(go, menuCommand); + } + + + private const string kUILayerName = "UI"; + + private const string kStandardSpritePath = "UI/Skin/UISprite.psd"; + private const string kBackgroundSpritePath = "UI/Skin/Background.psd"; + private const string kInputFieldBackgroundPath = "UI/Skin/InputFieldBackground.psd"; + private const string kKnobPath = "UI/Skin/Knob.psd"; + private const string kCheckmarkPath = "UI/Skin/Checkmark.psd"; + private const string kDropdownArrowPath = "UI/Skin/DropdownArrow.psd"; + private const string kMaskPath = "UI/Skin/UIMask.psd"; + + static private TMP_DefaultControls.Resources s_StandardResources; + + + static private TMP_DefaultControls.Resources GetStandardResources() + { + if (s_StandardResources.standard == null) + { + s_StandardResources.standard = AssetDatabase.GetBuiltinExtraResource(kStandardSpritePath); + s_StandardResources.background = AssetDatabase.GetBuiltinExtraResource(kBackgroundSpritePath); + s_StandardResources.inputField = AssetDatabase.GetBuiltinExtraResource(kInputFieldBackgroundPath); + s_StandardResources.knob = AssetDatabase.GetBuiltinExtraResource(kKnobPath); + s_StandardResources.checkmark = AssetDatabase.GetBuiltinExtraResource(kCheckmarkPath); + s_StandardResources.dropdown = AssetDatabase.GetBuiltinExtraResource(kDropdownArrowPath); + s_StandardResources.mask = AssetDatabase.GetBuiltinExtraResource(kMaskPath); + } + return s_StandardResources; + } + + + private static void SetPositionVisibleinSceneView(RectTransform canvasRTransform, RectTransform itemTransform) + { + // Find the best scene view + SceneView sceneView = SceneView.lastActiveSceneView; + if (sceneView == null && SceneView.sceneViews.Count > 0) + sceneView = SceneView.sceneViews[0] as SceneView; + + // Couldn't find a SceneView. Don't set position. + if (sceneView == null || sceneView.camera == null) + return; + + // Create world space Plane from canvas position. + Camera camera = sceneView.camera; + Vector3 position = Vector3.zero; + if (RectTransformUtility.ScreenPointToLocalPointInRectangle(canvasRTransform, new Vector2(camera.pixelWidth / 2, camera.pixelHeight / 2), camera, out Vector2 localPlanePosition)) + { + // Adjust for canvas pivot + localPlanePosition.x = localPlanePosition.x + canvasRTransform.sizeDelta.x * canvasRTransform.pivot.x; + localPlanePosition.y = localPlanePosition.y + canvasRTransform.sizeDelta.y * canvasRTransform.pivot.y; + + localPlanePosition.x = Mathf.Clamp(localPlanePosition.x, 0, canvasRTransform.sizeDelta.x); + localPlanePosition.y = Mathf.Clamp(localPlanePosition.y, 0, canvasRTransform.sizeDelta.y); + + // Adjust for anchoring + position.x = localPlanePosition.x - canvasRTransform.sizeDelta.x * itemTransform.anchorMin.x; + position.y = localPlanePosition.y - canvasRTransform.sizeDelta.y * itemTransform.anchorMin.y; + + Vector3 minLocalPosition; + minLocalPosition.x = canvasRTransform.sizeDelta.x * (0 - canvasRTransform.pivot.x) + itemTransform.sizeDelta.x * itemTransform.pivot.x; + minLocalPosition.y = canvasRTransform.sizeDelta.y * (0 - canvasRTransform.pivot.y) + itemTransform.sizeDelta.y * itemTransform.pivot.y; + + Vector3 maxLocalPosition; + maxLocalPosition.x = canvasRTransform.sizeDelta.x * (1 - canvasRTransform.pivot.x) - itemTransform.sizeDelta.x * itemTransform.pivot.x; + maxLocalPosition.y = canvasRTransform.sizeDelta.y * (1 - canvasRTransform.pivot.y) - itemTransform.sizeDelta.y * itemTransform.pivot.y; + + position.x = Mathf.Clamp(position.x, minLocalPosition.x, maxLocalPosition.x); + position.y = Mathf.Clamp(position.y, minLocalPosition.y, maxLocalPosition.y); + } + + itemTransform.anchoredPosition = position; + itemTransform.localRotation = Quaternion.identity; + itemTransform.localScale = Vector3.one; + } + + + private static void PlaceUIElementRoot(GameObject element, MenuCommand menuCommand) + { + GameObject parent = menuCommand.context as GameObject; + bool explicitParentChoice = true; + if (parent == null) + { + parent = GetOrCreateCanvasGameObject(); + explicitParentChoice = false; + + // If in Prefab Mode, Canvas has to be part of Prefab contents, + // otherwise use Prefab root instead. + PrefabStage prefabStage = PrefabStageUtility.GetCurrentPrefabStage(); + if (prefabStage != null && !prefabStage.IsPartOfPrefabContents(parent)) + parent = prefabStage.prefabContentsRoot; + } + if (parent.GetComponentInParent() == null) + { + // Create canvas under context GameObject, + // and make that be the parent which UI element is added under. + GameObject canvas = CreateNewUI(); + canvas.transform.SetParent(parent.transform, false); + parent = canvas; + } + + // Setting the element to be a child of an element already in the scene should + // be sufficient to also move the element to that scene. + // However, it seems the element needs to be already in its destination scene when the + // RegisterCreatedObjectUndo is performed; otherwise the scene it was created in is dirtied. + SceneManager.MoveGameObjectToScene(element, parent.scene); + + if (element.transform.parent == null) + { + Undo.SetTransformParent(element.transform, parent.transform, "Parent " + element.name); + } + + GameObjectUtility.EnsureUniqueNameForSibling(element); + + // We have to fix up the undo name since the name of the object was only known after reparenting it. + Undo.SetCurrentGroupName("Create " + element.name); + + GameObjectUtility.SetParentAndAlign(element, parent); + if (!explicitParentChoice) // not a context click, so center in sceneview + SetPositionVisibleinSceneView(parent.GetComponent(), element.GetComponent()); + + Undo.RegisterCreatedObjectUndo(element, "Create " + element.name); + + Selection.activeGameObject = element; + } + + + static public GameObject CreateNewUI() + { + // Root for the UI + var root = new GameObject("Canvas"); + root.layer = LayerMask.NameToLayer(kUILayerName); + Canvas canvas = root.AddComponent(); + canvas.renderMode = RenderMode.ScreenSpaceOverlay; + root.AddComponent(); + root.AddComponent(); + + // Works for all stages. + StageUtility.PlaceGameObjectInCurrentStage(root); + bool customScene = false; + PrefabStage prefabStage = PrefabStageUtility.GetCurrentPrefabStage(); + if (prefabStage != null) + { + root.transform.SetParent(prefabStage.prefabContentsRoot.transform, false); + customScene = true; + } + + Undo.RegisterCreatedObjectUndo(root, "Create " + root.name); + + // If there is no event system add one... + // No need to place event system in custom scene as these are temporary anyway. + // It can be argued for or against placing it in the user scenes, + // but let's not modify scene user is not currently looking at. + if (!customScene) + CreateEventSystem(false); + return root; + } + + + private static void CreateEventSystem(bool select) + { + CreateEventSystem(select, null); + } + + + private static void CreateEventSystem(bool select, GameObject parent) + { + var esys = Object.FindObjectOfType(); + if (esys == null) + { + var eventSystem = new GameObject("EventSystem"); + GameObjectUtility.SetParentAndAlign(eventSystem, parent); + esys = eventSystem.AddComponent(); + eventSystem.AddComponent(); + + Undo.RegisterCreatedObjectUndo(eventSystem, "Create " + eventSystem.name); + } + + if (select && esys != null) + { + Selection.activeGameObject = esys.gameObject; + } + } + + + // Helper function that returns a Canvas GameObject; preferably a parent of the selection, or other existing Canvas. + static public GameObject GetOrCreateCanvasGameObject() + { + GameObject selectedGo = Selection.activeGameObject; + + // Try to find a gameobject that is the selected GO or one if its parents. + Canvas canvas = (selectedGo != null) ? selectedGo.GetComponentInParent() : null; + if (IsValidCanvas(canvas)) + return canvas.gameObject; + + // No canvas in selection or its parents? Then use any valid canvas. + // We have to find all loaded Canvases, not just the ones in main scenes. + Canvas[] canvasArray = StageUtility.GetCurrentStageHandle().FindComponentsOfType(); + for (int i = 0; i < canvasArray.Length; i++) + if (IsValidCanvas(canvasArray[i])) + return canvasArray[i].gameObject; + + // No canvas in the scene at all? Then create a new one. + return CreateNewUI(); + } + + static bool IsValidCanvas(Canvas canvas) + { + if (canvas == null || !canvas.gameObject.activeInHierarchy) + return false; + + // It's important that the non-editable canvas from a prefab scene won't be rejected, + // but canvases not visible in the Hierarchy at all do. Don't check for HideAndDontSave. + if (EditorUtility.IsPersistent(canvas) || (canvas.hideFlags & HideFlags.HideInHierarchy) != 0) + return false; + + if (StageUtility.GetStageHandle(canvas.gameObject) != StageUtility.GetCurrentStageHandle()) + return false; + + return true; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMPro_EditorShaderUtilities.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMPro_EditorShaderUtilities.cs new file mode 100644 index 00000000..3d639005 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMPro_EditorShaderUtilities.cs @@ -0,0 +1,53 @@ +using UnityEngine; +using UnityEditor; +using System.Linq; +using System.Collections; + + +namespace TMPro.EditorUtilities +{ + + public static class EditorShaderUtilities + { + + /// + /// Copy Shader properties from source to destination material. + /// + /// + /// + public static void CopyMaterialProperties(Material source, Material destination) + { + MaterialProperty[] source_prop = MaterialEditor.GetMaterialProperties(new Material[] { source }); + + for (int i = 0; i < source_prop.Length; i++) + { + int property_ID = Shader.PropertyToID(source_prop[i].name); + if (destination.HasProperty(property_ID)) + { + //Debug.Log(source_prop[i].name + " Type:" + ShaderUtil.GetPropertyType(source.shader, i)); + switch (ShaderUtil.GetPropertyType(source.shader, i)) + { + case ShaderUtil.ShaderPropertyType.Color: + destination.SetColor(property_ID, source.GetColor(property_ID)); + break; + case ShaderUtil.ShaderPropertyType.Float: + destination.SetFloat(property_ID, source.GetFloat(property_ID)); + break; + case ShaderUtil.ShaderPropertyType.Range: + destination.SetFloat(property_ID, source.GetFloat(property_ID)); + break; + case ShaderUtil.ShaderPropertyType.TexEnv: + destination.SetTexture(property_ID, source.GetTexture(property_ID)); + break; + case ShaderUtil.ShaderPropertyType.Vector: + destination.SetVector(property_ID, source.GetVector(property_ID)); + break; + } + } + } + + } + + } + +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMPro_FontAssetCreatorWindow.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMPro_FontAssetCreatorWindow.cs new file mode 100644 index 00000000..95be939d --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMPro_FontAssetCreatorWindow.cs @@ -0,0 +1,1736 @@ +using System; +using UnityEngine; +using UnityEditor; +using System.Collections.Generic; +using System.Globalization; +using System.Threading; +using System.IO; +using System.Text.RegularExpressions; +using UnityEngine.TextCore; +using UnityEngine.TextCore.LowLevel; +using Object = UnityEngine.Object; + +namespace TMPro.EditorUtilities +{ + public class TMPro_FontAssetCreatorWindow : EditorWindow + { + [MenuItem("Window/TextMeshPro/Font Asset Creator", false, 2025)] + public static void ShowFontAtlasCreatorWindow() + { + var window = GetWindow(); + window.titleContent = new GUIContent("Font Asset Creator"); + window.Focus(); + + // Make sure TMP Essential Resources have been imported. + window.CheckEssentialResources(); + } + + + public static void ShowFontAtlasCreatorWindow(Font sourceFontFile) + { + var window = GetWindow(); + + window.titleContent = new GUIContent("Font Asset Creator"); + window.Focus(); + + window.ClearGeneratedData(); + window.m_LegacyFontAsset = null; + window.m_SelectedFontAsset = null; + + // Override selected font asset + window.m_SourceFontFile = sourceFontFile; + + // Make sure TMP Essential Resources have been imported. + window.CheckEssentialResources(); + } + + + public static void ShowFontAtlasCreatorWindow(TMP_FontAsset fontAsset) + { + var window = GetWindow(); + + window.titleContent = new GUIContent("Font Asset Creator"); + window.Focus(); + + // Clear any previously generated data + window.ClearGeneratedData(); + window.m_LegacyFontAsset = null; + + // Load font asset creation settings if we have valid settings + if (string.IsNullOrEmpty(fontAsset.creationSettings.sourceFontFileGUID) == false) + { + window.LoadFontCreationSettings(fontAsset.creationSettings); + + // Override settings to inject character list from font asset + window.m_CharacterSetSelectionMode = 6; + window.m_CharacterSequence = TMP_EditorUtility.GetUnicodeCharacterSequence(TMP_FontAsset.GetCharactersArray(fontAsset)); + + + window.m_ReferencedFontAsset = fontAsset; + window.m_SavedFontAtlas = fontAsset.atlasTexture; + } + else + { + window.m_WarningMessage = "Font Asset [" + fontAsset.name + "] does not contain any previous \"Font Asset Creation Settings\". This usually means [" + fontAsset.name + "] was created before this new functionality was added."; + window.m_SourceFontFile = null; + window.m_LegacyFontAsset = fontAsset; + } + + // Even if we don't have any saved generation settings, we still want to pre-select the source font file. + window.m_SelectedFontAsset = fontAsset; + + // Make sure TMP Essential Resources have been imported. + window.CheckEssentialResources(); + } + + [System.Serializable] + class FontAssetCreationSettingsContainer + { + public List fontAssetCreationSettings; + } + + FontAssetCreationSettingsContainer m_FontAssetCreationSettingsContainer; + + //static readonly string[] m_FontCreationPresets = new string[] { "Recent 1", "Recent 2", "Recent 3", "Recent 4" }; + int m_FontAssetCreationSettingsCurrentIndex = 0; + + const string k_FontAssetCreationSettingsContainerKey = "TextMeshPro.FontAssetCreator.RecentFontAssetCreationSettings.Container"; + const string k_FontAssetCreationSettingsCurrentIndexKey = "TextMeshPro.FontAssetCreator.RecentFontAssetCreationSettings.CurrentIndex"; + const float k_TwoColumnControlsWidth = 335f; + + // Diagnostics + System.Diagnostics.Stopwatch m_StopWatch; + double m_GlyphPackingGenerationTime; + double m_GlyphRenderingGenerationTime; + + string[] m_FontSizingOptions = { "Auto Sizing", "Custom Size" }; + int m_PointSizeSamplingMode; + string[] m_FontResolutionLabels = { "8", "16","32", "64", "128", "256", "512", "1024", "2048", "4096", "8192" }; + int[] m_FontAtlasResolutions = { 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192 }; + string[] m_FontCharacterSets = { "ASCII", "Extended ASCII", "ASCII Lowercase", "ASCII Uppercase", "Numbers + Symbols", "Custom Range", "Unicode Range (Hex)", "Custom Characters", "Characters from File" }; + enum FontPackingModes { Fast = 0, Optimum = 4 }; + FontPackingModes m_PackingMode = FontPackingModes.Fast; + + int m_CharacterSetSelectionMode; + + string m_CharacterSequence = ""; + string m_OutputFeedback = ""; + string m_WarningMessage; + int m_CharacterCount; + Vector2 m_ScrollPosition; + Vector2 m_OutputScrollPosition; + + bool m_IsRepaintNeeded; + + float m_AtlasGenerationProgress; + string m_AtlasGenerationProgressLabel = string.Empty; + float m_RenderingProgress; + bool m_IsRenderingDone; + bool m_IsProcessing; + bool m_IsGenerationDisabled; + bool m_IsGenerationCancelled; + + bool m_IsFontAtlasInvalid; + Object m_SourceFontFile; + TMP_FontAsset m_SelectedFontAsset; + TMP_FontAsset m_LegacyFontAsset; + TMP_FontAsset m_ReferencedFontAsset; + + TextAsset m_CharactersFromFile; + int m_PointSize; + int m_Padding = 5; + //FaceStyles m_FontStyle = FaceStyles.Normal; + //float m_FontStyleValue = 2; + + GlyphRenderMode m_GlyphRenderMode = GlyphRenderMode.SDFAA; + int m_AtlasWidth = 512; + int m_AtlasHeight = 512; + byte[] m_AtlasTextureBuffer; + Texture2D m_FontAtlasTexture; + Texture2D m_SavedFontAtlas; + + // + List m_FontGlyphTable = new List(); + List m_FontCharacterTable = new List(); + + Dictionary m_CharacterLookupMap = new Dictionary(); + Dictionary> m_GlyphLookupMap = new Dictionary>(); + + List m_GlyphsToPack = new List(); + List m_GlyphsPacked = new List(); + List m_FreeGlyphRects = new List(); + List m_UsedGlyphRects = new List(); + List m_GlyphsToRender = new List(); + List m_AvailableGlyphsToAdd = new List(); + List m_MissingCharacters = new List(); + List m_ExcludedCharacters = new List(); + + private FaceInfo m_FaceInfo; + + bool m_IncludeFontFeatures; + + + public void OnEnable() + { + // Used for Diagnostics + m_StopWatch = new System.Diagnostics.Stopwatch(); + + // Set Editor window size. + minSize = new Vector2(315, minSize.y); + + // Initialize & Get shader property IDs. + ShaderUtilities.GetShaderPropertyIDs(); + + // Load last selected preset if we are not already in the process of regenerating an existing font asset (via the Context menu) + if (EditorPrefs.HasKey(k_FontAssetCreationSettingsContainerKey)) + { + if (m_FontAssetCreationSettingsContainer == null) + m_FontAssetCreationSettingsContainer = JsonUtility.FromJson(EditorPrefs.GetString(k_FontAssetCreationSettingsContainerKey)); + + if (m_FontAssetCreationSettingsContainer.fontAssetCreationSettings != null && m_FontAssetCreationSettingsContainer.fontAssetCreationSettings.Count > 0) + { + // Load Font Asset Creation Settings preset. + if (EditorPrefs.HasKey(k_FontAssetCreationSettingsCurrentIndexKey)) + m_FontAssetCreationSettingsCurrentIndex = EditorPrefs.GetInt(k_FontAssetCreationSettingsCurrentIndexKey); + + LoadFontCreationSettings(m_FontAssetCreationSettingsContainer.fontAssetCreationSettings[m_FontAssetCreationSettingsCurrentIndex]); + } + } + + ClearGeneratedData(); + } + + + public void OnDisable() + { + //Debug.Log("TextMeshPro Editor Window has been disabled."); + + // Destroy Engine only if it has been initialized already + FontEngine.DestroyFontEngine(); + + ClearGeneratedData(); + + // Remove Glyph Report if one was created. + if (File.Exists("Assets/TextMesh Pro/Glyph Report.txt")) + { + File.Delete("Assets/TextMesh Pro/Glyph Report.txt"); + File.Delete("Assets/TextMesh Pro/Glyph Report.txt.meta"); + + AssetDatabase.Refresh(); + } + + // Save Font Asset Creation Settings Index + SaveCreationSettingsToEditorPrefs(SaveFontCreationSettings()); + EditorPrefs.SetInt(k_FontAssetCreationSettingsCurrentIndexKey, m_FontAssetCreationSettingsCurrentIndex); + + // Unregister to event + TMPro_EventManager.RESOURCE_LOAD_EVENT.Remove(ON_RESOURCES_LOADED); + + Resources.UnloadUnusedAssets(); + } + + + // Event received when TMP resources have been loaded. + void ON_RESOURCES_LOADED() + { + TMPro_EventManager.RESOURCE_LOAD_EVENT.Remove(ON_RESOURCES_LOADED); + + m_IsGenerationDisabled = false; + } + + // Make sure TMP Essential Resources have been imported. + void CheckEssentialResources() + { + if (TMP_Settings.instance == null) + { + if (m_IsGenerationDisabled == false) + TMPro_EventManager.RESOURCE_LOAD_EVENT.Add(ON_RESOURCES_LOADED); + + m_IsGenerationDisabled = true; + } + } + + + public void OnGUI() + { + GUILayout.BeginHorizontal(); + DrawControls(); + if (position.width > position.height && position.width > k_TwoColumnControlsWidth) + { + DrawPreview(); + } + GUILayout.EndHorizontal(); + } + + + public void Update() + { + if (m_IsRepaintNeeded) + { + //Debug.Log("Repainting..."); + m_IsRepaintNeeded = false; + Repaint(); + } + + // Update Progress bar is we are Rendering a Font. + if (m_IsProcessing) + { + m_AtlasGenerationProgress = FontEngine.generationProgress; + + m_IsRepaintNeeded = true; + } + + // Update Feedback Window & Create Font Texture once Rendering is done. + if (m_IsRenderingDone) + { + m_IsProcessing = false; + m_IsRenderingDone = false; + + if (m_IsGenerationCancelled == false) + { + m_AtlasGenerationProgressLabel = "Generation completed in: " + (m_GlyphPackingGenerationTime + m_GlyphRenderingGenerationTime).ToString("0.00 ms."); + + UpdateRenderFeedbackWindow(); + CreateFontAtlasTexture(); + + // If dynamic make readable ... + m_FontAtlasTexture.Apply(false, false); + } + Repaint(); + } + } + + + /// + /// Method which returns the character corresponding to a decimal value. + /// + /// + /// + static uint[] ParseNumberSequence(string sequence) + { + List unicodeList = new List(); + string[] sequences = sequence.Split(','); + + foreach (string seq in sequences) + { + string[] s1 = seq.Split('-'); + + if (s1.Length == 1) + try + { + unicodeList.Add(uint.Parse(s1[0])); + } + catch + { + Debug.Log("No characters selected or invalid format."); + } + else + { + for (uint j = uint.Parse(s1[0]); j < uint.Parse(s1[1]) + 1; j++) + { + unicodeList.Add(j); + } + } + } + + return unicodeList.ToArray(); + } + + + /// + /// Method which returns the character (decimal value) from a hex sequence. + /// + /// + /// + static uint[] ParseHexNumberSequence(string sequence) + { + List unicodeList = new List(); + string[] sequences = sequence.Split(','); + + foreach (string seq in sequences) + { + string[] s1 = seq.Split('-'); + + if (s1.Length == 1) + try + { + unicodeList.Add(uint.Parse(s1[0], NumberStyles.AllowHexSpecifier)); + } + catch + { + Debug.Log("No characters selected or invalid format."); + } + else + { + for (uint j = uint.Parse(s1[0], NumberStyles.AllowHexSpecifier); j < uint.Parse(s1[1], NumberStyles.AllowHexSpecifier) + 1; j++) + { + unicodeList.Add(j); + } + } + } + + return unicodeList.ToArray(); + } + + + void DrawControls() + { + GUILayout.Space(5f); + + if (position.width > position.height && position.width > k_TwoColumnControlsWidth) + { + m_ScrollPosition = EditorGUILayout.BeginScrollView(m_ScrollPosition, GUILayout.Width(315)); + } + else + { + m_ScrollPosition = EditorGUILayout.BeginScrollView(m_ScrollPosition); + } + + GUILayout.Space(5f); + + GUILayout.Label(m_SelectedFontAsset != null ? string.Format("Font Settings [{0}]", m_SelectedFontAsset.name) : "Font Settings", EditorStyles.boldLabel); + + EditorGUILayout.BeginVertical(EditorStyles.helpBox); + + EditorGUIUtility.labelWidth = 125f; + EditorGUIUtility.fieldWidth = 5f; + + // Disable Options if already generating a font atlas texture. + EditorGUI.BeginDisabledGroup(m_IsProcessing); + { + // FONT TTF SELECTION + EditorGUI.BeginChangeCheck(); + m_SourceFontFile = EditorGUILayout.ObjectField("Source Font File", m_SourceFontFile, typeof(Font), false) as Font; + if (EditorGUI.EndChangeCheck()) + { + m_SelectedFontAsset = null; + m_IsFontAtlasInvalid = true; + } + + // FONT SIZING + EditorGUI.BeginChangeCheck(); + if (m_PointSizeSamplingMode == 0) + { + m_PointSizeSamplingMode = EditorGUILayout.Popup("Sampling Point Size", m_PointSizeSamplingMode, m_FontSizingOptions); + } + else + { + GUILayout.BeginHorizontal(); + m_PointSizeSamplingMode = EditorGUILayout.Popup("Sampling Point Size", m_PointSizeSamplingMode, m_FontSizingOptions, GUILayout.Width(225)); + m_PointSize = EditorGUILayout.IntField(m_PointSize); + GUILayout.EndHorizontal(); + } + if (EditorGUI.EndChangeCheck()) + { + m_IsFontAtlasInvalid = true; + } + + // FONT PADDING + EditorGUI.BeginChangeCheck(); + m_Padding = EditorGUILayout.IntField("Padding", m_Padding); + m_Padding = (int)Mathf.Clamp(m_Padding, 0f, 64f); + if (EditorGUI.EndChangeCheck()) + { + m_IsFontAtlasInvalid = true; + } + + // FONT PACKING METHOD SELECTION + EditorGUI.BeginChangeCheck(); + m_PackingMode = (FontPackingModes)EditorGUILayout.EnumPopup("Packing Method", m_PackingMode); + if (EditorGUI.EndChangeCheck()) + { + m_IsFontAtlasInvalid = true; + } + + // FONT ATLAS RESOLUTION SELECTION + GUILayout.BeginHorizontal(); + GUI.changed = false; + + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PrefixLabel("Atlas Resolution"); + m_AtlasWidth = EditorGUILayout.IntPopup(m_AtlasWidth, m_FontResolutionLabels, m_FontAtlasResolutions); + m_AtlasHeight = EditorGUILayout.IntPopup(m_AtlasHeight, m_FontResolutionLabels, m_FontAtlasResolutions); + if (EditorGUI.EndChangeCheck()) + { + m_IsFontAtlasInvalid = true; + } + + GUILayout.EndHorizontal(); + + + // FONT CHARACTER SET SELECTION + EditorGUI.BeginChangeCheck(); + bool hasSelectionChanged = false; + m_CharacterSetSelectionMode = EditorGUILayout.Popup("Character Set", m_CharacterSetSelectionMode, m_FontCharacterSets); + if (EditorGUI.EndChangeCheck()) + { + m_CharacterSequence = ""; + hasSelectionChanged = true; + m_IsFontAtlasInvalid = true; + } + + switch (m_CharacterSetSelectionMode) + { + case 0: // ASCII + //characterSequence = "32 - 126, 130, 132 - 135, 139, 145 - 151, 153, 155, 161, 166 - 167, 169 - 174, 176, 181 - 183, 186 - 187, 191, 8210 - 8226, 8230, 8240, 8242 - 8244, 8249 - 8250, 8252 - 8254, 8260, 8286"; + m_CharacterSequence = "32 - 126, 160, 8203, 8230, 9633"; + break; + + case 1: // EXTENDED ASCII + m_CharacterSequence = "32 - 126, 160 - 255, 8192 - 8303, 8364, 8482, 9633"; + // Could add 9632 for missing glyph + break; + + case 2: // Lowercase + m_CharacterSequence = "32 - 64, 91 - 126, 160"; + break; + + case 3: // Uppercase + m_CharacterSequence = "32 - 96, 123 - 126, 160"; + break; + + case 4: // Numbers & Symbols + m_CharacterSequence = "32 - 64, 91 - 96, 123 - 126, 160"; + break; + + case 5: // Custom Range + EditorGUILayout.BeginVertical(EditorStyles.helpBox); + GUILayout.Label("Enter a sequence of decimal values to define the characters to be included in the font asset or retrieve one from another font asset.", TMP_UIStyleManager.label); + GUILayout.Space(10f); + + EditorGUI.BeginChangeCheck(); + m_ReferencedFontAsset = EditorGUILayout.ObjectField("Select Font Asset", m_ReferencedFontAsset, typeof(TMP_FontAsset), false) as TMP_FontAsset; + if (EditorGUI.EndChangeCheck() || hasSelectionChanged) + { + if (m_ReferencedFontAsset != null) + m_CharacterSequence = TMP_EditorUtility.GetDecimalCharacterSequence(TMP_FontAsset.GetCharactersArray(m_ReferencedFontAsset)); + + m_IsFontAtlasInvalid = true; + } + + // Filter out unwanted characters. + char chr = Event.current.character; + if ((chr < '0' || chr > '9') && (chr < ',' || chr > '-')) + { + Event.current.character = '\0'; + } + GUILayout.Label("Character Sequence (Decimal)", EditorStyles.boldLabel); + EditorGUI.BeginChangeCheck(); + m_CharacterSequence = EditorGUILayout.TextArea(m_CharacterSequence, TMP_UIStyleManager.textAreaBoxWindow, GUILayout.Height(120), GUILayout.ExpandWidth(true)); + if (EditorGUI.EndChangeCheck()) + { + m_IsFontAtlasInvalid = true; + } + + EditorGUILayout.EndVertical(); + break; + + case 6: // Unicode HEX Range + EditorGUILayout.BeginVertical(EditorStyles.helpBox); + GUILayout.Label("Enter a sequence of Unicode (hex) values to define the characters to be included in the font asset or retrieve one from another font asset.", TMP_UIStyleManager.label); + GUILayout.Space(10f); + + EditorGUI.BeginChangeCheck(); + m_ReferencedFontAsset = EditorGUILayout.ObjectField("Select Font Asset", m_ReferencedFontAsset, typeof(TMP_FontAsset), false) as TMP_FontAsset; + if (EditorGUI.EndChangeCheck() || hasSelectionChanged) + { + if (m_ReferencedFontAsset != null) + m_CharacterSequence = TMP_EditorUtility.GetUnicodeCharacterSequence(TMP_FontAsset.GetCharactersArray(m_ReferencedFontAsset)); + + m_IsFontAtlasInvalid = true; + } + + // Filter out unwanted characters. + chr = Event.current.character; + if ((chr < '0' || chr > '9') && (chr < 'a' || chr > 'f') && (chr < 'A' || chr > 'F') && (chr < ',' || chr > '-')) + { + Event.current.character = '\0'; + } + GUILayout.Label("Character Sequence (Hex)", EditorStyles.boldLabel); + EditorGUI.BeginChangeCheck(); + m_CharacterSequence = EditorGUILayout.TextArea(m_CharacterSequence, TMP_UIStyleManager.textAreaBoxWindow, GUILayout.Height(120), GUILayout.ExpandWidth(true)); + if (EditorGUI.EndChangeCheck()) + { + m_IsFontAtlasInvalid = true; + } + + EditorGUILayout.EndVertical(); + break; + + case 7: // Characters from Font Asset + EditorGUILayout.BeginVertical(EditorStyles.helpBox); + GUILayout.Label("Type the characters to be included in the font asset or retrieve them from another font asset.", TMP_UIStyleManager.label); + GUILayout.Space(10f); + + EditorGUI.BeginChangeCheck(); + m_ReferencedFontAsset = EditorGUILayout.ObjectField("Select Font Asset", m_ReferencedFontAsset, typeof(TMP_FontAsset), false) as TMP_FontAsset; + if (EditorGUI.EndChangeCheck() || hasSelectionChanged) + { + if (m_ReferencedFontAsset != null) + m_CharacterSequence = TMP_FontAsset.GetCharacters(m_ReferencedFontAsset); + + m_IsFontAtlasInvalid = true; + } + + EditorGUI.indentLevel = 0; + + GUILayout.Label("Custom Character List", EditorStyles.boldLabel); + EditorGUI.BeginChangeCheck(); + m_CharacterSequence = EditorGUILayout.TextArea(m_CharacterSequence, TMP_UIStyleManager.textAreaBoxWindow, GUILayout.Height(120), GUILayout.ExpandWidth(true)); + if (EditorGUI.EndChangeCheck()) + { + m_IsFontAtlasInvalid = true; + } + EditorGUILayout.EndVertical(); + break; + + case 8: // Character List from File + EditorGUI.BeginChangeCheck(); + m_CharactersFromFile = EditorGUILayout.ObjectField("Character File", m_CharactersFromFile, typeof(TextAsset), false) as TextAsset; + if (EditorGUI.EndChangeCheck()) + { + m_IsFontAtlasInvalid = true; + } + + if (m_CharactersFromFile != null) + { + Regex rx = new Regex(@"(? + { + if (match.Value.StartsWith("\\U")) + return char.ConvertFromUtf32(int.Parse(match.Value.Replace("\\U", ""), NumberStyles.HexNumber)); + + return char.ConvertFromUtf32(int.Parse(match.Value.Replace("\\u", ""), NumberStyles.HexNumber)); + }); + } + break; + } + + // FONT STYLE SELECTION + //GUILayout.BeginHorizontal(); + //EditorGUI.BeginChangeCheck(); + ////m_FontStyle = (FaceStyles)EditorGUILayout.EnumPopup("Font Style", m_FontStyle, GUILayout.Width(225)); + ////m_FontStyleValue = EditorGUILayout.IntField((int)m_FontStyleValue); + //if (EditorGUI.EndChangeCheck()) + //{ + // m_IsFontAtlasInvalid = true; + //} + //GUILayout.EndHorizontal(); + + // Render Mode Selection + CheckForLegacyGlyphRenderMode(); + + EditorGUI.BeginChangeCheck(); + m_GlyphRenderMode = (GlyphRenderMode)EditorGUILayout.EnumPopup("Render Mode", m_GlyphRenderMode); + if (EditorGUI.EndChangeCheck()) + { + m_IsFontAtlasInvalid = true; + } + + m_IncludeFontFeatures = EditorGUILayout.Toggle("Get Kerning Pairs", m_IncludeFontFeatures); + + EditorGUILayout.Space(); + } + + EditorGUI.EndDisabledGroup(); + + if (!string.IsNullOrEmpty(m_WarningMessage)) + { + EditorGUILayout.HelpBox(m_WarningMessage, MessageType.Warning); + } + + GUI.enabled = m_SourceFontFile != null && !m_IsProcessing && !m_IsGenerationDisabled; // Enable Preview if we are not already rendering a font. + if (GUILayout.Button("Generate Font Atlas") && GUI.enabled) + { + if (!m_IsProcessing && m_SourceFontFile != null) + { + DestroyImmediate(m_FontAtlasTexture); + m_FontAtlasTexture = null; + m_SavedFontAtlas = null; + + // Initialize font engine + FontEngineError errorCode = FontEngine.InitializeFontEngine(); + if (errorCode != FontEngineError.Success) + { + Debug.Log("Font Asset Creator - Error [" + errorCode + "] has occurred while Initializing the FreeType Library."); + } + + // Get file path of the source font file. + string fontPath = AssetDatabase.GetAssetPath(m_SourceFontFile); + + if (errorCode == FontEngineError.Success) + { + errorCode = FontEngine.LoadFontFace(fontPath); + + if (errorCode != FontEngineError.Success) + { + Debug.Log("Font Asset Creator - Error Code [" + errorCode + "] has occurred trying to load the [" + m_SourceFontFile.name + "] font file. This typically results from the use of an incompatible or corrupted font file."); + } + } + + + // Define an array containing the characters we will render. + if (errorCode == FontEngineError.Success) + { + uint[] characterSet = null; + + // Get list of characters that need to be packed and rendered to the atlas texture. + if (m_CharacterSetSelectionMode == 7 || m_CharacterSetSelectionMode == 8) + { + List char_List = new List(); + + for (int i = 0; i < m_CharacterSequence.Length; i++) + { + uint unicode = m_CharacterSequence[i]; + + // Handle surrogate pairs + if (i < m_CharacterSequence.Length - 1 && char.IsHighSurrogate((char)unicode) && char.IsLowSurrogate(m_CharacterSequence[i + 1])) + { + unicode = (uint)char.ConvertToUtf32(m_CharacterSequence[i], m_CharacterSequence[i + 1]); + i += 1; + } + + // Check to make sure we don't include duplicates + if (char_List.FindIndex(item => item == unicode) == -1) + char_List.Add(unicode); + } + + characterSet = char_List.ToArray(); + } + else if (m_CharacterSetSelectionMode == 6) + { + characterSet = ParseHexNumberSequence(m_CharacterSequence); + } + else + { + characterSet = ParseNumberSequence(m_CharacterSequence); + } + + m_CharacterCount = characterSet.Length; + + m_AtlasGenerationProgress = 0; + m_IsProcessing = true; + m_IsGenerationCancelled = false; + + GlyphLoadFlags glyphLoadFlags = ((GlyphRasterModes)m_GlyphRenderMode & GlyphRasterModes.RASTER_MODE_HINTED) == GlyphRasterModes.RASTER_MODE_HINTED ? GlyphLoadFlags.LOAD_RENDER : GlyphLoadFlags.LOAD_RENDER | GlyphLoadFlags.LOAD_NO_HINTING; + + // + AutoResetEvent autoEvent = new AutoResetEvent(false); + + // Worker thread to pack glyphs in the given texture space. + ThreadPool.QueueUserWorkItem(PackGlyphs => + { + // Start Stop Watch + m_StopWatch = System.Diagnostics.Stopwatch.StartNew(); + + // Clear the various lists used in the generation process. + m_AvailableGlyphsToAdd.Clear(); + m_MissingCharacters.Clear(); + m_ExcludedCharacters.Clear(); + m_CharacterLookupMap.Clear(); + m_GlyphLookupMap.Clear(); + m_GlyphsToPack.Clear(); + m_GlyphsPacked.Clear(); + + // Check if requested characters are available in the source font file. + for (int i = 0; i < characterSet.Length; i++) + { + uint unicode = characterSet[i]; + + if (FontEngine.TryGetGlyphIndex(unicode, out uint glyphIndex)) + { + // Skip over potential duplicate characters. + if (m_CharacterLookupMap.ContainsKey(unicode)) + continue; + + // Add character to character lookup map. + m_CharacterLookupMap.Add(unicode, glyphIndex); + + // Skip over potential duplicate glyph references. + if (m_GlyphLookupMap.ContainsKey(glyphIndex)) + { + // Add additional glyph reference for this character. + m_GlyphLookupMap[glyphIndex].Add(unicode); + continue; + } + + // Add glyph reference to glyph lookup map. + m_GlyphLookupMap.Add(glyphIndex, new List() { unicode }); + + // Add glyph index to list of glyphs to add to texture. + m_AvailableGlyphsToAdd.Add(glyphIndex); + } + else + { + // Add Unicode to list of missing characters. + m_MissingCharacters.Add(unicode); + } + } + + // Pack available glyphs in the provided texture space. + if (m_AvailableGlyphsToAdd.Count > 0) + { + int packingModifier = ((GlyphRasterModes)m_GlyphRenderMode & GlyphRasterModes.RASTER_MODE_BITMAP) == GlyphRasterModes.RASTER_MODE_BITMAP ? 0 : 1; + + if (m_PointSizeSamplingMode == 0) // Auto-Sizing Point Size Mode + { + // Estimate min / max range for auto sizing of point size. + int minPointSize = 0; + int maxPointSize = (int)Mathf.Sqrt((m_AtlasWidth * m_AtlasHeight) / m_AvailableGlyphsToAdd.Count) * 3; + + m_PointSize = (maxPointSize + minPointSize) / 2; + + bool optimumPointSizeFound = false; + for (int iteration = 0; iteration < 15 && optimumPointSizeFound == false; iteration++) + { + m_AtlasGenerationProgressLabel = "Packing glyphs - Pass (" + iteration + ")"; + + FontEngine.SetFaceSize(m_PointSize); + + m_GlyphsToPack.Clear(); + m_GlyphsPacked.Clear(); + + m_FreeGlyphRects.Clear(); + m_FreeGlyphRects.Add(new GlyphRect(0, 0, m_AtlasWidth - packingModifier, m_AtlasHeight - packingModifier)); + m_UsedGlyphRects.Clear(); + + for (int i = 0; i < m_AvailableGlyphsToAdd.Count; i++) + { + uint glyphIndex = m_AvailableGlyphsToAdd[i]; + + if (FontEngine.TryGetGlyphWithIndexValue(glyphIndex, glyphLoadFlags, out Glyph glyph)) + { + if (glyph.glyphRect.width > 0 && glyph.glyphRect.height > 0) + { + m_GlyphsToPack.Add(glyph); + } + else + { + m_GlyphsPacked.Add(glyph); + } + } + } + + FontEngine.TryPackGlyphsInAtlas(m_GlyphsToPack, m_GlyphsPacked, m_Padding, (GlyphPackingMode)m_PackingMode, m_GlyphRenderMode, m_AtlasWidth, m_AtlasHeight, m_FreeGlyphRects, m_UsedGlyphRects); + + if (m_IsGenerationCancelled) + { + DestroyImmediate(m_FontAtlasTexture); + m_FontAtlasTexture = null; + return; + } + + //Debug.Log("Glyphs remaining to add [" + m_GlyphsToAdd.Count + "]. Glyphs added [" + m_GlyphsAdded.Count + "]."); + + if (m_GlyphsToPack.Count > 0) + { + if (m_PointSize > minPointSize) + { + maxPointSize = m_PointSize; + m_PointSize = (m_PointSize + minPointSize) / 2; + + //Debug.Log("Decreasing point size from [" + maxPointSize + "] to [" + m_PointSize + "]."); + } + } + else + { + if (maxPointSize - minPointSize > 1 && m_PointSize < maxPointSize) + { + minPointSize = m_PointSize; + m_PointSize = (m_PointSize + maxPointSize) / 2; + + //Debug.Log("Increasing point size from [" + minPointSize + "] to [" + m_PointSize + "]."); + } + else + { + //Debug.Log("[" + iteration + "] iterations to find the optimum point size of : [" + m_PointSize + "]."); + optimumPointSizeFound = true; + } + } + } + } + else // Custom Point Size Mode + { + m_AtlasGenerationProgressLabel = "Packing glyphs..."; + + // Set point size + FontEngine.SetFaceSize(m_PointSize); + + m_GlyphsToPack.Clear(); + m_GlyphsPacked.Clear(); + + m_FreeGlyphRects.Clear(); + m_FreeGlyphRects.Add(new GlyphRect(0, 0, m_AtlasWidth - packingModifier, m_AtlasHeight - packingModifier)); + m_UsedGlyphRects.Clear(); + + for (int i = 0; i < m_AvailableGlyphsToAdd.Count; i++) + { + uint glyphIndex = m_AvailableGlyphsToAdd[i]; + + if (FontEngine.TryGetGlyphWithIndexValue(glyphIndex, glyphLoadFlags, out Glyph glyph)) + { + if (glyph.glyphRect.width > 0 && glyph.glyphRect.height > 0) + { + m_GlyphsToPack.Add(glyph); + } + else + { + m_GlyphsPacked.Add(glyph); + } + } + } + + FontEngine.TryPackGlyphsInAtlas(m_GlyphsToPack, m_GlyphsPacked, m_Padding, (GlyphPackingMode)m_PackingMode, m_GlyphRenderMode, m_AtlasWidth, m_AtlasHeight, m_FreeGlyphRects, m_UsedGlyphRects); + + if (m_IsGenerationCancelled) + { + DestroyImmediate(m_FontAtlasTexture); + m_FontAtlasTexture = null; + return; + } + //Debug.Log("Glyphs remaining to add [" + m_GlyphsToAdd.Count + "]. Glyphs added [" + m_GlyphsAdded.Count + "]."); + } + + } + else + { + int packingModifier = ((GlyphRasterModes)m_GlyphRenderMode & GlyphRasterModes.RASTER_MODE_BITMAP) == GlyphRasterModes.RASTER_MODE_BITMAP ? 0 : 1; + + FontEngine.SetFaceSize(m_PointSize); + + m_GlyphsToPack.Clear(); + m_GlyphsPacked.Clear(); + + m_FreeGlyphRects.Clear(); + m_FreeGlyphRects.Add(new GlyphRect(0, 0, m_AtlasWidth - packingModifier, m_AtlasHeight - packingModifier)); + m_UsedGlyphRects.Clear(); + } + + //Stop StopWatch + m_StopWatch.Stop(); + m_GlyphPackingGenerationTime = m_StopWatch.Elapsed.TotalMilliseconds; + Debug.Log("Glyph packing completed in: " + m_GlyphPackingGenerationTime.ToString("0.000 ms.")); + m_StopWatch.Reset(); + + m_FontCharacterTable.Clear(); + m_FontGlyphTable.Clear(); + m_GlyphsToRender.Clear(); + + // Add glyphs and characters successfully added to texture to their respective font tables. + foreach (Glyph glyph in m_GlyphsPacked) + { + uint glyphIndex = glyph.index; + + m_FontGlyphTable.Add(glyph); + + // Add glyphs to list of glyphs that need to be rendered. + if (glyph.glyphRect.width > 0 && glyph.glyphRect.height > 0) + m_GlyphsToRender.Add(glyph); + + foreach (uint unicode in m_GlyphLookupMap[glyphIndex]) + { + // Create new Character + m_FontCharacterTable.Add(new TMP_Character(unicode, glyph)); + } + } + + // + foreach (Glyph glyph in m_GlyphsToPack) + { + foreach (uint unicode in m_GlyphLookupMap[glyph.index]) + { + m_ExcludedCharacters.Add(unicode); + } + } + + // Get the face info for the current sampling point size. + m_FaceInfo = FontEngine.GetFaceInfo(); + + autoEvent.Set(); + }); + + // Worker thread to render glyphs in texture buffer. + ThreadPool.QueueUserWorkItem(RenderGlyphs => + { + autoEvent.WaitOne(); + + // Start Stop Watch + m_StopWatch = System.Diagnostics.Stopwatch.StartNew(); + + m_IsRenderingDone = false; + + // Allocate texture data + m_AtlasTextureBuffer = new byte[m_AtlasWidth * m_AtlasHeight]; + + m_AtlasGenerationProgressLabel = "Rendering glyphs..."; + + // Render and add glyphs to the given atlas texture. + if (m_GlyphsToRender.Count > 0) + { + FontEngine.RenderGlyphsToTexture(m_GlyphsToRender, m_Padding, m_GlyphRenderMode, m_AtlasTextureBuffer, m_AtlasWidth, m_AtlasHeight); + } + + m_IsRenderingDone = true; + + // Stop StopWatch + m_StopWatch.Stop(); + m_GlyphRenderingGenerationTime = m_StopWatch.Elapsed.TotalMilliseconds; + Debug.Log("Font Atlas generation completed in: " + m_GlyphRenderingGenerationTime.ToString("0.000 ms.")); + m_StopWatch.Reset(); + }); + } + + SaveCreationSettingsToEditorPrefs(SaveFontCreationSettings()); + } + } + + // FONT RENDERING PROGRESS BAR + GUILayout.Space(1); + Rect progressRect = EditorGUILayout.GetControlRect(false, 20); + + GUI.enabled = true; + progressRect.width -= 22; + EditorGUI.ProgressBar(progressRect, Mathf.Max(0.01f, m_AtlasGenerationProgress), m_AtlasGenerationProgressLabel); + progressRect.x = progressRect.x + progressRect.width + 2; + progressRect.y -= 1; + progressRect.width = 20; + progressRect.height = 20; + + GUI.enabled = m_IsProcessing; + if (GUI.Button(progressRect, "X")) + { + FontEngine.SendCancellationRequest(); + m_AtlasGenerationProgress = 0; + m_IsProcessing = false; + m_IsGenerationCancelled = true; + } + GUILayout.Space(5); + + // FONT STATUS & INFORMATION + GUI.enabled = true; + + GUILayout.BeginVertical(EditorStyles.helpBox, GUILayout.Height(200)); + m_OutputScrollPosition = EditorGUILayout.BeginScrollView(m_OutputScrollPosition); + EditorGUILayout.LabelField(m_OutputFeedback, TMP_UIStyleManager.label); + EditorGUILayout.EndScrollView(); + GUILayout.EndVertical(); + + // SAVE TEXTURE & CREATE and SAVE FONT XML FILE + GUI.enabled = m_FontAtlasTexture != null && !m_IsProcessing; // Enable Save Button if font_Atlas is not Null. + + EditorGUILayout.BeginHorizontal(); + + if (GUILayout.Button("Save") && GUI.enabled) + { + if (m_SelectedFontAsset == null) + { + if (m_LegacyFontAsset != null) + SaveNewFontAssetWithSameName(m_LegacyFontAsset); + else + SaveNewFontAsset(m_SourceFontFile); + } + else + { + // Save over exiting Font Asset + string filePath = Path.GetFullPath(AssetDatabase.GetAssetPath(m_SelectedFontAsset)).Replace('\\', '/'); + + if (((GlyphRasterModes)m_GlyphRenderMode & GlyphRasterModes.RASTER_MODE_BITMAP) == GlyphRasterModes.RASTER_MODE_BITMAP) + Save_Bitmap_FontAsset(filePath); + else + Save_SDF_FontAsset(filePath); + } + } + if (GUILayout.Button("Save as...") && GUI.enabled) + { + if (m_SelectedFontAsset == null) + { + SaveNewFontAsset(m_SourceFontFile); + } + else + { + SaveNewFontAssetWithSameName(m_SelectedFontAsset); + } + } + + EditorGUILayout.EndHorizontal(); + + EditorGUILayout.Space(); + + EditorGUILayout.EndVertical(); + + GUI.enabled = true; // Re-enable GUI + + if (position.height > position.width || position.width < k_TwoColumnControlsWidth) + { + DrawPreview(); + GUILayout.Space(5); + } + + EditorGUILayout.EndScrollView(); + + if (m_IsFontAtlasInvalid) + ClearGeneratedData(); + } + + + /// + /// Clear the previously generated data. + /// + void ClearGeneratedData() + { + m_IsFontAtlasInvalid = false; + + if (m_FontAtlasTexture != null && !EditorUtility.IsPersistent(m_FontAtlasTexture)) + { + DestroyImmediate(m_FontAtlasTexture); + m_FontAtlasTexture = null; + } + + m_AtlasGenerationProgressLabel = string.Empty; + m_AtlasGenerationProgress = 0; + m_SavedFontAtlas = null; + + m_OutputFeedback = string.Empty; + m_WarningMessage = string.Empty; + } + + + /// + /// Function to update the feedback window showing the results of the latest generation. + /// + void UpdateRenderFeedbackWindow() + { + m_PointSize = m_FaceInfo.pointSize; + + string missingGlyphReport = string.Empty; + + //string colorTag = m_FontCharacterTable.Count == m_CharacterCount ? "" : ""; + string colorTag2 = ""; + + missingGlyphReport = "Font: " + colorTag2 + m_FaceInfo.familyName + " Style: " + colorTag2 + m_FaceInfo.styleName + ""; + + missingGlyphReport += "\nPoint Size: " + colorTag2 + m_FaceInfo.pointSize + " SP/PD Ratio: " + colorTag2 + ((float)m_Padding / m_FaceInfo.pointSize).ToString("0.0%" + ""); + + missingGlyphReport += "\n\nCharacters included: " + m_FontCharacterTable.Count + "/" + m_CharacterCount + ""; + missingGlyphReport += "\nMissing characters: " + m_MissingCharacters.Count + ""; + missingGlyphReport += "\nExcluded characters: " + m_ExcludedCharacters.Count + ""; + + // Report characters missing from font file + missingGlyphReport += "\n\nCharacters missing from font file:"; + missingGlyphReport += "\n----------------------------------------"; + + m_OutputFeedback = missingGlyphReport; + + for (int i = 0; i < m_MissingCharacters.Count; i++) + { + missingGlyphReport += "\nID: " + m_MissingCharacters[i] + "\tHex: " + m_MissingCharacters[i].ToString("X") + "\tChar [" + (char)m_MissingCharacters[i] + "]"; + + if (missingGlyphReport.Length < 16300) + m_OutputFeedback = missingGlyphReport; + } + + // Report characters that did not fit in the atlas texture + missingGlyphReport += "\n\nCharacters excluded from packing:"; + missingGlyphReport += "\n----------------------------------------"; + + for (int i = 0; i < m_ExcludedCharacters.Count; i++) + { + missingGlyphReport += "\nID: " + m_ExcludedCharacters[i] + "\tHex: " + m_ExcludedCharacters[i].ToString("X") + "\tChar [" + (char)m_ExcludedCharacters[i] + "]"; + + if (missingGlyphReport.Length < 16300) + m_OutputFeedback = missingGlyphReport; + } + + if (missingGlyphReport.Length > 16300) + m_OutputFeedback += "\n\nReport truncated.\nSee \"TextMesh Pro\\Glyph Report.txt\""; + + // Save Missing Glyph Report file + if (Directory.Exists("Assets/TextMesh Pro")) + { + missingGlyphReport = System.Text.RegularExpressions.Regex.Replace(missingGlyphReport, @"<[^>]*>", string.Empty); + File.WriteAllText("Assets/TextMesh Pro/Glyph Report.txt", missingGlyphReport); + AssetDatabase.Refresh(); + } + } + + + void CreateFontAtlasTexture() + { + if (m_FontAtlasTexture != null) + DestroyImmediate(m_FontAtlasTexture); + + m_FontAtlasTexture = new Texture2D(m_AtlasWidth, m_AtlasHeight, TextureFormat.Alpha8, false, true); + + Color32[] colors = new Color32[m_AtlasWidth * m_AtlasHeight]; + + for (int i = 0; i < colors.Length; i++) + { + byte c = m_AtlasTextureBuffer[i]; + colors[i] = new Color32(c, c, c, c); + } + + // Clear allocation of + m_AtlasTextureBuffer = null; + + if ((m_GlyphRenderMode & GlyphRenderMode.RASTER) == GlyphRenderMode.RASTER || (m_GlyphRenderMode & GlyphRenderMode.RASTER_HINTED) == GlyphRenderMode.RASTER_HINTED) + m_FontAtlasTexture.filterMode = FilterMode.Point; + + m_FontAtlasTexture.SetPixels32(colors, 0); + m_FontAtlasTexture.Apply(false, false); + + // Saving File for Debug + //var pngData = m_FontAtlasTexture.EncodeToPNG(); + //File.WriteAllBytes("Assets/Textures/Debug Font Texture.png", pngData); + } + + + /// + /// Open Save Dialog to provide the option save the font asset using the name of the source font file. This also appends SDF to the name if using any of the SDF Font Asset creation modes. + /// + /// + void SaveNewFontAsset(Object sourceObject) + { + string filePath; + + // Save new Font Asset and open save file requester at Source Font File location. + string saveDirectory = new FileInfo(AssetDatabase.GetAssetPath(sourceObject)).DirectoryName; + + if (((GlyphRasterModes)m_GlyphRenderMode & GlyphRasterModes.RASTER_MODE_BITMAP) == GlyphRasterModes.RASTER_MODE_BITMAP) + { + filePath = EditorUtility.SaveFilePanel("Save TextMesh Pro! Font Asset File", saveDirectory, sourceObject.name, "asset"); + + if (filePath.Length == 0) + return; + + Save_Bitmap_FontAsset(filePath); + } + else + { + filePath = EditorUtility.SaveFilePanel("Save TextMesh Pro! Font Asset File", saveDirectory, sourceObject.name + " SDF", "asset"); + + if (filePath.Length == 0) + return; + + Save_SDF_FontAsset(filePath); + } + } + + + /// + /// Open Save Dialog to provide the option to save the font asset under the same name. + /// + /// + void SaveNewFontAssetWithSameName(Object sourceObject) + { + string filePath; + + // Save new Font Asset and open save file requester at Source Font File location. + string saveDirectory = new FileInfo(AssetDatabase.GetAssetPath(sourceObject)).DirectoryName; + + filePath = EditorUtility.SaveFilePanel("Save TextMesh Pro! Font Asset File", saveDirectory, sourceObject.name, "asset"); + + if (filePath.Length == 0) + return; + + if (((GlyphRasterModes)m_GlyphRenderMode & GlyphRasterModes.RASTER_MODE_BITMAP) == GlyphRasterModes.RASTER_MODE_BITMAP) + { + Save_Bitmap_FontAsset(filePath); + } + else + { + Save_SDF_FontAsset(filePath); + } + } + + + void Save_Bitmap_FontAsset(string filePath) + { + filePath = filePath.Substring(0, filePath.Length - 6); // Trim file extension from filePath. + + string dataPath = Application.dataPath; + + if (filePath.IndexOf(dataPath, System.StringComparison.InvariantCultureIgnoreCase) == -1) + { + Debug.LogError("You're saving the font asset in a directory outside of this project folder. This is not supported. Please select a directory under \"" + dataPath + "\""); + return; + } + + string relativeAssetPath = filePath.Substring(dataPath.Length - 6); + string tex_DirName = Path.GetDirectoryName(relativeAssetPath); + string tex_FileName = Path.GetFileNameWithoutExtension(relativeAssetPath); + string tex_Path_NoExt = tex_DirName + "/" + tex_FileName; + + // Check if TextMeshPro font asset already exists. If not, create a new one. Otherwise update the existing one. + TMP_FontAsset fontAsset = AssetDatabase.LoadAssetAtPath(tex_Path_NoExt + ".asset", typeof(TMP_FontAsset)) as TMP_FontAsset; + if (fontAsset == null) + { + //Debug.Log("Creating TextMeshPro font asset!"); + fontAsset = ScriptableObject.CreateInstance(); // Create new TextMeshPro Font Asset. + AssetDatabase.CreateAsset(fontAsset, tex_Path_NoExt + ".asset"); + + // Set version number of font asset + fontAsset.version = "1.1.0"; + + //Set Font Asset Type + fontAsset.atlasRenderMode = m_GlyphRenderMode; + + // Reference to the source font file GUID. + fontAsset.m_SourceFontFileGUID = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(m_SourceFontFile)); + + // Add FaceInfo to Font Asset + fontAsset.faceInfo = m_FaceInfo; + + // Add GlyphInfo[] to Font Asset + fontAsset.glyphTable = m_FontGlyphTable; + + // Add CharacterTable[] to font asset. + fontAsset.characterTable = m_FontCharacterTable; + + // Sort glyph and character tables. + fontAsset.SortGlyphAndCharacterTables(); + + // Get and Add Kerning Pairs to Font Asset + if (m_IncludeFontFeatures) + fontAsset.fontFeatureTable = GetKerningTable(); + + + // Add Font Atlas as Sub-Asset + fontAsset.atlasTextures = new Texture2D[] { m_FontAtlasTexture }; + m_FontAtlasTexture.name = tex_FileName + " Atlas"; + fontAsset.atlasWidth = m_AtlasWidth; + fontAsset.atlasHeight = m_AtlasHeight; + fontAsset.atlasPadding = m_Padding; + + AssetDatabase.AddObjectToAsset(m_FontAtlasTexture, fontAsset); + + // Create new Material and Add it as Sub-Asset + Shader default_Shader = Shader.Find("TextMeshPro/Bitmap"); // m_shaderSelection; + Material tmp_material = new Material(default_Shader); + tmp_material.name = tex_FileName + " Material"; + tmp_material.SetTexture(ShaderUtilities.ID_MainTex, m_FontAtlasTexture); + fontAsset.material = tmp_material; + + AssetDatabase.AddObjectToAsset(tmp_material, fontAsset); + + } + else + { + // Find all Materials referencing this font atlas. + Material[] material_references = TMP_EditorUtility.FindMaterialReferences(fontAsset); + + // Set version number of font asset + fontAsset.version = "1.1.0"; + + // Special handling to remove legacy font asset data + if (fontAsset.m_glyphInfoList != null && fontAsset.m_glyphInfoList.Count > 0) + fontAsset.m_glyphInfoList = null; + + // Destroy Assets that will be replaced. + if (fontAsset.atlasTextures != null && fontAsset.atlasTextures.Length > 0) + DestroyImmediate(fontAsset.atlasTextures[0], true); + + //Set Font Asset Type + fontAsset.atlasRenderMode = m_GlyphRenderMode; + + // Add FaceInfo to Font Asset + fontAsset.faceInfo = m_FaceInfo; + + // Add GlyphInfo[] to Font Asset + fontAsset.glyphTable = m_FontGlyphTable; + + // Add CharacterTable[] to font asset. + fontAsset.characterTable = m_FontCharacterTable; + + // Sort glyph and character tables. + fontAsset.SortGlyphAndCharacterTables(); + + // Get and Add Kerning Pairs to Font Asset + if (m_IncludeFontFeatures) + fontAsset.fontFeatureTable = GetKerningTable(); + + // Add Font Atlas as Sub-Asset + fontAsset.atlasTextures = new Texture2D[] { m_FontAtlasTexture }; + m_FontAtlasTexture.name = tex_FileName + " Atlas"; + fontAsset.atlasWidth = m_AtlasWidth; + fontAsset.atlasHeight = m_AtlasHeight; + fontAsset.atlasPadding = m_Padding; + + // Special handling due to a bug in earlier versions of Unity. + m_FontAtlasTexture.hideFlags = HideFlags.None; + fontAsset.material.hideFlags = HideFlags.None; + + AssetDatabase.AddObjectToAsset(m_FontAtlasTexture, fontAsset); + + // Assign new font atlas texture to the existing material. + fontAsset.material.SetTexture(ShaderUtilities.ID_MainTex, fontAsset.atlasTextures[0]); + + // Update the Texture reference on the Material + for (int i = 0; i < material_references.Length; i++) + { + material_references[i].SetTexture(ShaderUtilities.ID_MainTex, m_FontAtlasTexture); + } + } + + // Add list of GlyphRects to font asset. + fontAsset.freeGlyphRects = m_FreeGlyphRects; + fontAsset.usedGlyphRects = m_UsedGlyphRects; + + // Save Font Asset creation settings + m_SelectedFontAsset = fontAsset; + m_LegacyFontAsset = null; + fontAsset.creationSettings = SaveFontCreationSettings(); + + AssetDatabase.SaveAssets(); + + AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(fontAsset)); // Re-import font asset to get the new updated version. + + //EditorUtility.SetDirty(font_asset); + fontAsset.ReadFontAssetDefinition(); + + AssetDatabase.Refresh(); + + m_FontAtlasTexture = null; + + // NEED TO GENERATE AN EVENT TO FORCE A REDRAW OF ANY TEXTMESHPRO INSTANCES THAT MIGHT BE USING THIS FONT ASSET + TMPro_EventManager.ON_FONT_PROPERTY_CHANGED(true, fontAsset); + } + + + void Save_SDF_FontAsset(string filePath) + { + filePath = filePath.Substring(0, filePath.Length - 6); // Trim file extension from filePath. + + string dataPath = Application.dataPath; + + if (filePath.IndexOf(dataPath, System.StringComparison.InvariantCultureIgnoreCase) == -1) + { + Debug.LogError("You're saving the font asset in a directory outside of this project folder. This is not supported. Please select a directory under \"" + dataPath + "\""); + return; + } + + string relativeAssetPath = filePath.Substring(dataPath.Length - 6); + string tex_DirName = Path.GetDirectoryName(relativeAssetPath); + string tex_FileName = Path.GetFileNameWithoutExtension(relativeAssetPath); + string tex_Path_NoExt = tex_DirName + "/" + tex_FileName; + + + // Check if TextMeshPro font asset already exists. If not, create a new one. Otherwise update the existing one. + TMP_FontAsset fontAsset = AssetDatabase.LoadAssetAtPath(tex_Path_NoExt + ".asset"); + if (fontAsset == null) + { + //Debug.Log("Creating TextMeshPro font asset!"); + fontAsset = ScriptableObject.CreateInstance(); // Create new TextMeshPro Font Asset. + AssetDatabase.CreateAsset(fontAsset, tex_Path_NoExt + ".asset"); + + // Set version number of font asset + fontAsset.version = "1.1.0"; + + // Reference to source font file GUID. + fontAsset.m_SourceFontFileGUID = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(m_SourceFontFile)); + + //Set Font Asset Type + fontAsset.atlasRenderMode = m_GlyphRenderMode; + + // Add FaceInfo to Font Asset + fontAsset.faceInfo = m_FaceInfo; + + // Add GlyphInfo[] to Font Asset + fontAsset.glyphTable = m_FontGlyphTable; + + // Add CharacterTable[] to font asset. + fontAsset.characterTable = m_FontCharacterTable; + + // Sort glyph and character tables. + fontAsset.SortGlyphAndCharacterTables(); + + // Get and Add Kerning Pairs to Font Asset + if (m_IncludeFontFeatures) + fontAsset.fontFeatureTable = GetKerningTable(); + + // Add Font Atlas as Sub-Asset + fontAsset.atlasTextures = new Texture2D[] { m_FontAtlasTexture }; + m_FontAtlasTexture.name = tex_FileName + " Atlas"; + fontAsset.atlasWidth = m_AtlasWidth; + fontAsset.atlasHeight = m_AtlasHeight; + fontAsset.atlasPadding = m_Padding; + + AssetDatabase.AddObjectToAsset(m_FontAtlasTexture, fontAsset); + + // Create new Material and Add it as Sub-Asset + Shader default_Shader = Shader.Find("TextMeshPro/Distance Field"); + Material tmp_material = new Material(default_Shader); + + tmp_material.name = tex_FileName + " Material"; + tmp_material.SetTexture(ShaderUtilities.ID_MainTex, m_FontAtlasTexture); + tmp_material.SetFloat(ShaderUtilities.ID_TextureWidth, m_FontAtlasTexture.width); + tmp_material.SetFloat(ShaderUtilities.ID_TextureHeight, m_FontAtlasTexture.height); + + int spread = m_Padding + 1; + tmp_material.SetFloat(ShaderUtilities.ID_GradientScale, spread); // Spread = Padding for Brute Force SDF. + + tmp_material.SetFloat(ShaderUtilities.ID_WeightNormal, fontAsset.normalStyle); + tmp_material.SetFloat(ShaderUtilities.ID_WeightBold, fontAsset.boldStyle); + + fontAsset.material = tmp_material; + + AssetDatabase.AddObjectToAsset(tmp_material, fontAsset); + + } + else + { + // Find all Materials referencing this font atlas. + Material[] material_references = TMP_EditorUtility.FindMaterialReferences(fontAsset); + + // Destroy Assets that will be replaced. + if (fontAsset.atlasTextures != null && fontAsset.atlasTextures.Length > 0) + DestroyImmediate(fontAsset.atlasTextures[0], true); + + // Set version number of font asset + fontAsset.version = "1.1.0"; + + // Special handling to remove legacy font asset data + if (fontAsset.m_glyphInfoList != null && fontAsset.m_glyphInfoList.Count > 0) + fontAsset.m_glyphInfoList = null; + + //Set Font Asset Type + fontAsset.atlasRenderMode = m_GlyphRenderMode; + + // Add FaceInfo to Font Asset + fontAsset.faceInfo = m_FaceInfo; + + // Add GlyphInfo[] to Font Asset + fontAsset.glyphTable = m_FontGlyphTable; + + // Add CharacterTable[] to font asset. + fontAsset.characterTable = m_FontCharacterTable; + + // Sort glyph and character tables. + fontAsset.SortGlyphAndCharacterTables(); + + // Get and Add Kerning Pairs to Font Asset + // TODO: Check and preserve existing adjustment pairs. + if (m_IncludeFontFeatures) + fontAsset.fontFeatureTable = GetKerningTable(); + + // Add Font Atlas as Sub-Asset + fontAsset.atlasTextures = new Texture2D[] { m_FontAtlasTexture }; + m_FontAtlasTexture.name = tex_FileName + " Atlas"; + fontAsset.atlasWidth = m_AtlasWidth; + fontAsset.atlasHeight = m_AtlasHeight; + fontAsset.atlasPadding = m_Padding; + + // Special handling due to a bug in earlier versions of Unity. + m_FontAtlasTexture.hideFlags = HideFlags.None; + fontAsset.material.hideFlags = HideFlags.None; + + AssetDatabase.AddObjectToAsset(m_FontAtlasTexture, fontAsset); + + // Assign new font atlas texture to the existing material. + fontAsset.material.SetTexture(ShaderUtilities.ID_MainTex, fontAsset.atlasTextures[0]); + + // Update the Texture reference on the Material + for (int i = 0; i < material_references.Length; i++) + { + material_references[i].SetTexture(ShaderUtilities.ID_MainTex, m_FontAtlasTexture); + material_references[i].SetFloat(ShaderUtilities.ID_TextureWidth, m_FontAtlasTexture.width); + material_references[i].SetFloat(ShaderUtilities.ID_TextureHeight, m_FontAtlasTexture.height); + + int spread = m_Padding + 1; + material_references[i].SetFloat(ShaderUtilities.ID_GradientScale, spread); // Spread = Padding for Brute Force SDF. + + material_references[i].SetFloat(ShaderUtilities.ID_WeightNormal, fontAsset.normalStyle); + material_references[i].SetFloat(ShaderUtilities.ID_WeightBold, fontAsset.boldStyle); + } + } + + // Saving File for Debug + //var pngData = destination_Atlas.EncodeToPNG(); + //File.WriteAllBytes("Assets/Textures/Debug Distance Field.png", pngData); + + // Add list of GlyphRects to font asset. + fontAsset.freeGlyphRects = m_FreeGlyphRects; + fontAsset.usedGlyphRects = m_UsedGlyphRects; + + // Save Font Asset creation settings + m_SelectedFontAsset = fontAsset; + m_LegacyFontAsset = null; + fontAsset.creationSettings = SaveFontCreationSettings(); + + AssetDatabase.SaveAssets(); + + AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(fontAsset)); // Re-import font asset to get the new updated version. + + fontAsset.ReadFontAssetDefinition(); + + AssetDatabase.Refresh(); + + m_FontAtlasTexture = null; + + // NEED TO GENERATE AN EVENT TO FORCE A REDRAW OF ANY TEXTMESHPRO INSTANCES THAT MIGHT BE USING THIS FONT ASSET + TMPro_EventManager.ON_FONT_PROPERTY_CHANGED(true, fontAsset); + } + + + /// + /// Internal method to save the Font Asset Creation Settings + /// + /// + FontAssetCreationSettings SaveFontCreationSettings() + { + FontAssetCreationSettings settings = new FontAssetCreationSettings(); + + //settings.sourceFontFileName = m_SourceFontFile.name; + settings.sourceFontFileGUID = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(m_SourceFontFile)); + settings.pointSizeSamplingMode = m_PointSizeSamplingMode; + settings.pointSize = m_PointSize; + settings.padding = m_Padding; + settings.packingMode = (int)m_PackingMode; + settings.atlasWidth = m_AtlasWidth; + settings.atlasHeight = m_AtlasHeight; + settings.characterSetSelectionMode = m_CharacterSetSelectionMode; + settings.characterSequence = m_CharacterSequence; + settings.referencedFontAssetGUID = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(m_ReferencedFontAsset)); + settings.referencedTextAssetGUID = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(m_CharactersFromFile)); + //settings.fontStyle = (int)m_FontStyle; + //settings.fontStyleModifier = m_FontStyleValue; + settings.renderMode = (int)m_GlyphRenderMode; + settings.includeFontFeatures = m_IncludeFontFeatures; + + return settings; + } + + + /// + /// Internal method to load the Font Asset Creation Settings + /// + /// + void LoadFontCreationSettings(FontAssetCreationSettings settings) + { + m_SourceFontFile = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(settings.sourceFontFileGUID)); + m_PointSizeSamplingMode = settings.pointSizeSamplingMode; + m_PointSize = settings.pointSize; + m_Padding = settings.padding; + m_PackingMode = (FontPackingModes)settings.packingMode; + m_AtlasWidth = settings.atlasWidth; + m_AtlasHeight = settings.atlasHeight; + m_CharacterSetSelectionMode = settings.characterSetSelectionMode; + m_CharacterSequence = settings.characterSequence; + m_ReferencedFontAsset = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(settings.referencedFontAssetGUID)); + m_CharactersFromFile = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(settings.referencedTextAssetGUID)); + //m_FontStyle = (FaceStyles)settings.fontStyle; + //m_FontStyleValue = settings.fontStyleModifier; + m_GlyphRenderMode = (GlyphRenderMode)settings.renderMode; + m_IncludeFontFeatures = settings.includeFontFeatures; + } + + + /// + /// Save the latest font asset creation settings to EditorPrefs. + /// + /// + void SaveCreationSettingsToEditorPrefs(FontAssetCreationSettings settings) + { + // Create new list if one does not already exist + if (m_FontAssetCreationSettingsContainer == null) + { + m_FontAssetCreationSettingsContainer = new FontAssetCreationSettingsContainer(); + m_FontAssetCreationSettingsContainer.fontAssetCreationSettings = new List(); + } + + // Add new creation settings to the list + m_FontAssetCreationSettingsContainer.fontAssetCreationSettings.Add(settings); + + // Since list should only contain the most 4 recent settings, we remove the first element if list exceeds 4 elements. + if (m_FontAssetCreationSettingsContainer.fontAssetCreationSettings.Count > 4) + m_FontAssetCreationSettingsContainer.fontAssetCreationSettings.RemoveAt(0); + + m_FontAssetCreationSettingsCurrentIndex = m_FontAssetCreationSettingsContainer.fontAssetCreationSettings.Count - 1; + + // Serialize list to JSON + string serializedSettings = JsonUtility.ToJson(m_FontAssetCreationSettingsContainer, true); + + EditorPrefs.SetString(k_FontAssetCreationSettingsContainerKey, serializedSettings); + } + + void DrawPreview() + { + Rect pixelRect; + if (position.width > position.height && position.width > k_TwoColumnControlsWidth) + { + float minSide = Mathf.Min(position.height - 15f, position.width - k_TwoColumnControlsWidth); + + EditorGUILayout.BeginVertical(EditorStyles.helpBox, GUILayout.MaxWidth(minSide)); + + pixelRect = GUILayoutUtility.GetRect(minSide, minSide, GUILayout.ExpandHeight(false), GUILayout.ExpandWidth(false)); + } + else + { + EditorGUILayout.BeginVertical(EditorStyles.helpBox); + + pixelRect = GUILayoutUtility.GetAspectRect(1f); + } + + if (m_FontAtlasTexture != null) + { + EditorGUI.DrawTextureAlpha(pixelRect, m_FontAtlasTexture, ScaleMode.StretchToFill); + } + else if (m_SavedFontAtlas != null) + { + EditorGUI.DrawTextureAlpha(pixelRect, m_SavedFontAtlas, ScaleMode.StretchToFill); + } + + EditorGUILayout.EndVertical(); + } + + + void CheckForLegacyGlyphRenderMode() + { + // Special handling for legacy glyph render mode + if ((int)m_GlyphRenderMode < 0x100) + { + switch ((int)m_GlyphRenderMode) + { + case 0: + m_GlyphRenderMode = GlyphRenderMode.SMOOTH_HINTED; + break; + case 1: + m_GlyphRenderMode = GlyphRenderMode.SMOOTH; + break; + case 2: + m_GlyphRenderMode = GlyphRenderMode.RASTER_HINTED; + break; + case 3: + m_GlyphRenderMode = GlyphRenderMode.RASTER; + break; + case 6: + case 7: + m_GlyphRenderMode = GlyphRenderMode.SDFAA; + break; + } + } + } + + + // Get Kerning Pairs + public TMP_FontFeatureTable GetKerningTable() + { + GlyphPairAdjustmentRecord[] adjustmentRecords = FontEngine.GetGlyphPairAdjustmentTable(m_AvailableGlyphsToAdd.ToArray()); + + if (adjustmentRecords == null) + return null; + + TMP_FontFeatureTable fontFeatureTable = new TMP_FontFeatureTable(); + + for (int i = 0; i < adjustmentRecords.Length; i++) + { + fontFeatureTable.glyphPairAdjustmentRecords.Add(new TMP_GlyphPairAdjustmentRecord(adjustmentRecords[i])); + } + + fontFeatureTable.SortGlyphPairAdjustmentRecords(); + + return fontFeatureTable; + } + } +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMPro_FontPlugin.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMPro_FontPlugin.cs new file mode 100644 index 00000000..3b098ff2 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMPro_FontPlugin.cs @@ -0,0 +1,115 @@ +using UnityEngine; +using UnityEditor; +using System.Collections; +using System; +using System.Runtime.InteropServices; + + +namespace TMPro.EditorUtilities +{ + /* + public class TMPro_FontPlugin + { + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate void DebugLog(string log); + private static readonly DebugLog debugLog = DebugWrapper; + private static readonly IntPtr functionPointer = Marshal.GetFunctionPointerForDelegate(debugLog); + + private static void DebugWrapper(string log) + { + Debug.Log(log); + } + + public static void LinkDebugLog() + { + LinkDebug(functionPointer); + } + + [DllImport("TMPro_Plugin")] + private static extern void LinkDebug([MarshalAs(UnmanagedType.FunctionPtr)]IntPtr debugCall); + + [DllImport("TMPro_Plugin")] + public static extern + int Initialize_FontEngine(); + + [DllImport("TMPro_Plugin")] + public static extern + int Destroy_FontEngine(); + + [DllImport("TMPro_Plugin")] + public static extern + int Load_TrueType_Font(string fontPath); + + [DllImport("TMPro_Plugin")] + public static extern + int FT_Size_Font(int fontSize); + + [DllImport("TMPro_Plugin")] + public static extern + int Render_Character(byte[] buffer_fill, byte[] buffer_edge, int buffer_width, int buffer_height, int offset, int asc, FaceStyles style, float thickness, RenderModes rasterMode, ref FT_GlyphInfo glyphInfo); + + [DllImport("TMPro_Plugin")] + public static extern + int Render_Characters(byte[] buffer, int buffer_width, int buffer_height, int character_padding, int[] asc_set, int char_count, FaceStyles style, float style_mod, bool autoSize, RenderModes renderMode, int method, ref FT_FaceInfo fontData, FT_GlyphInfo[] Output); + + [DllImport("TMPro_Plugin")] + public static extern + int FT_GetKerningPairs(string fontPath, int[] characterSet, int setCount, FT_KerningPair[] kerningPairs); + + [DllImport("TMPro_Plugin")] + public static extern + float Check_RenderProgress(); + + [DllImport("TMPro_Plugin")] + internal static extern + void SendCancellationRequest(CancellationRequestType request); + } + + public enum FaceStyles { Normal, Bold, Italic, Bold_Italic, Outline, Bold_Sim }; + public enum RenderModes { HintedSmooth = 0, Smooth = 1, RasterHinted = 2, Raster = 3, DistanceField16 = 6, DistanceField32 = 7 }; // SignedDistanceField64 = 8 + + internal enum CancellationRequestType : byte { None = 0x0, CancelInProgess = 0x1, WindowClosed = 0x2 }; + + [StructLayout(LayoutKind.Sequential)] + public struct FT_KerningPair + { + public int ascII_Left; + public int ascII_Right; + public float xAdvanceOffset; + } + + + [StructLayout(LayoutKind.Sequential)] + public struct FT_GlyphInfo + { + public int id; + public float x; + public float y; + public float width; + public float height; + public float xOffset; + public float yOffset; + public float xAdvance; + } + + + [StructLayout(LayoutKind.Sequential)] + public struct FT_FaceInfo + { + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)] + public string name; + public int pointSize; + public int padding; + public float lineHeight; + public float baseline; + public float ascender; + public float descender; + public float centerLine; + public float underline; + public float underlineThickness; + public int characterCount; + public int atlasWidth; + public int atlasHeight; + } + */ +} diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMPro_SortingLayerHelper.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMPro_SortingLayerHelper.cs new file mode 100644 index 00000000..4f44c53b --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMPro_SortingLayerHelper.cs @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2014, Nick Gravelyn. + * + * This software is provided 'as-is', without any express or implied + * warranty. In no event will the authors be held liable for any damages + * arising from the use of this software. + * + * Permission is granted to anyone to use this software for any purpose, + * including commercial applications, and to alter it and redistribute it + * freely, subject to the following restrictions: + * + * 1. The origin of this software must not be misrepresented; you must not + * claim that you wrote the original software. If you use this software + * in a product, an acknowledgment in the product documentation would be + * appreciated but is not required. + * + * 2. Altered source versions must be plainly marked as such, and must not be + * misrepresented as being the original software. + * + * 3. This notice may not be removed or altered from any source + * distribution. + */ + +using UnityEngine; +using UnityEditor; +using System; +using System.Reflection; + +namespace TMPro +{ + // Helpers used by the different sorting layer classes. + public static class SortingLayerHelper + { + private static Type _utilityType; + private static PropertyInfo _sortingLayerNamesProperty; + private static MethodInfo _getSortingLayerUserIdMethod; + + static SortingLayerHelper() + { + _utilityType = Type.GetType("UnityEditorInternal.InternalEditorUtility, UnityEditor"); + _sortingLayerNamesProperty = _utilityType.GetProperty("sortingLayerNames", BindingFlags.Static | BindingFlags.NonPublic); + _getSortingLayerUserIdMethod = _utilityType.GetMethod("GetSortingLayerUniqueID", BindingFlags.Static | BindingFlags.NonPublic); + } + + // Gets an array of sorting layer names. + // Since this uses reflection, callers should check for 'null' which will be returned if the reflection fails. + public static string[] sortingLayerNames + { + get + { + if (_sortingLayerNamesProperty == null) + { + return null; + } + + return _sortingLayerNamesProperty.GetValue(null, null) as string[]; + } + } + + // Given the ID of a sorting layer, returns the sorting layer's name + public static string GetSortingLayerNameFromID(int id) + { + string[] names = sortingLayerNames; + if (names == null) + { + return null; + } + + for (int i = 0; i < names.Length; i++) + { + if (GetSortingLayerIDForIndex(i) == id) + { + return names[i]; + } + } + + return null; + } + + // Given the name of a sorting layer, returns the ID. + public static int GetSortingLayerIDForName(string name) + { + string[] names = sortingLayerNames; + if (names == null) + { + return 0; + } + + return GetSortingLayerIDForIndex(Array.IndexOf(names, name)); + } + + // Helper to convert from a sorting layer INDEX to a sorting layer ID. These are not the same thing. + // IDs are based on the order in which layers were created and do not change when reordering the layers. + // Thankfully there is a private helper we can call to get the ID for a layer given its index. + public static int GetSortingLayerIDForIndex(int index) + { + if (_getSortingLayerUserIdMethod == null) + { + return 0; + } + + return (int)_getSortingLayerUserIdMethod.Invoke(null, new object[] { index }); + } + } +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMPro_TextContainerEditor.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMPro_TextContainerEditor.cs new file mode 100644 index 00000000..09fc6173 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMPro_TextContainerEditor.cs @@ -0,0 +1,235 @@ +using UnityEngine; +using UnityEditor; +using System.Collections; + + +namespace TMPro.EditorUtilities +{ + [CustomEditor(typeof(TextContainer)), CanEditMultipleObjects] + public class TMPro_TextContainerEditor : Editor + { + + // Serialized Properties + private SerializedProperty anchorPosition_prop; + private SerializedProperty pivot_prop; + private SerializedProperty rectangle_prop; + private SerializedProperty margins_prop; + + + private TextContainer m_textContainer; + //private Transform m_transform; + //private Vector3[] m_Rect_handlePoints = new Vector3[4]; + //private Vector3[] m_Margin_handlePoints = new Vector3[4]; + + //private Vector2 m_anchorPosition; + + //private Vector3 m_mousePreviousPOS; + //private Vector2 m_previousStartPOS; + //private int m_mouseDragFlag = 0; + + //private static Transform m_visualHelper; + + + void OnEnable() + { + + // Serialized Properties + anchorPosition_prop = serializedObject.FindProperty("m_anchorPosition"); + pivot_prop = serializedObject.FindProperty("m_pivot"); + rectangle_prop = serializedObject.FindProperty("m_rect"); + margins_prop = serializedObject.FindProperty("m_margins"); + + m_textContainer = (TextContainer)target; + //m_transform = m_textContainer.transform; + + + /* + if (m_visualHelper == null) + { + m_visualHelper = GameObject.CreatePrimitive(PrimitiveType.Sphere).transform; + m_visualHelper.localScale = new Vector3(0.25f, 0.25f, 0.25f); + } + */ + } + + void OnDisable() + { + /* + if (m_visualHelper != null) + DestroyImmediate (m_visualHelper.gameObject); + */ + } + + + + + public override void OnInspectorGUI() + { + serializedObject.Update(); + + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(anchorPosition_prop); + if (anchorPosition_prop.enumValueIndex == 9) + { + EditorGUI.indentLevel += 1; + EditorGUILayout.PropertyField(pivot_prop, new GUIContent("Pivot Position")); + EditorGUI.indentLevel -= 1; + } + + + DrawDimensionProperty(rectangle_prop, "Dimensions"); + DrawMaginProperty(margins_prop, "Margins"); + if (EditorGUI.EndChangeCheck()) + { + // Re-compute pivot position when changes are made. + if (anchorPosition_prop.enumValueIndex != 9) + pivot_prop.vector2Value = GetAnchorPosition(anchorPosition_prop.enumValueIndex); + + m_textContainer.hasChanged = true; + } + + serializedObject.ApplyModifiedProperties(); + + EditorGUILayout.Space(); + } + + + private void DrawDimensionProperty(SerializedProperty property, string label) + { + float old_LabelWidth = EditorGUIUtility.labelWidth; + float old_FieldWidth = EditorGUIUtility.fieldWidth; + + Rect rect = EditorGUILayout.GetControlRect(false, 18); + Rect pos0 = new Rect(rect.x, rect.y + 2, rect.width, 18); + + float width = rect.width + 3; + pos0.width = old_LabelWidth; + GUI.Label(pos0, label); + + Rect rectangle = property.rectValue; + + float width_B = width - old_LabelWidth; + float fieldWidth = width_B / 4; + pos0.width = fieldWidth - 5; + + pos0.x = old_LabelWidth + 15; + GUI.Label(pos0, "Width"); + + pos0.x += fieldWidth; + rectangle.width = EditorGUI.FloatField(pos0, GUIContent.none, rectangle.width); + + pos0.x += fieldWidth; + GUI.Label(pos0, "Height"); + + pos0.x += fieldWidth; + rectangle.height = EditorGUI.FloatField(pos0, GUIContent.none, rectangle.height); + + property.rectValue = rectangle; + EditorGUIUtility.labelWidth = old_LabelWidth; + EditorGUIUtility.fieldWidth = old_FieldWidth; + } + + + private void DrawMaginProperty(SerializedProperty property, string label) + { + float old_LabelWidth = EditorGUIUtility.labelWidth; + float old_FieldWidth = EditorGUIUtility.fieldWidth; + + Rect rect = EditorGUILayout.GetControlRect(false, 2 * 18); + Rect pos0 = new Rect(rect.x, rect.y + 2, rect.width, 18); + + float width = rect.width + 3; + pos0.width = old_LabelWidth; + GUI.Label(pos0, label); + + //Vector4 vec = property.vector4Value; + Vector4 vec = Vector4.zero; + vec.x = property.FindPropertyRelative("x").floatValue; + vec.y = property.FindPropertyRelative("y").floatValue; + vec.z = property.FindPropertyRelative("z").floatValue; + vec.w = property.FindPropertyRelative("w").floatValue; + + + float widthB = width - old_LabelWidth; + float fieldWidth = widthB / 4; + pos0.width = fieldWidth - 5; + + // Labels + pos0.x = old_LabelWidth + 15; + GUI.Label(pos0, "Left"); + + pos0.x += fieldWidth; + GUI.Label(pos0, "Top"); + + pos0.x += fieldWidth; + GUI.Label(pos0, "Right"); + + pos0.x += fieldWidth; + GUI.Label(pos0, "Bottom"); + + pos0.y += 18; + + pos0.x = old_LabelWidth + 15; + vec.x = EditorGUI.FloatField(pos0, GUIContent.none, vec.x); + + pos0.x += fieldWidth; + vec.y = EditorGUI.FloatField(pos0, GUIContent.none, vec.y); + + pos0.x += fieldWidth; + vec.z = EditorGUI.FloatField(pos0, GUIContent.none, vec.z); + + pos0.x += fieldWidth; + vec.w = EditorGUI.FloatField(pos0, GUIContent.none, vec.w); + + //property.vector4Value = vec; + property.FindPropertyRelative("x").floatValue = vec.x; + property.FindPropertyRelative("y").floatValue = vec.y; + property.FindPropertyRelative("z").floatValue = vec.z; + property.FindPropertyRelative("w").floatValue = vec.w; + + EditorGUIUtility.labelWidth = old_LabelWidth; + EditorGUIUtility.fieldWidth = old_FieldWidth; + } + + + Vector2 GetAnchorPosition(int index) + { + Vector2 anchorPosition = Vector2.zero; + + switch (index) + { + case 0: // TOP LEFT + anchorPosition = new Vector2(0, 1); + break; + case 1: // TOP + anchorPosition = new Vector2(0.5f, 1); + break; + case 2: // TOP RIGHT + anchorPosition = new Vector2(1, 1); + break; + case 3: // LEFT + anchorPosition = new Vector2(0, 0.5f); + break; + case 4: // MIDDLE + anchorPosition = new Vector2(0.5f, 0.5f); + break; + case 5: // RIGHT + anchorPosition = new Vector2(1, 0.5f); + break; + case 6: // BOTTOM LEFT + anchorPosition = new Vector2(0, 0); + break; + case 7: // BOTTOM + anchorPosition = new Vector2(0.5f, 0); + break; + case 8: // BOTTOM RIGHT + anchorPosition = new Vector2(1, 0); + break; + } + + return anchorPosition; + } + + + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMPro_TexturePostProcessor.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMPro_TexturePostProcessor.cs new file mode 100644 index 00000000..b1634094 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMPro_TexturePostProcessor.cs @@ -0,0 +1,75 @@ +using UnityEngine; +using UnityEditor; +using System.Collections; + + +namespace TMPro.EditorUtilities +{ + + public class TMPro_TexturePostProcessor : AssetPostprocessor + { + + void OnPostprocessTexture(Texture2D texture) + { + //var importer = assetImporter as TextureImporter; + + Texture2D tex = AssetDatabase.LoadAssetAtPath(assetPath, typeof(Texture2D)) as Texture2D; + + // Send Event Sub Objects + if (tex != null) + TMPro_EventManager.ON_SPRITE_ASSET_PROPERTY_CHANGED(true, tex); + } + + } + + + //public class TMPro_PackageImportPostProcessor : AssetPostprocessor + //{ + // static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) + // { + // for (int i = 0; i < importedAssets.Length; i++) + // { + // if (importedAssets[i].Contains("TextMesh Pro/Resources/TMP Settings.asset")) + // { + // Debug.Log("New TMP Settings file was just imported."); + + // // TMP Settings file was just re-imported. + // // Check if project already contains + // } + + + // if (importedAssets[i].Contains("com.unity.TextMeshPro/Examples")) + // { + // //Debug.Log("New TMP Examples folder was just imported."); + // } + + // //Debug.Log("[" + importedAssets[i] + "] was just imported."); + // } + + + + // //for (int i = 0; i < deletedAssets.Length; i++) + // //{ + // // if (deletedAssets[i] == "Assets/TextMesh Pro") + // // { + // // //Debug.Log("Asset [" + deletedAssets[i] + "] has been deleted."); + // // string currentBuildSettings = PlayerSettings.GetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup); + + // // //Check for and inject TMP_PRESENT + // // if (currentBuildSettings.Contains("TMP_PRESENT;")) + // // { + // // currentBuildSettings = currentBuildSettings.Replace("TMP_PRESENT;", ""); + + // // PlayerSettings.SetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup, currentBuildSettings); + // // } + // // else if (currentBuildSettings.Contains("TMP_PRESENT")) + // // { + // // currentBuildSettings = currentBuildSettings.Replace("TMP_PRESENT", ""); + + // // PlayerSettings.SetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup, currentBuildSettings); + // // } + // // } + // //} + // } + //} +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/Unity.TextMeshPro.Editor.asmdef b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/Unity.TextMeshPro.Editor.asmdef new file mode 100644 index 00000000..d5df154d --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/Unity.TextMeshPro.Editor.asmdef @@ -0,0 +1,13 @@ +{ + "name": "Unity.TextMeshPro.Editor", + "references": [ + "Unity.TextMeshPro", + "Unity.ugui", + "Unity.ugui.Editor" + ], + "optionalUnityReferences": [], + "includePlatforms": [ + "Editor" + ], + "excludePlatforms": [] +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Runtime/AssemblyInfo.cs.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Runtime/AssemblyInfo.cs.cs new file mode 100644 index 00000000..52784935 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Runtime/AssemblyInfo.cs.cs @@ -0,0 +1,11 @@ +using System.Runtime.CompilerServices; + +// Allow internal visibility for testing purposes. +[assembly: InternalsVisibleTo("Unity.TextCore")] + +[assembly: InternalsVisibleTo("Unity.FontEngine.Tests")] + +#if UNITY_EDITOR +[assembly: InternalsVisibleTo("Unity.TextCore.Editor")] +[assembly: InternalsVisibleTo("Unity.TextMeshPro.Editor")] +#endif diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Runtime/FastAction.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Runtime/FastAction.cs new file mode 100644 index 00000000..0a6485ab --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Runtime/FastAction.cs @@ -0,0 +1,146 @@ +using UnityEngine; +using System.Collections; +using System.Collections.Generic; + + +namespace TMPro +{ + public class FastAction + { + + LinkedList delegates = new LinkedList(); + + Dictionary> lookup = new Dictionary>(); + + public void Add(System.Action rhs) + { + if (lookup.ContainsKey(rhs)) return; + + lookup[rhs] = delegates.AddLast(rhs); + } + + public void Remove(System.Action rhs) + { + if (lookup.TryGetValue(rhs, out LinkedListNode node)) + { + lookup.Remove(rhs); + delegates.Remove(node); + } + } + + public void Call() + { + var node = delegates.First; + while (node != null) + { + node.Value(); + node = node.Next; + } + } + } + + + public class FastAction + { + + LinkedList> delegates = new LinkedList>(); + + Dictionary, LinkedListNode>> lookup = new Dictionary, LinkedListNode>>(); + + public void Add(System.Action rhs) + { + if (lookup.ContainsKey(rhs)) return; + + lookup[rhs] = delegates.AddLast(rhs); + } + + public void Remove(System.Action rhs) + { + if (lookup.TryGetValue(rhs, out LinkedListNode> node)) + { + lookup.Remove(rhs); + delegates.Remove(node); + } + } + + public void Call(A a) + { + var node = delegates.First; + while (node != null) + { + node.Value(a); + node = node.Next; + } + } + } + + + public class FastAction + { + + LinkedList> delegates = new LinkedList>(); + + Dictionary, LinkedListNode>> lookup = new Dictionary, LinkedListNode>>(); + + public void Add(System.Action rhs) + { + if (lookup.ContainsKey(rhs)) return; + + lookup[rhs] = delegates.AddLast(rhs); + } + + public void Remove(System.Action rhs) + { + if (lookup.TryGetValue(rhs, out LinkedListNode> node)) + { + lookup.Remove(rhs); + delegates.Remove(node); + } + } + + public void Call(A a, B b) + { + var node = delegates.First; + while (node != null) + { + node.Value(a, b); + node = node.Next; + } + } + } + + + public class FastAction + { + + LinkedList> delegates = new LinkedList>(); + + Dictionary, LinkedListNode>> lookup = new Dictionary, LinkedListNode>>(); + + public void Add(System.Action rhs) + { + if (lookup.ContainsKey(rhs)) return; + + lookup[rhs] = delegates.AddLast(rhs); + } + + public void Remove(System.Action rhs) + { + if (lookup.TryGetValue(rhs, out LinkedListNode> node)) + { + lookup.Remove(rhs); + delegates.Remove(node); + } + } + + public void Call(A a, B b, C c) + { + var node = delegates.First; + while (node != null) + { + node.Value(a, b, c); + node = node.Next; + } + } + } +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Runtime/MaterialReferenceManager.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Runtime/MaterialReferenceManager.cs new file mode 100644 index 00000000..33709634 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Runtime/MaterialReferenceManager.cs @@ -0,0 +1,644 @@ +using UnityEngine; +using System.Collections; +using System.Collections.Generic; + + +namespace TMPro +{ + + public class MaterialReferenceManager + { + private static MaterialReferenceManager s_Instance; + + // Dictionaries used to track Asset references. + private Dictionary m_FontMaterialReferenceLookup = new Dictionary(); + private Dictionary m_FontAssetReferenceLookup = new Dictionary(); + private Dictionary m_SpriteAssetReferenceLookup = new Dictionary(); + private Dictionary m_ColorGradientReferenceLookup = new Dictionary(); + + + /// + /// Get a singleton instance of the registry + /// + public static MaterialReferenceManager instance + { + get + { + if (MaterialReferenceManager.s_Instance == null) + MaterialReferenceManager.s_Instance = new MaterialReferenceManager(); + return MaterialReferenceManager.s_Instance; + } + } + + + + /// + /// Add new font asset reference to dictionary. + /// + /// + public static void AddFontAsset(TMP_FontAsset fontAsset) + { + MaterialReferenceManager.instance.AddFontAssetInternal(fontAsset); + } + + /// + /// Add new Font Asset reference to dictionary. + /// + /// + private void AddFontAssetInternal(TMP_FontAsset fontAsset) + { + if (m_FontAssetReferenceLookup.ContainsKey(fontAsset.hashCode)) return; + + // Add reference to the font asset. + m_FontAssetReferenceLookup.Add(fontAsset.hashCode, fontAsset); + + // Add reference to the font material. + m_FontMaterialReferenceLookup.Add(fontAsset.materialHashCode, fontAsset.material); + } + + + + /// + /// Add new Sprite Asset to dictionary. + /// + /// + /// + public static void AddSpriteAsset(TMP_SpriteAsset spriteAsset) + { + MaterialReferenceManager.instance.AddSpriteAssetInternal(spriteAsset); + } + + /// + /// Internal method to add a new sprite asset to the dictionary. + /// + /// + /// + private void AddSpriteAssetInternal(TMP_SpriteAsset spriteAsset) + { + if (m_SpriteAssetReferenceLookup.ContainsKey(spriteAsset.hashCode)) return; + + // Add reference to sprite asset. + m_SpriteAssetReferenceLookup.Add(spriteAsset.hashCode, spriteAsset); + + // Adding reference to the sprite asset material as well + m_FontMaterialReferenceLookup.Add(spriteAsset.hashCode, spriteAsset.material); + } + + /// + /// Add new Sprite Asset to dictionary. + /// + /// + /// + public static void AddSpriteAsset(int hashCode, TMP_SpriteAsset spriteAsset) + { + MaterialReferenceManager.instance.AddSpriteAssetInternal(hashCode, spriteAsset); + } + + /// + /// Internal method to add a new sprite asset to the dictionary. + /// + /// + /// + private void AddSpriteAssetInternal(int hashCode, TMP_SpriteAsset spriteAsset) + { + if (m_SpriteAssetReferenceLookup.ContainsKey(hashCode)) return; + + // Add reference to Sprite Asset. + m_SpriteAssetReferenceLookup.Add(hashCode, spriteAsset); + + // Add reference to Sprite Asset using the asset hashcode. + m_FontMaterialReferenceLookup.Add(hashCode, spriteAsset.material); + + // Compatibility check + if (spriteAsset.hashCode == 0) spriteAsset.hashCode = hashCode; + } + + + /// + /// Add new Material reference to dictionary. + /// + /// + /// + public static void AddFontMaterial(int hashCode, Material material) + { + MaterialReferenceManager.instance.AddFontMaterialInternal(hashCode, material); + } + + /// + /// Add new material reference to dictionary. + /// + /// + /// + private void AddFontMaterialInternal(int hashCode, Material material) + { + // Since this function is called after checking if the material is + // contained in the dictionary, there is no need to check again. + m_FontMaterialReferenceLookup.Add(hashCode, material); + } + + + /// + /// Add new Color Gradient Preset to dictionary. + /// + /// + /// + public static void AddColorGradientPreset(int hashCode, TMP_ColorGradient spriteAsset) + { + MaterialReferenceManager.instance.AddColorGradientPreset_Internal(hashCode, spriteAsset); + } + + /// + /// Internal method to add a new Color Gradient Preset to the dictionary. + /// + /// + /// + private void AddColorGradientPreset_Internal(int hashCode, TMP_ColorGradient spriteAsset) + { + if (m_ColorGradientReferenceLookup.ContainsKey(hashCode)) return; + + // Add reference to Color Gradient Preset Asset. + m_ColorGradientReferenceLookup.Add(hashCode, spriteAsset); + } + + + + /// + /// Add new material reference and return the index of this new reference in the materialReferences array. + /// + /// + /// + /// + //public int AddMaterial(Material material, int materialHashCode, TMP_FontAsset fontAsset) + //{ + // if (!m_MaterialReferenceLookup.ContainsKey(materialHashCode)) + // { + // int index = m_MaterialReferenceLookup.Count; + + // materialReferences[index].fontAsset = fontAsset; + // materialReferences[index].material = material; + // materialReferences[index].isDefaultMaterial = material.GetInstanceID() == fontAsset.material.GetInstanceID() ? true : false; + // materialReferences[index].index = index; + // materialReferences[index].referenceCount = 0; + + // m_MaterialReferenceLookup[materialHashCode] = index; + + // // Compute Padding value and store it + // // TODO + + // int fontAssetHashCode = fontAsset.hashCode; + + // if (!m_FontAssetReferenceLookup.ContainsKey(fontAssetHashCode)) + // m_FontAssetReferenceLookup.Add(fontAssetHashCode, fontAsset); + + // m_countInternal += 1; + + // return index; + // } + // else + // { + // return m_MaterialReferenceLookup[materialHashCode]; + // } + //} + + + /// + /// Add new material reference and return the index of this new reference in the materialReferences array. + /// + /// + /// + /// + /// + //public int AddMaterial(Material material, int materialHashCode, TMP_SpriteAsset spriteAsset) + //{ + // if (!m_MaterialReferenceLookup.ContainsKey(materialHashCode)) + // { + // int index = m_MaterialReferenceLookup.Count; + + // materialReferences[index].fontAsset = materialReferences[0].fontAsset; + // materialReferences[index].spriteAsset = spriteAsset; + // materialReferences[index].material = material; + // materialReferences[index].isDefaultMaterial = true; + // materialReferences[index].index = index; + // materialReferences[index].referenceCount = 0; + + // m_MaterialReferenceLookup[materialHashCode] = index; + + // int spriteAssetHashCode = spriteAsset.hashCode; + + // if (!m_SpriteAssetReferenceLookup.ContainsKey(spriteAssetHashCode)) + // m_SpriteAssetReferenceLookup.Add(spriteAssetHashCode, spriteAsset); + + // m_countInternal += 1; + + // return index; + // } + // else + // { + // return m_MaterialReferenceLookup[materialHashCode]; + // } + //} + + + /// + /// Function to check if the font asset is already referenced. + /// + /// + /// + public bool Contains(TMP_FontAsset font) + { + if (m_FontAssetReferenceLookup.ContainsKey(font.hashCode)) + return true; + + return false; + } + + + /// + /// Function to check if the sprite asset is already referenced. + /// + /// + /// + public bool Contains(TMP_SpriteAsset sprite) + { + if (m_FontAssetReferenceLookup.ContainsKey(sprite.hashCode)) + return true; + + return false; + } + + + + /// + /// Function returning the Font Asset corresponding to the provided hash code. + /// + /// + /// + /// + public static bool TryGetFontAsset(int hashCode, out TMP_FontAsset fontAsset) + { + return MaterialReferenceManager.instance.TryGetFontAssetInternal(hashCode, out fontAsset); + } + + /// + /// Internal Function returning the Font Asset corresponding to the provided hash code. + /// + /// + /// + /// + private bool TryGetFontAssetInternal(int hashCode, out TMP_FontAsset fontAsset) + { + fontAsset = null; + + if (m_FontAssetReferenceLookup.TryGetValue(hashCode, out fontAsset)) + { + return true; + } + + return false; + } + + + + /// + /// Function returning the Sprite Asset corresponding to the provided hash code. + /// + /// + /// + /// + public static bool TryGetSpriteAsset(int hashCode, out TMP_SpriteAsset spriteAsset) + { + return MaterialReferenceManager.instance.TryGetSpriteAssetInternal(hashCode, out spriteAsset); + } + + /// + /// Internal function returning the Sprite Asset corresponding to the provided hash code. + /// + /// + /// + /// + private bool TryGetSpriteAssetInternal(int hashCode, out TMP_SpriteAsset spriteAsset) + { + spriteAsset = null; + + if (m_SpriteAssetReferenceLookup.TryGetValue(hashCode, out spriteAsset)) + { + return true; + } + + return false; + } + + + /// + /// Function returning the Color Gradient Preset corresponding to the provided hash code. + /// + /// + /// + /// + public static bool TryGetColorGradientPreset(int hashCode, out TMP_ColorGradient gradientPreset) + { + return MaterialReferenceManager.instance.TryGetColorGradientPresetInternal(hashCode, out gradientPreset); + } + + /// + /// Internal function returning the Color Gradient Preset corresponding to the provided hash code. + /// + /// + /// + /// + private bool TryGetColorGradientPresetInternal(int hashCode, out TMP_ColorGradient gradientPreset) + { + gradientPreset = null; + + if (m_ColorGradientReferenceLookup.TryGetValue(hashCode, out gradientPreset)) + { + return true; + } + + return false; + } + + + /// + /// Function returning the Font Material corresponding to the provided hash code. + /// + /// + /// + /// + public static bool TryGetMaterial(int hashCode, out Material material) + { + return MaterialReferenceManager.instance.TryGetMaterialInternal(hashCode, out material); + } + + /// + /// Internal function returning the Font Material corresponding to the provided hash code. + /// + /// + /// + /// + private bool TryGetMaterialInternal(int hashCode, out Material material) + { + material = null; + + if (m_FontMaterialReferenceLookup.TryGetValue(hashCode, out material)) + { + return true; + } + + return false; + } + + + /// + /// Function to lookup a material based on hash code and returning the MaterialReference containing this material. + /// + /// + /// + /// + //public bool TryGetMaterial(int hashCode, out MaterialReference materialReference) + //{ + // int materialIndex = -1; + + // if (m_MaterialReferenceLookup.TryGetValue(hashCode, out materialIndex)) + // { + // materialReference = materialReferences[materialIndex]; + + // return true; + // } + + // materialReference = new MaterialReference(); + + // return false; + //} + + + + /// + /// + /// + /// + /// + //public int GetMaterialIndex(TMP_FontAsset fontAsset) + //{ + // if (m_MaterialReferenceLookup.ContainsKey(fontAsset.materialHashCode)) + // return m_MaterialReferenceLookup[fontAsset.materialHashCode]; + + // return -1; + //} + + + /// + /// + /// + /// + /// + //public TMP_FontAsset GetFontAsset(int index) + //{ + // if (index >= 0 && index < materialReferences.Length) + // return materialReferences[index].fontAsset; + + // return null; + //} + + + /// + /// + /// + /// + /// + /// + //public void SetDefaultMaterial(Material material, int materialHashCode, TMP_FontAsset fontAsset) + //{ + // if (!m_MaterialReferenceLookup.ContainsKey(materialHashCode)) + // { + // materialReferences[0].fontAsset = fontAsset; + // materialReferences[0].material = material; + // materialReferences[0].index = 0; + // materialReferences[0].isDefaultMaterial = material.GetInstanceID() == fontAsset.material.GetInstanceID() ? true : false; + // materialReferences[0].referenceCount = 0; + // m_MaterialReferenceLookup[materialHashCode] = 0; + + // // Compute Padding value and store it + // // TODO + + // int fontHashCode = fontAsset.hashCode; + + // if (!m_FontAssetReferenceLookup.ContainsKey(fontHashCode)) + // m_FontAssetReferenceLookup.Add(fontHashCode, fontAsset); + // } + // else + // { + // materialReferences[0].fontAsset = fontAsset; + // materialReferences[0].material = material; + // materialReferences[0].index = 0; + // materialReferences[0].referenceCount = 0; + // m_MaterialReferenceLookup[materialHashCode] = 0; + // } + // // Compute padding + // // TODO + + // m_countInternal = 1; + //} + + + + /// + /// + /// + //public void Clear() + //{ + // //m_currentIndex = 0; + // m_MaterialReferenceLookup.Clear(); + // m_SpriteAssetReferenceLookup.Clear(); + // m_FontAssetReferenceLookup.Clear(); + //} + + + /// + /// Function to clear the reference count for each of the material references. + /// + //public void ClearReferenceCount() + //{ + // m_countInternal = 0; + + // for (int i = 0; i < materialReferences.Length; i++) + // { + // if (materialReferences[i].fontAsset == null) + // return; + + // materialReferences[i].referenceCount = 0; + // } + //} + + } + + + + public struct MaterialReference + { + + public int index; + public TMP_FontAsset fontAsset; + public TMP_SpriteAsset spriteAsset; + public Material material; + public bool isDefaultMaterial; + public bool isFallbackMaterial; + public Material fallbackMaterial; + public float padding; + public int referenceCount; + + + /// + /// Constructor for new Material Reference. + /// + /// + /// + /// + /// + /// + public MaterialReference(int index, TMP_FontAsset fontAsset, TMP_SpriteAsset spriteAsset, Material material, float padding) + { + this.index = index; + this.fontAsset = fontAsset; + this.spriteAsset = spriteAsset; + this.material = material; + this.isDefaultMaterial = material.GetInstanceID() == fontAsset.material.GetInstanceID() ? true : false; + this.isFallbackMaterial = false; + this.fallbackMaterial = null; + this.padding = padding; + this.referenceCount = 0; + } + + + /// + /// Function to check if a certain font asset is contained in the material reference array. + /// + /// + /// + /// + public static bool Contains(MaterialReference[] materialReferences, TMP_FontAsset fontAsset) + { + int id = fontAsset.GetInstanceID(); + + for (int i = 0; i < materialReferences.Length && materialReferences[i].fontAsset != null; i++) + { + if (materialReferences[i].fontAsset.GetInstanceID() == id) + return true; + } + + return false; + } + + + /// + /// Function to add a new material reference and returning its index in the material reference array. + /// + /// + /// + /// + /// + /// + public static int AddMaterialReference(Material material, TMP_FontAsset fontAsset, MaterialReference[] materialReferences, Dictionary materialReferenceIndexLookup) + { + int materialID = material.GetInstanceID(); + + if (materialReferenceIndexLookup.TryGetValue(materialID, out int index)) + { + return index; + } + else + { + index = materialReferenceIndexLookup.Count; + + // Add new reference index + materialReferenceIndexLookup[materialID] = index; + + materialReferences[index].index = index; + materialReferences[index].fontAsset = fontAsset; + materialReferences[index].spriteAsset = null; + materialReferences[index].material = material; + materialReferences[index].isDefaultMaterial = materialID == fontAsset.material.GetInstanceID() ? true : false; + //materialReferences[index].padding = 0; + materialReferences[index].referenceCount = 0; + + return index; + } + } + + + /// + /// + /// + /// + /// + /// + /// + /// + public static int AddMaterialReference(Material material, TMP_SpriteAsset spriteAsset, MaterialReference[] materialReferences, Dictionary materialReferenceIndexLookup) + { + int materialID = material.GetInstanceID(); + + if (materialReferenceIndexLookup.TryGetValue(materialID, out int index)) + { + return index; + } + else + { + index = materialReferenceIndexLookup.Count; + + // Add new reference index + materialReferenceIndexLookup[materialID] = index; + + materialReferences[index].index = index; + materialReferences[index].fontAsset = materialReferences[0].fontAsset; + materialReferences[index].spriteAsset = spriteAsset; + materialReferences[index].material = material; + materialReferences[index].isDefaultMaterial = true; + //materialReferences[index].padding = 0; + materialReferences[index].referenceCount = 0; + + return index; + } + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Runtime/TMP_Asset.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Runtime/TMP_Asset.cs new file mode 100644 index 00000000..a0ff4971 --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Runtime/TMP_Asset.cs @@ -0,0 +1,26 @@ +using UnityEngine; + +namespace TMPro +{ + + // Base class inherited by the various TextMeshPro Assets. + [System.Serializable] + public class TMP_Asset : ScriptableObject + { + /// + /// HashCode based on the name of the asset. + /// + public int hashCode; + + /// + /// The material used by this asset. + /// + public Material material; + + /// + /// HashCode based on the name of the material assigned to this asset. + /// + public int materialHashCode; + + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Runtime/TMP_Character.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Runtime/TMP_Character.cs new file mode 100644 index 00000000..8fc161ec --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Runtime/TMP_Character.cs @@ -0,0 +1,51 @@ +using System; +using UnityEngine.TextCore; + +namespace TMPro +{ + /// + /// A basic element of text. + /// + [Serializable] + public class TMP_Character : TMP_TextElement + { + /// + /// Default constructor. + /// + public TMP_Character() + { + m_ElementType = TextElementType.Character; + this.scale = 1.0f; + } + + /// + /// Constructor for new character + /// + /// Unicode value. + /// Glyph + public TMP_Character(uint unicode, Glyph glyph) + { + m_ElementType = TextElementType.Character; + + this.unicode = unicode; + this.glyph = glyph; + this.glyphIndex = glyph.index; + this.scale = 1.0f; + } + + /// + /// Constructor for new character + /// + /// Unicode value. + /// Glyph index. + internal TMP_Character(uint unicode, uint glyphIndex) + { + m_ElementType = TextElementType.Character; + + this.unicode = unicode; + this.glyph = null; + this.glyphIndex = glyphIndex; + this.scale = 1.0f; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Runtime/TMP_CharacterInfo.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Runtime/TMP_CharacterInfo.cs new file mode 100644 index 00000000..e15c46af --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Runtime/TMP_CharacterInfo.cs @@ -0,0 +1,73 @@ +using UnityEngine; +using UnityEngine.TextCore; + +namespace TMPro +{ + public struct TMP_Vertex + { + public Vector3 position; + public Vector2 uv; + public Vector2 uv2; + public Vector2 uv4; + public Color32 color; + + //public Vector3 normal; + //public Vector4 tangent; + } + + /// + /// Structure containing information about individual text elements (character or sprites). + /// + public struct TMP_CharacterInfo + { + public char character; // Should be changed to an int to handle UTF 32 + /// + /// Index of the character in the raw string. + /// + public int index; // Index of the character in the input string. + public int stringLength; + public TMP_TextElementType elementType; + + public TMP_TextElement textElement; + public TMP_FontAsset fontAsset; + public TMP_SpriteAsset spriteAsset; + public int spriteIndex; + public Material material; + public int materialReferenceIndex; + public bool isUsingAlternateTypeface; + + public float pointSize; + + //public short wordNumber; + public int lineNumber; + //public short charNumber; + public int pageNumber; + + + public int vertexIndex; + public TMP_Vertex vertex_BL; + public TMP_Vertex vertex_TL; + public TMP_Vertex vertex_TR; + public TMP_Vertex vertex_BR; + + public Vector3 topLeft; + public Vector3 bottomLeft; + public Vector3 topRight; + public Vector3 bottomRight; + public float origin; + public float ascender; + public float baseLine; + public float descender; + + public float xAdvance; + public float aspectRatio; + public float scale; + public Color32 color; + public Color32 underlineColor; + public Color32 strikethroughColor; + public Color32 highlightColor; + public FontStyles style; + public bool isVisible; + //public bool isIgnoringAlignment; + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Runtime/TMP_ColorGradient.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Runtime/TMP_ColorGradient.cs new file mode 100644 index 00000000..0730adaf --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Runtime/TMP_ColorGradient.cs @@ -0,0 +1,68 @@ +using UnityEngine; +using System.Collections; + +namespace TMPro +{ + public enum ColorMode + { + Single, + HorizontalGradient, + VerticalGradient, + FourCornersGradient + } + + [System.Serializable] + public class TMP_ColorGradient : ScriptableObject + { + public ColorMode colorMode = ColorMode.FourCornersGradient; + + public Color topLeft; + public Color topRight; + public Color bottomLeft; + public Color bottomRight; + + const ColorMode k_DefaultColorMode = ColorMode.FourCornersGradient; + static readonly Color k_DefaultColor = Color.white; + + /// + /// Default Constructor which sets each of the colors as white. + /// + public TMP_ColorGradient() + { + colorMode = k_DefaultColorMode; + topLeft = k_DefaultColor; + topRight = k_DefaultColor; + bottomLeft = k_DefaultColor; + bottomRight = k_DefaultColor; + } + + /// + /// Constructor allowing to set the default color of the Color Gradient. + /// + /// + public TMP_ColorGradient(Color color) + { + colorMode = k_DefaultColorMode; + topLeft = color; + topRight = color; + bottomLeft = color; + bottomRight = color; + } + + /// + /// The vertex colors at the corners of the characters. + /// + /// Top left color. + /// Top right color. + /// Bottom left color. + /// Bottom right color. + public TMP_ColorGradient(Color color0, Color color1, Color color2, Color color3) + { + colorMode = k_DefaultColorMode; + this.topLeft = color0; + this.topRight = color1; + this.bottomLeft = color2; + this.bottomRight = color3; + } + } +} diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Runtime/TMP_CoroutineTween.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Runtime/TMP_CoroutineTween.cs new file mode 100644 index 00000000..bec1f54e --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Runtime/TMP_CoroutineTween.cs @@ -0,0 +1,246 @@ +using UnityEngine; +using UnityEngine.Events; +using System.Collections; + + +namespace TMPro +{ + // Base interface for tweeners, + // using an interface instead of + // an abstract class as we want the + // tweens to be structs. + internal interface ITweenValue + { + void TweenValue(float floatPercentage); + bool ignoreTimeScale { get; } + float duration { get; } + bool ValidTarget(); + } + + // Color tween class, receives the + // TweenValue callback and then sets + // the value on the target. + internal struct ColorTween : ITweenValue + { + public enum ColorTweenMode + { + All, + RGB, + Alpha + } + + public class ColorTweenCallback : UnityEvent { } + + private ColorTweenCallback m_Target; + private Color m_StartColor; + private Color m_TargetColor; + private ColorTweenMode m_TweenMode; + + private float m_Duration; + private bool m_IgnoreTimeScale; + + public Color startColor + { + get { return m_StartColor; } + set { m_StartColor = value; } + } + + public Color targetColor + { + get { return m_TargetColor; } + set { m_TargetColor = value; } + } + + public ColorTweenMode tweenMode + { + get { return m_TweenMode; } + set { m_TweenMode = value; } + } + + public float duration + { + get { return m_Duration; } + set { m_Duration = value; } + } + + public bool ignoreTimeScale + { + get { return m_IgnoreTimeScale; } + set { m_IgnoreTimeScale = value; } + } + + public void TweenValue(float floatPercentage) + { + if (!ValidTarget()) + return; + + var newColor = Color.Lerp(m_StartColor, m_TargetColor, floatPercentage); + + if (m_TweenMode == ColorTweenMode.Alpha) + { + newColor.r = m_StartColor.r; + newColor.g = m_StartColor.g; + newColor.b = m_StartColor.b; + } + else if (m_TweenMode == ColorTweenMode.RGB) + { + newColor.a = m_StartColor.a; + } + m_Target.Invoke(newColor); + } + + public void AddOnChangedCallback(UnityAction callback) + { + if (m_Target == null) + m_Target = new ColorTweenCallback(); + + m_Target.AddListener(callback); + } + + public bool GetIgnoreTimescale() + { + return m_IgnoreTimeScale; + } + + public float GetDuration() + { + return m_Duration; + } + + public bool ValidTarget() + { + return m_Target != null; + } + } + + // Float tween class, receives the + // TweenValue callback and then sets + // the value on the target. + internal struct FloatTween : ITweenValue + { + public class FloatTweenCallback : UnityEvent { } + + private FloatTweenCallback m_Target; + private float m_StartValue; + private float m_TargetValue; + + private float m_Duration; + private bool m_IgnoreTimeScale; + + public float startValue + { + get { return m_StartValue; } + set { m_StartValue = value; } + } + + public float targetValue + { + get { return m_TargetValue; } + set { m_TargetValue = value; } + } + + public float duration + { + get { return m_Duration; } + set { m_Duration = value; } + } + + public bool ignoreTimeScale + { + get { return m_IgnoreTimeScale; } + set { m_IgnoreTimeScale = value; } + } + + public void TweenValue(float floatPercentage) + { + if (!ValidTarget()) + return; + + var newValue = Mathf.Lerp(m_StartValue, m_TargetValue, floatPercentage); + m_Target.Invoke(newValue); + } + + public void AddOnChangedCallback(UnityAction callback) + { + if (m_Target == null) + m_Target = new FloatTweenCallback(); + + m_Target.AddListener(callback); + } + + public bool GetIgnoreTimescale() + { + return m_IgnoreTimeScale; + } + + public float GetDuration() + { + return m_Duration; + } + + public bool ValidTarget() + { + return m_Target != null; + } + } + + // Tween runner, executes the given tween. + // The coroutine will live within the given + // behaviour container. + internal class TweenRunner where T : struct, ITweenValue + { + protected MonoBehaviour m_CoroutineContainer; + protected IEnumerator m_Tween; + + // utility function for starting the tween + private static IEnumerator Start(T tweenInfo) + { + if (!tweenInfo.ValidTarget()) + yield break; + + var elapsedTime = 0.0f; + while (elapsedTime < tweenInfo.duration) + { + elapsedTime += tweenInfo.ignoreTimeScale ? Time.unscaledDeltaTime : Time.deltaTime; + var percentage = Mathf.Clamp01(elapsedTime / tweenInfo.duration); + tweenInfo.TweenValue(percentage); + yield return null; + } + tweenInfo.TweenValue(1.0f); + } + + public void Init(MonoBehaviour coroutineContainer) + { + m_CoroutineContainer = coroutineContainer; + } + + public void StartTween(T info) + { + if (m_CoroutineContainer == null) + { + Debug.LogWarning("Coroutine container not configured... did you forget to call Init?"); + return; + } + + StopTween(); + + if (!m_CoroutineContainer.gameObject.activeInHierarchy) + { + info.TweenValue(1.0f); + return; + } + + m_Tween = Start(info); + m_CoroutineContainer.StartCoroutine(m_Tween); + } + + public void StopTween() + { + if (m_Tween != null) + { + m_CoroutineContainer.StopCoroutine(m_Tween); + m_Tween = null; + } + } + } +} \ No newline at end of file diff --git a/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Runtime/TMP_DefaultControls.cs b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Runtime/TMP_DefaultControls.cs new file mode 100644 index 00000000..7bc6f97e --- /dev/null +++ b/KerbalVR/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Runtime/TMP_DefaultControls.cs @@ -0,0 +1,385 @@ +using UnityEngine; +using System.Collections; +using UnityEngine.UI; + + +namespace TMPro +{ + + public static class TMP_DefaultControls + { + public struct Resources + { + public Sprite standard; + public Sprite background; + public Sprite inputField; + public Sprite knob; + public Sprite checkmark; + public Sprite dropdown; + public Sprite mask; + } + + private const float kWidth = 160f; + private const float kThickHeight = 30f; + private const float kThinHeight = 20f; + private static Vector2 s_ThickElementSize = new Vector2(kWidth, kThickHeight); + private static Vector2 s_ThinElementSize = new Vector2(kWidth, kThinHeight); + //private static Vector2 s_ImageElementSize = new Vector2(100f, 100f); + private static Color s_DefaultSelectableColor = new Color(1f, 1f, 1f, 1f); + //private static Color s_PanelColor = new Color(1f, 1f, 1f, 0.392f); + private static Color s_TextColor = new Color(50f / 255f, 50f / 255f, 50f / 255f, 1f); + + + private static GameObject CreateUIElementRoot(string name, Vector2 size) + { + GameObject child = new GameObject(name); + RectTransform rectTransform = child.AddComponent(); + rectTransform.sizeDelta = size; + return child; + } + + static GameObject CreateUIObject(string name, GameObject parent) + { + GameObject go = new GameObject(name); + go.AddComponent(); + SetParentAndAlign(go, parent); + return go; + } + + private static void SetDefaultTextValues(TMP_Text lbl) + { + // Set text values we want across UI elements in default controls. + // Don't set values which are the same as the default values for the Text component, + // since there's no point in that, and it's good to keep them as consistent as possible. + lbl.color = s_TextColor; + lbl.fontSize = 14; + } + + private static void SetDefaultColorTransitionValues(Selectable slider) + { + ColorBlock colors = slider.colors; + colors.highlightedColor = new Color(0.882f, 0.882f, 0.882f); + colors.pressedColor = new Color(0.698f, 0.698f, 0.698f); + colors.disabledColor = new Color(0.521f, 0.521f, 0.521f); + } + + private static void SetParentAndAlign(GameObject child, GameObject parent) + { + if (parent == null) + return; + + child.transform.SetParent(parent.transform, false); + SetLayerRecursively(child, parent.layer); + } + + private static void SetLayerRecursively(GameObject go, int layer) + { + go.layer = layer; + Transform t = go.transform; + for (int i = 0; i < t.childCount; i++) + SetLayerRecursively(t.GetChild(i).gameObject, layer); + } + + // Actual controls + + public static GameObject CreateScrollbar(Resources resources) + { + // Create GOs Hierarchy + GameObject scrollbarRoot = CreateUIElementRoot("Scrollbar", s_ThinElementSize); + + GameObject sliderArea = CreateUIObject("Sliding Area", scrollbarRoot); + GameObject handle = CreateUIObject("Handle", sliderArea); + + Image bgImage = scrollbarRoot.AddComponent(); + bgImage.sprite = resources.background; + bgImage.type = Image.Type.Sliced; + bgImage.color = s_DefaultSelectableColor; + + Image handleImage = handle.AddComponent(); + handleImage.sprite = resources.standard; + handleImage.type = Image.Type.Sliced; + handleImage.color = s_DefaultSelectableColor; + + RectTransform sliderAreaRect = sliderArea.GetComponent(); + sliderAreaRect.sizeDelta = new Vector2(-20, -20); + sliderAreaRect.anchorMin = Vector2.zero; + sliderAreaRect.anchorMax = Vector2.one; + + RectTransform handleRect = handle.GetComponent(); + handleRect.sizeDelta = new Vector2(20, 20); + + Scrollbar scrollbar = scrollbarRoot.AddComponent(); + scrollbar.handleRect = handleRect; + scrollbar.targetGraphic = handleImage; + SetDefaultColorTransitionValues(scrollbar); + + return scrollbarRoot; + } + + public static GameObject CreateButton(Resources resources) + { + GameObject buttonRoot = CreateUIElementRoot("Button", s_ThickElementSize); + + GameObject childText = new GameObject("Text (TMP)"); + childText.AddComponent(); + SetParentAndAlign(childText, buttonRoot); + + Image image = buttonRoot.AddComponent(); + image.sprite = resources.standard; + image.type = Image.Type.Sliced; + image.color = s_DefaultSelectableColor; + + Button bt = buttonRoot.AddComponent