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);
        }
Пример #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);
        }
Пример #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);
        }
Пример #4
0
        public ObjectFaceF InitMember(IList <Vector3> vertices, IList <int> triangles)
        {
            if (weak_faceFs != null)
            {
                weak_faceFs.Dispose();
            }
            weak_faceFs = CollectionPool <FaceF> .ListCell.Create();

            for (int i = 0; i + 2 < triangles.Count; i += 3)
            {
                var faceF = ObjectPool <FaceF> .Create(initFacef, construct);

                weak_faceFs.Add(faceF);

                void initFacef(FaceF cell) => cell.InitMember(
                    vertices[triangles[i]],
                    vertices[triangles[i + 1]],
                    vertices[triangles[i + 2]]);
                FaceF construct() => new FaceF(
                    vertices[triangles[i]],
                    vertices[triangles[i + 1]],
                    vertices[triangles[i + 2]]);
            }
            disposedValue = false;
            return(this);
        }
Пример #5
0
        public FaceF InitMember(Vector3 p1, Vector3 p2, Vector3 p3)
        {
            if (weak_vertices != null)
            {
                weak_vertices.Dispose();
            }
            weak_vertices = CollectionPool <Vector3> .ListCell.Create(p1, p2, p3);

            PlaneNormal     = Vector3.Cross(p2 - p1, p3 - p1).normalized;
            DisOrigin2plane = Vector3.Dot(PlaneNormal, p1);
            disposedValue   = false;
            return(this);
        }
Пример #6
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));
        }
Пример #7
0
        private bool disposedValue = false; // 要检测冗余调用

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    // TODO: 释放托管状态(托管对象)。
                    weak_vertices.Dispose();
                    weak_vertices = null;
                    ObjectPool <FaceF> .Recycle(this);
                }
                // TODO: 释放未托管的资源(未托管的对象)并在以下内容中替代终结器。
                // TODO: 将大型字段设置为 null。
                root = null;

                disposedValue = true;
            }
        }
        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);
        }
Пример #9
0
        /// <summary>
        /// Creates a new package instance
        /// </summary>
        public PackageMeta()
        {
            this.dependencies = CollectionPool <Dictionary <PackageId, PackageVersion>, PackageId, PackageVersion> .Get();

            this.references = CollectionPool <Dictionary <PackageId, PackageVersion>, PackageId, PackageVersion> .Get();

            this.platform = CollectionPool <HashSet <string>, string> .Get();

            this.architecture = CollectionPool <HashSet <PlatformTarget>, PlatformTarget> .Get();

            this.files = CollectionPool <HashSet <string>, string> .Get();

            this.tags = CollectionPool <HashSet <string>, string> .Get();

            this.maintainer = CollectionPool <HashSet <Identity>, Identity> .Get();

            this.events = CollectionPool <Dictionary <string, string>, string, string> .Get();

            this.parameter = CollectionPool <Dictionary <string, string>, string, string> .Get();
        }
        public bool TryParseValue(Type targetType, object value, out object result)
        {
            JsonNode node = (value as JsonNode);

            if (node != null && node.Type == JsonNodeType.Object)
            {
                Type[]   genericArgs = targetType.GetGenericArguments();
                Type     functorType = typeof(Func <, ,>).MakeGenericType(genericArgs[0], genericArgs[1], targetType);
                Delegate creator     = functorType.GetCreator(targetType);

                List <object> items = CollectionPool <List <object>, object> .Get();

                try
                {
                    node = node.Child;
                    while (node != null)
                    {
                        if (node.Type > JsonNodeType.Array)
                        {
                            object k, v; if (node.Name.TryCast(genericArgs[0], out k) && k != null && node.RawValue.TryCast(genericArgs[1], out v) && v != null)
                            {
                                items.Add(creator.DynamicInvoke(k, v));
                            }
                        }
                        node = node.Next;
                    }
                    result = items.ToArray();
                    return(true);
                }
                finally
                {
                    CollectionPool <List <object>, object> .Return(items);
                }
            }
            else
            {
                result = null;
                return(false);
            }
        }
Пример #11
0
        private bool disposedValue = false; // 要检测冗余调用

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    // TODO: 释放托管状态(托管对象)。
                    for (int i = 0; i < weak_faceFs.Count; i++)
                    {
                        weak_faceFs[i].Dispose();
                    }
                    weak_faceFs.Dispose();
                    weak_faceFs = null;
                    ObjectPool <ObjectFaceF> .Recycle(this);
                }

                // TODO: 释放未托管的资源(未托管的对象)并在以下内容中替代终结器。
                // TODO: 将大型字段设置为 null。

                disposedValue = true;
            }
        }
