void SelectSimulatedReplicatorChildren()
        {
            var replicatorRow   = (ReplicatorRow)this;
            var sceneObject     = replicatorRow.BackingReplicator.transform;
            var simulatedObject = replicatorRow.SimulatedReplicator.transform;

            var simulatedMatches = CollectionPool <List <GameObject>, GameObject> .GetCollection();

            foreach (var proxy in simulatedObject.GetComponentsInChildren <Proxy>())
            {
                foreach (Transform child in proxy.transform)
                {
                    if (child.gameObject.activeInHierarchy)
                    {
                        simulatedMatches.Add(child.gameObject);
                    }
                }
            }

            RulesModule.FrameObject(sceneObject);

            // ReSharper disable once CoVariantArrayConversion
            Selection.objects = simulatedMatches.ToArray();
            CollectionPool <List <GameObject>, GameObject> .RecycleCollection(simulatedMatches);
        }
Esempio n. 2
0
        /// <summary>
        /// Adds the given Game Object to the current simulation and starts running its ISimulatable behaviours
        /// </summary>
        /// <param name="gameObject">The Game Object to add to simulation</param>
        public void AddSpawnedObjectToSimulation(GameObject gameObject)
        {
            if (gameObject.transform.parent == null && SimulatedContentRoot != null)
            {
                m_SimulationSceneModule.AddContentGameObject(gameObject);
                gameObject.transform.SetParent(SimulatedContentRoot.transform, true);
                gameObject.SetHideFlagsRecursively(SimulatedObjectHideFlags);
            }

            k_Subscribers.Clear();
            gameObject.GetComponentsInChildren(k_Subscribers);
            m_QuerySimulationModule.functionalityIsland.InjectPreparedFunctionality(k_Subscribers);

            // Because GameObjects may be created in Awake, AddSpawnedObjectToSimulation can be called recursively, thus
            // we cannot re-use the list of simulatables as it may be modified while iterating
            var simulatablesList = CollectionPool <List <ISimulatable>, ISimulatable> .GetCollection();

            gameObject.GetComponentsInChildren(simulatablesList);
            foreach (var simulatable in simulatablesList.Cast <MonoBehaviour>())
            {
                m_SpawnedSimulatableBehaviours.Add(simulatable);
                simulatable.StartRunInEditMode();
            }

            m_SpawnedSimulatableObjects.Add(gameObject);
            CollectionPool <List <ISimulatable>, ISimulatable> .RecycleCollection(simulatablesList);
        }
Esempio n. 3
0
        public void Initialize()
        {
            var cameraRig  = CameraUtils.GetCameraRig();
            var proxyTypes = CollectionPool <List <Type>, Type> .GetCollection();

            typeof(IProxy).GetImplementationsOfInterface(proxyTypes);
            foreach (var proxyType in proxyTypes)
            {
                var proxy = (IProxy)EditorXRUtils.CreateGameObjectWithComponent(proxyType, cameraRig, false);
                this.ConnectInterfaces(proxy);
                this.InjectFunctionalitySingle(proxy);
                var trackedObjectInput = m_DeviceInputModule.trackedObjectInput;
                if (trackedObjectInput == null)
                {
                    Debug.LogError("Device Input Module not initialized--trackedObjectInput is null");
                }

                proxy.trackedObjectInput = trackedObjectInput;
                proxy.activeChanged     += () => OnProxyActiveChanged(proxy);

                m_Proxies.Add(proxy);
            }

            CollectionPool <List <Type>, Type> .RecycleCollection(proxyTypes);
        }