Пример #12
0
        /// <summary>
        /// Constructs a Object3d object based on a solid file.
        /// </summary>
        /// <param name="solid">solid used to construct the Object3d object</param>
        public Object3D(Solid solid)
        {
            var verticesPoints = CollectionPool <Vector3Double> .ListCell.Create();

            solid.GetVertices(verticesPoints);

            var indices = CollectionPool <int> .ListCell.Create();

            solid.GetTriangles(indices);

            using (var vsCache = CollectionPool <Vertex> .ListCell.Create())
            {
                //create vertices
                m_vertices = CollectionPool <Vertex> .ListCell.Create();

                for (int i = 0; i < verticesPoints.Count; i++)
                {
                    var vertex = AddVertex(verticesPoints[i], Status.UNKNOWN);
                    vsCache.Add(vertex);
                }

                //create faces
                m_faces = CollectionPool <Face> .ListCell.Create();

                for (int i = 0; i < indices.Count; i += 3)
                {
                    var v1 = vsCache[indices[i]];
                    var v2 = vsCache[indices[i + 1]];
                    var v3 = vsCache[indices[i + 2]];
                    AddFace(v1, v2, v3);
                }
            }

            //create bound
            m_bound = new Bound(verticesPoints);
            indices.Dispose();
            verticesPoints.Dispose();
        }
Пример #13
0
        public void Dispose()
        {
            CollectionPool <Dictionary <PackageId, PackageVersion>, PackageId, PackageVersion> .Return(dependencies);

            dependencies = null;

            CollectionPool <Dictionary <PackageId, PackageVersion>, PackageId, PackageVersion> .Return(references);

            references = null;

            CollectionPool <HashSet <string>, string> .Return(platform);

            platform = null;

            CollectionPool <HashSet <PlatformTarget>, PlatformTarget> .Return(architecture);

            architecture = null;

            CollectionPool <HashSet <string>, string> .Return(files);

            files = null;

            CollectionPool <HashSet <string>, string> .Return(tags);

            tags = null;

            CollectionPool <HashSet <Identity>, Identity> .Return(maintainer);

            maintainer = null;

            CollectionPool <Dictionary <string, string>, string, string> .Return(events);

            events = null;

            CollectionPool <Dictionary <string, string>, string, string> .Return(parameter);

            parameter = null;
        }
        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);
        }
Пример #15
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);
        }
        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);
        }
Пример #17
0
        public static void Init()
        {
            CostTypeDef costType_ItemFraction = new CostTypeDef();

            costType_ItemFraction.costStringFormatToken = "COST_MYSTICSITEMS_PERCENTAGEITEMS_FORMAT";
            costType_ItemFraction.isAffordable          = delegate(CostTypeDef costTypeDef2, CostTypeDef.IsAffordableContext context)
            {
                CharacterBody body = context.activator.gameObject.GetComponent <CharacterBody>();
                if (body)
                {
                    Inventory inventory = body.inventory;
                    if (inventory)
                    {
                        int       totalItemCount = 0;
                        ItemIndex itemIndex      = 0;
                        ItemIndex itemCount      = (ItemIndex)ItemCatalog.itemCount;
                        while (itemIndex < itemCount)
                        {
                            int thisItemCount = inventory.GetItemCount(itemIndex);
                            if (thisItemCount > 0)
                            {
                                ItemDef itemDef = ItemCatalog.GetItemDef(itemIndex);
                                if (itemDef.canRemove)
                                {
                                    totalItemCount += inventory.GetItemCount(itemIndex);
                                }
                            }
                            itemIndex++;

                            int itemsToTake = Mathf.FloorToInt(totalItemCount * Mathf.Clamp01(context.cost / 100f));
                            if (itemsToTake > 0)
                            {
                                return(true);
                            }
                        }
                    }
                }
                return(false);
            };
            costType_ItemFraction.payCost = delegate(CostTypeDef costTypeDef2, CostTypeDef.PayCostContext context)
            {
                if (context.activatorBody)
                {
                    Inventory inventory = context.activatorBody.inventory;
                    if (inventory)
                    {
                        List <ItemIndex> itemsToTake = CollectionPool <ItemIndex, List <ItemIndex> > .RentCollection();

                        WeightedSelection <ItemIndex> weightedSelection      = new WeightedSelection <ItemIndex>(8);
                        WeightedSelection <ItemIndex> weightedSelectionScrap = new WeightedSelection <ItemIndex>(8);
                        int totalItemCount = 0;
                        // Populate weighted selections with items from the inventory (weight is equal to the item count)
                        foreach (ItemIndex itemIndex in ItemCatalog.allItems)
                        {
                            if (itemIndex != context.avoidedItemIndex)
                            {
                                int itemCount = inventory.GetItemCount(itemIndex);
                                if (itemCount > 0)
                                {
                                    ItemDef itemDef = ItemCatalog.GetItemDef(itemIndex);
                                    if (itemDef.canRemove)
                                    {
                                        (itemDef.ContainsTag(ItemTag.Scrap) ? weightedSelectionScrap : weightedSelection).AddChoice(itemIndex, (float)itemCount);
                                        totalItemCount += itemCount;
                                    }
                                }
                            }
                        }
                        int halfTotalItemCount = Mathf.FloorToInt(totalItemCount * Mathf.Clamp01(context.cost / 100f));
                        // Take choices from the weighted selections and put them into the final list, until we take enough items
                        TakeItemsFromWeightedSelection(weightedSelectionScrap, ref context, ref itemsToTake, halfTotalItemCount);
                        TakeItemsFromWeightedSelection(weightedSelection, ref context, ref itemsToTake, halfTotalItemCount);
                        // Unused shop terminal behaviour? If we didn't take enough items, and the purchasable is a shop terminal choice, add the choice's item index as remaining items to take
                        for (int i = itemsToTake.Count; i < halfTotalItemCount; i++)
                        {
                            itemsToTake.Add(context.avoidedItemIndex);
                        }
                        // Remove the items from the interactor's inventory and add them to the pay context results
                        for (int j = 0; j < itemsToTake.Count; j++)
                        {
                            ItemIndex itemIndex2 = itemsToTake[j];
                            context.results.itemsTaken.Add(itemIndex2);
                            inventory.RemoveItem(itemIndex2, 1);
                        }
                        CollectionPool <ItemIndex, List <ItemIndex> > .ReturnCollection(itemsToTake);
                    }
                }
            };
            costType_ItemFraction.colorIndex = ColorCatalog.ColorIndex.Tier1Item;
            CostTypeCreation.CreateCostType(new CostTypeCreation.CustomCostTypeInfo
            {
                costTypeDef = costType_ItemFraction,
                onRegister  = (costTypeIndex) => {
                    if (OnItemFractionCostTypeRegister != null)
                    {
                        OnItemFractionCostTypeRegister(costTypeIndex);
                    }
                }
            });
            On.RoR2.Language.GetLocalizedFormattedStringByToken += (orig, self, token, args) =>
            {
                if (token == costType_ItemFraction.costStringFormatToken)
                {
                    return(orig(self, "COST_ITEM_FORMAT", new object[] { args[0].ToString() + "%" }));
                }
                return(orig(self, token, args));
            };
        }