Esempio n. 4
0
        void SpawnActions()
        {
            m_SpatialMenuData.Clear();
            var spatialMenuActions = new List <SpatialMenu.SpatialMenuElementContainer>();
            var spatialMenuData    = new SpatialMenu.SpatialMenuData("Actions", "Perform actions on selected object", spatialMenuActions);

            m_SpatialMenuData.Add(spatialMenuData);

            m_MenuActions.Clear();
            var actionTypes = CollectionPool <List <Type>, Type> .GetCollection();

            typeof(IAction).GetImplementationsOfInterface(actionTypes);
            foreach (var actionType in actionTypes)
            {
                // Don't treat vanilla actions or tool actions as first class actions
                if (actionType.IsNested || !typeof(MonoBehaviour).IsAssignableFrom(actionType))
                {
                    continue;
                }

                var action = EditorXRUtils.AddComponent(actionType, gameObject) as IAction;
                this.ConnectInterfaces(action);
                this.InjectFunctionalitySingle(action);

                var defaultActionAttribute = (ActionMenuItemAttribute)actionType.GetCustomAttributes(typeof(ActionMenuItemAttribute), false).FirstOrDefault();
                if (defaultActionAttribute != null)
                {
                    var actionMenuData = new ActionMenuData()
                    {
                        name        = defaultActionAttribute.name,
                        sectionName = defaultActionAttribute.sectionName,
                        priority    = defaultActionAttribute.priority,
                        action      = action,
                    };

                    m_MenuActions.Add(actionMenuData);
                }

                var spatialMenuAttribute = (SpatialMenuItemAttribute)actionType.GetCustomAttributes(typeof(SpatialMenuItemAttribute), false).FirstOrDefault();
                if (spatialMenuAttribute != null)
                {
                    spatialMenuActions.Add(new SpatialMenu.SpatialMenuElementContainer(spatialMenuAttribute.name, spatialMenuAttribute.description, (node) => action.ExecuteAction()));
                }

                m_Actions.Add(action);
            }

            CollectionPool <List <Type>, Type> .RecycleCollection(actionTypes);

            m_MenuActions.Sort((x, y) => y.priority.CompareTo(x.priority));
        }
        static AssetDeleteResult HandleFolderDelete(string path)
        {
            var files     = Directory.GetFiles(path, k_FileSearchPattern, SearchOption.AllDirectories);
            var remaining = files.ToList();

            foreach (var file in files)
            {
                var assetType = AssetDatabase.GetMainAssetTypeAtPath(file);
                if (assetType == typeof(MarsMarkerLibrary))
                {
                    remaining.Remove(file);
                    var marsMarkerLibrary = AssetDatabase.LoadAssetAtPath <MarsMarkerLibrary>(file);
                    HandleAssetDelete(marsMarkerLibrary, out var deletedPath);
                    if (!string.IsNullOrEmpty(deletedPath))
                    {
                        remaining.Remove(deletedPath);
                    }
                }
            }

            var remainingXrLibraries = CollectionPool <List <string>, string> .GetCollection();

            foreach (var file in remaining)
            {
                var assetType = AssetDatabase.GetMainAssetTypeAtPath(file);
                if (assetType == typeof(XRReferenceImageLibrary))
                {
                    remainingXrLibraries.Add(file);
                }
            }

            if (remainingXrLibraries.Count > 0)
            {
                var assetList = string.Join("\n", remainingXrLibraries);
                Debug.LogWarning($"Failed to delete {path} because it contains XR Reference Libraries needed to support MARS Marker Libraries which are not contained within. Delete the corresponding MARS marker libraries for the following assets\n{assetList}");
                return(AssetDeleteResult.DidNotDelete);
            }

            CollectionPool <List <string>, string> .RecycleCollection(remainingXrLibraries);

            return(AssetDeleteResult.DidNotDelete);
        }
        void SelectSimulatedGroupChildren()
        {
            var simulatedObjectsManager = ModuleLoaderCore.instance.GetModule <SimulatedObjectsManager>();
            var sceneObject             = ((ProxyRow)this).BackingObject.transform;
            var simulatedProxy          = simulatedObjectsManager.GetCopiedTransform(sceneObject);
            var group      = sceneObject.GetComponentInParent <ProxyGroup>();
            var sceneProxy = sceneObject.GetComponent <Proxy>();

            group.RepopulateChildList();
            var idx = group.IndexOfChild(sceneProxy);

            var simulatedMatches = CollectionPool <List <GameObject>, GameObject> .GetCollection();

            var parentReplicator = simulatedProxy.GetComponentInParent <Replicator>();

            foreach (var simGrp in parentReplicator.GetComponentsInChildren <ProxyGroup>())
            {
                var groupChildren = CollectionPool <List <Proxy>, Proxy> .GetCollection();

                simGrp.GetChildList(groupChildren);

                foreach (Transform child in groupChildren[idx].transform)
                {
                    if (child.gameObject.activeInHierarchy)
                    {
                        simulatedMatches.Add(child.gameObject);
                    }
                }

                CollectionPool <List <Proxy>, Proxy> .RecycleCollection(groupChildren);
            }

            RulesModule.FrameObject(sceneObject);

            // ReSharper disable once CoVariantArrayConversion
            Selection.objects = simulatedMatches.ToArray();
            CollectionPool <List <GameObject>, GameObject> .RecycleCollection(simulatedMatches);
        }
Esempio n. 7
0
        public static List <IEditingContext> GetEditingContextAssets()
        {
#if UNITY_EDITOR
            var availableContexts = new List <IEditingContext>();
            var contextTypes      = CollectionPool <List <Type>, Type> .GetCollection();

            typeof(IEditingContext).GetImplementationsOfInterface(contextTypes);
            var searchString = "t: " + string.Join(" t: ", contextTypes.Select(t => t.FullName).ToArray());
            CollectionPool <List <Type>, Type> .RecycleCollection(contextTypes);

            var assets = AssetDatabase.FindAssets(searchString);

            foreach (var asset in assets)
            {
                var assetPath = AssetDatabase.GUIDToAssetPath(asset);
                var context   = AssetDatabase.LoadMainAssetAtPath(assetPath) as IEditingContext;
                availableContexts.Add(context);
            }
#else
            var availableContexts = DefaultScriptReferences.GetEditingContexts();
#endif

            return(availableContexts);
        }
Esempio n. 8
0
        static SettingsProvider CreateSettingsProvider()
        {
            var contextNames = GetEditingContextNames();
            var context      = defaultContext;

            if (string.IsNullOrEmpty(settings.defaultContextName) && context != null)
            {
                settings.defaultContextName = context.name;
            }

            var selectedIndex = Array.IndexOf(contextNames, settings.defaultContextName);
            var provider      = new SettingsProvider("Project/EditorXR/Context Manager", SettingsScope.Project)
            {
                label      = "Context Manager",
                guiHandler = (searchContext) =>
                {
#if UNITY_EDITORXR_EDIT_MODE_SUPPORT
                    EditorGUILayout.LabelField("Global Settings", EditorStyles.boldLabel);

                    using (new EditorGUILayout.HorizontalScope())
                    {
                        using (var changed = new EditorGUI.ChangeCheckScope())
                        {
                            selectedIndex = EditorGUILayout.Popup("Default Context", selectedIndex, contextNames);
                            if (changed.changed)
                            {
                                settings.defaultContextName = contextNames[selectedIndex];
                                SaveProjectSettings(settings);
                                GUIUtility.ExitGUI();
                            }
                        }

                        const float resetButtonWidth = 40f;
                        if (GUILayout.Button("Reset", EditorStyles.miniButton, GUILayout.Width(resetButtonWidth)))
                        {
                            ResetProjectSettings();
                            selectedIndex = 0;
                        }
                    }

                    // Auto open an EditorXR context
                    const string title   = "Auto open";
                    const string tooltip = "Automatically open an EditorXR context when the HMD is being worn";

                    using (var change = new EditorGUI.ChangeCheckScope())
                    {
                        autoOpen = EditorGUILayout.Toggle(new GUIContent(title, tooltip), autoOpen);

                        if (change.changed)
                        {
                            OnAutoOpenStateChanged();
                        }

                        if (s_EnableXRFailed)
                        {
                            const float retryButtonWidth = 70f;
                            EditorGUILayout.HelpBox("Failed to initialize XR session. Check that your device and platform software are working properly.", MessageType.Warning);
                            if (GUILayout.Button("Retry", GUILayout.Width(retryButtonWidth)))
                            {
                                s_EnableXRFailed = false;
                                OnAutoOpenStateChanged();
                            }
                        }
                    }
#else
                    EditorGUILayout.HelpBox("EditorXR in Edit Mode requires legacy VR support, which was removed in Unity 2020.1. To use EditorXR in Edit Mode, you must use Unity 2019. To use EditorXR in Play Mode, add an EditingContextManager to your scene and install an XR Plugin.", MessageType.Warning);
#endif

                    var contextTypes = CollectionPool <List <Type>, Type> .GetCollection();

                    typeof(IEditingContext).GetImplementationsOfInterface(contextTypes);
                    foreach (var contextType in contextTypes)
                    {
                        var preferencesGUIMethod = contextType.GetMethod("PreferencesGUI", BindingFlags.Static | BindingFlags.NonPublic);
                        if (preferencesGUIMethod != null)
                        {
                            EditorGUILayout.Space();
                            EditorGUILayout.Space();
                            EditorGUILayout.LabelField(contextType.Name.Replace("Context", string.Empty), EditorStyles.boldLabel);
                            preferencesGUIMethod.Invoke(null, null);
                        }
                    }

                    CollectionPool <List <Type>, Type> .RecycleCollection(contextTypes);
                }
            };

            return(provider);
        }
        static void ImportEnvironment(string environmentName, string jsonText, string path,
                                      GameObject simulatedPlanePrefab, Material simulatedPlaneMaterial, Post postPrefab, MeshFilter meshPrefab,
                                      GameObject simulatedLightingPrefab, Action <UnityObject> callback)
        {
            var environment = SceneSerialization.FromJson <Environment>(jsonText);
            var height      = environment.height;
            var vertices    = environment.vertices;
            var center      = Vector3.zero;
            var posts       = CollectionPool <List <Post>, Post> .GetCollection();

            var  count    = vertices.Count;
            Post previous = null;

            foreach (var vertex in vertices)
            {
                var post = UnityObject.Instantiate(postPrefab);
                posts.Add(post);
                center += vertex;
                var postTransform = post.transform;
                postTransform.position = vertex;
                post.SetTopSphereHeight(height);

                if (previous != null)
                {
                    previous.Setup();
                    var previousPosition = previous.transform.position;
                    previous.UpdateWall(vertex, previousPosition - vertex, height);
                }

                previous = post;
            }

            if (count != 0)
            {
                center /= count;
            }

            var prefabRoot = new GameObject(environmentName).transform;
            var floorPlan  = new GameObject("Floor Plan").transform;

            prefabRoot.position = center;
            floorPlan.SetParent(prefabRoot, false);
            foreach (var post in posts)
            {
                post.transform.SetParent(floorPlan, true);
                var wall = post.Wall;
                if (wall != null)
                {
                    wall.SetParent(floorPlan, true);
                }
            }

            var planesRoot = new GameObject("Planes").transform;

            planesRoot.SetParent(prefabRoot, false);
            foreach (var plane in environment.planes)
            {
                var synthesizedPlane = ((GameObject)PrefabUtility.InstantiatePrefab(simulatedPlanePrefab, planesRoot)).GetComponent <SynthesizedPlane>();
                synthesizedPlane.transform.SetWorldPose(plane.pose);
                synthesizedPlane.SetMRPlaneData(plane.vertices, plane.center, plane.extents);
                synthesizedPlane.transform.SetParent(planesRoot, true);
                var renderer = synthesizedPlane.GetComponentInChildren <Renderer>();
                renderer.AddMaterial(simulatedPlaneMaterial);
            }

            var meshCapture = environment.MeshCapture;

            if (meshCapture.Meshes.Count > 0)
            {
                var meshesRoot = new GameObject("Meshes").transform;
                meshesRoot.SetParent(prefabRoot, false);
                var meshPath = EditorUtility.SaveFilePanelInProject(k_SaveMeshDialogTitle, environmentName, "asset", string.Empty);
                var index    = 0;
                foreach (var segment in meshCapture.Meshes)
                {
                    var meshFilter = UnityObject.Instantiate(meshPrefab, meshesRoot);
                    var mesh       = new Mesh {
                        name = $"Mesh Segment {index}"
                    };
                    mesh.SetVertices(segment.Vertices);
                    mesh.SetIndices(segment.Indices, MeshTopology.Triangles, 0);
                    mesh.SetNormals(segment.Normals);
                    meshFilter.transform.SetWorldPose(segment.Pose);
                    meshFilter.sharedMesh = mesh;
                    if (index == 0)
                    {
                        AssetDatabase.CreateAsset(mesh, meshPath);
                        AssetDatabase.SetMainObject(mesh, meshPath);
                    }
                    else
                    {
                        AssetDatabase.AddObjectToAsset(mesh, meshPath);
                    }

                    index++;
                }

                AssetDatabase.SaveAssets();
            }

            var environmentBounds    = BoundsUtils.GetBounds(prefabRoot);
            var prefabRootGameObject = prefabRoot.gameObject;
            var environmentSettings  = prefabRootGameObject.AddComponent <MARSEnvironmentSettings>();
            var environmentInfo      = environmentSettings.EnvironmentInfo;

            environmentInfo.EnvironmentBounds = environmentBounds;
            center = environmentBounds.center;
            var extents = environmentBounds.extents * 0.9f; // Reduce offset to avoid sim starting pose warning

            environmentInfo.DefaultCameraPivot = center;
            var cameraPose = new Pose(center + extents, Quaternion.LookRotation(-extents));

            environmentInfo.DefaultCameraWorldPose = cameraPose;
            environmentInfo.DefaultCameraSize      = environmentBounds.size.magnitude;
            environmentSettings.SetSimulationStartingPose(cameraPose, false);
            environmentSettings.UpdatePrefabInfo();
            UnityObject.Instantiate(simulatedLightingPrefab, prefabRoot);

            var prefab = PrefabUtility.SaveAsPrefabAssetAndConnect(prefabRootGameObject, path, InteractionMode.AutomatedAction);

            UnityObject.DestroyImmediate(prefabRootGameObject);
            AssetDatabase.SetLabels(prefab, new[] { MARSEnvironmentManager.EnvironmentLabel });
            ModuleLoaderCore.instance.GetModule <MARSEnvironmentManager>().UpdateSimulatedEnvironmentCandidates();
            callback(prefab);

            CollectionPool <List <Post>, Post> .RecycleCollection(posts);
        }