Пример #18
0
            /*public void OnTakeDamageServer(DamageReport damageReport)
             * {
             *  //Here we apply damage to the link found on SearchForLink
             *  if (!NetworkServer.active || !hasLinkTarget)
             *  {
             #if DEBUG
             *      TurboEdition._logger.LogWarning("LinkComponent has no output link or NetworkServer is not active!");
             #endif
             *      return;
             *  }
             *  DamageInfo damageInfo = new DamageInfo
             *  {
             *      attacker = damageReport.attacker,
             *      inflictor = base.gameObject,
             *      position = damageReport.attacker.transform.position,
             *      crit = damageReport.attackerBody.RollCrit(), //Isn't this too much? Who are we refering to? Previous link or the player?
             *      damage = damageReport.damageInfo.damage,
             *      damageColorIndex = DamageColorIndex.Item,
             *      force = Vector3.zero, //Wouldn't it be funny if we set it to non-zero?
             *      procCoefficient = 0f, //See: RandomKill line 131
             *      damageType = DamageType.Generic, //Thinkan about nonlethal
             *      procChainMask = default(ProcChainMask)
             *  };
             #if DEBUG
             *  TurboEdition._logger.LogWarning("LinkComponent owner got damaged and has output, relaying a new damageInfo.");
             #endif
             *  this.hasLinkTarget.TakeDamage(damageInfo);
             * }*/

            private void SearchForLink()
            {
                List <HurtBox> hurtBoxList = CollectionPool <HurtBox, List <HurtBox> > .RentCollection();         //Use these to store the sphere search targets that got found

                List <Transform> transformList = CollectionPool <Transform, List <Transform> > .RentCollection(); //Use this to store the transforms of the targets

                //You might say, why not instead of storing two lists you store one and you replace the transforms list with hurtbox and you just go hurtbox by hurtbox getting the transforms? Check around line 468, transforms can be either from the hurtbox or the body if null.

                if (ownerBody.HasBuff(linkedBuff)) //This previously used networkedBodyAttachment.attachedBody
                {
#if DEBUG
                    TurboEdition._logger.LogWarning("LinkComponent body has the correct debuff, trying to find a match.");
#endif
                    this.SearchForTargets(hurtBoxList);
                }
                int i = 0;
                while (i < hurtBoxList.Count)
                {
#if DEBUG
                    TurboEdition._logger.LogWarning("LinkComponent searching for a link (" + (i + 1) + ") in a list out of " + hurtBoxList.Count);
#endif
                    HurtBox currentHurtbox = hurtBoxList[i];
                    var     externalLink   = currentHurtbox.healthComponent.body.GetComponentInChildren <LinkComponent>(); //we get the link component of whatever we are on rn
                    if (!externalLink)
                    {
                        //They dont have a linkComponent, meaning they aren't debuffed and we don't want to do anything with them
#if DEBUG
                        TurboEdition._logger.LogWarning("LinkComponent, match doesn't have LinkComponent, ignoring.");
#endif
                        i++;
                        continue;
                    }
                    if ((!currentHurtbox || !currentHurtbox.healthComponent || !currentHurtbox.healthComponent.alive) /*|| currentHurtbox.GetComponentInChildren<LinkComponent>().hasLinkTarget*/) //Commenting this last part because thats the output link, shouldnt be affect input.
                    {
                        //This means it either has no hurtboxes, no health component, not alive, or is already linked.
#if DEBUG
                        TurboEdition._logger.LogWarning("LinkComponent, match doesn't have a hurtbox, a HealthComponent, or is already dead, ignoring.");
#endif
                        i++;
                        continue;
                    }
                    HealthComponent hcHurtBoxToLink = currentHurtbox.healthComponent;
                    //We make sure we aren't linking ourselves
                    if (!(hcHurtBoxToLink.body == ownerBody))
                    {
                        if (!tetheredHurtBoxList.Contains(currentHurtbox))
                        {
                            tetheredHurtBoxList.Add(currentHurtbox); Transform transform = hcHurtBoxToLink.body.coreTransform ?? currentHurtbox.transform; transformList.Add(transform);
                        }
                        if (!externalLink.tetheredHurtBoxList.Contains(ownerBody.mainHurtBox))
                        {
                            externalLink.tetheredHurtBoxList.Add(ownerBody.mainHurtBox);
                        }
#if DEBUG
                        TurboEdition._logger.LogWarning("LinkComponent, found link, adding " + currentHurtbox + " to " + tetheredHurtBoxList);
#endif
                        //We also make sure we aren't linking something that is already tethered to avoid drawing two lines
                        if (!externalLink.tetheredHurtBoxList.Contains(ownerBody.mainHurtBox)) //should be transformlist?
                        {
                            //Get the hurtbox transform we are affecting, else the body transform

#if DEBUG
                            TurboEdition._logger.LogWarning("LinkComponent, found link that wasn't linked to ours with transform: " + transform);
#endif
                        }
                    }
                    if (transformList.Count < 1)
                    {
#if DEBUG
                        TurboEdition._logger.LogWarning("LinkComponent, transformList doesn't have the needed amount of elements, searching for more.");
#endif
                        i++;
                        continue;
                    }
                    this.isLinkedToAtLeastOneObject = (transformList.Count > 0);
                    if (this.tetherVfxOrigin)
                    {
#if DEBUG
                        TurboEdition._logger.LogWarning("LinkComponent, tetherVfxOrigin exists, setting transforms from " + transformList + " with count " + transformList.Count);
#endif
                        this.tetherVfxOrigin.SetTetheredTransforms(transformList);
                    }
                    if (this.activeVfx)
                    {
#if DEBUG
                        TurboEdition._logger.LogWarning("LinkComponent, activeVfx exists, changing enabled/disabled!");
#endif
                        this.activeVfx.SetActive(isLinkedToAtLeastOneObject);
                    }
                    CollectionPool <Transform, List <Transform> > .ReturnCollection(transformList);

                    CollectionPool <HurtBox, List <HurtBox> > .ReturnCollection(hurtBoxList);
                }
#if DEBUG
                TurboEdition._logger.LogWarning("LinkComponent, couldn't find match, what a shame!");
#endif
            }
Пример #19
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);
        }