private void RefreshPickupables()
    {
        if (pickupablesDirty)
        {
            duplicants.Clear();
            ListPool <ScenePartitionerEntry, LogicDuplicantSensor> .PooledList pooledList = ListPool <ScenePartitionerEntry, LogicDuplicantSensor> .Allocate();

            GameScenePartitioner.Instance.GatherEntries(pickupableExtents.x, pickupableExtents.y, pickupableExtents.width, pickupableExtents.height, GameScenePartitioner.Instance.pickupablesLayer, pooledList);
            int cell_a = Grid.PosToCell(this);
            for (int i = 0; i < pooledList.Count; i++)
            {
                Pickupable pickupable     = pooledList[i].obj as Pickupable;
                int        pickupableCell = GetPickupableCell(pickupable);
                int        cellRange      = Grid.GetCellRange(cell_a, pickupableCell);
                if (IsPickupableRelevantToMyInterestsAndReachable(pickupable) && cellRange <= pickupRange)
                {
                    duplicants.Add(pickupable);
                }
            }
            SetState(duplicants.Count > 0);
            pickupablesDirty = false;
        }
    }
コード例 #2
0
    protected override void OnSpawn()
    {
        base.OnSpawn();
        RegisterInGrid(true);
        SetGridRestrictions(null, DefaultPermission);
        foreach (KeyValuePair <Ref <KPrefabID>, Permission> savedPermission in savedPermissions)
        {
            SetGridRestrictions(savedPermission.Key.Get(), savedPermission.Value);
        }
        ListPool <Tuple <MinionAssignablesProxy, Permission>, AccessControl> .PooledList pooledList = ListPool <Tuple <MinionAssignablesProxy, Permission>, AccessControl> .Allocate();

        for (int num = savedPermissions.Count - 1; num >= 0; num--)
        {
            KPrefabID kPrefabID = savedPermissions[num].Key.Get();
            if ((Object)kPrefabID != (Object)null)
            {
                MinionIdentity component = kPrefabID.GetComponent <MinionIdentity>();
                if ((Object)component != (Object)null)
                {
                    pooledList.Add(new Tuple <MinionAssignablesProxy, Permission>(component.assignableProxy.Get(), savedPermissions[num].Value));
                    savedPermissions.RemoveAt(num);
                    ClearGridRestrictions(kPrefabID);
                }
            }
        }
        foreach (Tuple <MinionAssignablesProxy, Permission> item in pooledList)
        {
            SetPermission(item.first, item.second);
        }
        pooledList.Recycle();
        SetStatusItem();
    }
コード例 #3
0
        /// <summary>
        /// Refreshes the rocket modules on this object.
        /// </summary>
        private void RefreshRocketModules()
        {
            string moduleName = null;
            var    rocketInterface = lastSelection.rocketInterface;
            var    parent = sis.rocketStatusContainer.Content.gameObject;
            var    text = CACHED_BUILDER;
            var    allModules = rocketInterface.ClusterModules;
            int    count = 0, n = allModules.Count;
            var    allCargoBays = ListPool <CargoBayCluster, RocketSimpleInfoPanel> .
                                  Allocate();

            setInactive.UnionWith(rocketLabels);
            rocketLabels.Clear();
            // Iterates the rocket again, but needs to be done after the engine stats
            for (int i = 0; i < n; i++)
            {
                var module = allModules[i].Get();
                if (module != null)
                {
                    if (module.TryGetComponent(out ArtifactModule artModule))
                    {
                        var label = GetStorageLabel(parent, "artifactModule_" + count.
                                                    ToString());
                        var occupant = artModule.Occupant;
                        count++;
                        if (moduleName == null)
                        {
                            moduleName = artModule.GetProperName();
                        }
                        text.Clear().Append(moduleName).Append(": ");
                        if (occupant != null)
                        {
                            text.Append(occupant.GetProperName());
                        }
                        else
                        {
                            text.Append(ROCKETS.ARTIFACT_MODULE.EMPTY);
                        }
                        label.text.SetText(text);
                        label.FreezeIfMatch(1, true);
                        label.SetAllowDrop(false, null, artModule.Occupant);
                        rocketLabels.Add(label);
                    }
                    else if (module.TryGetComponent(out CargoBayCluster cargoBay))
                    {
                        allCargoBays.Add(cargoBay);
                    }
                }
            }
            if (allCargoBays.Count > 0)
            {
                RefreshCargo(parent, allCargoBays);
            }
            allCargoBays.Recycle();
            // Only turn off the things that are gone
            setInactive.ExceptWith(rocketLabels);
            foreach (var inactive in setInactive)
            {
                inactive.SetActive(false);
            }
            setInactive.Clear();
        }
    public void Iterate <IteratorType>(int x, int y, int width, int height, ScenePartitionerLayer layer, ref IteratorType iterator) where IteratorType : Iterator
    {
        ListPool <ScenePartitionerEntry, GameScenePartitioner> .PooledList pooledList = ListPool <ScenePartitionerEntry, GameScenePartitioner> .Allocate();

        Instance.GatherEntries(x, y, width, height, layer, pooledList);
        for (int i = 0; i < ((List <ScenePartitionerEntry>)pooledList).Count; i++)
        {
            ScenePartitionerEntry scenePartitionerEntry = ((List <ScenePartitionerEntry>)pooledList)[i];
            iterator.Iterate(scenePartitionerEntry.obj);
        }
        pooledList.Recycle();
    }
コード例 #5
0
    private void GetObjectUnderCursor2D <T>(List <Intersection> intersections, Func <T, bool> condition, int layer_mask) where T : MonoBehaviour
    {
        Camera  main      = Camera.main;
        Vector3 mousePos  = KInputManager.GetMousePos();
        float   x         = mousePos.x;
        Vector3 mousePos2 = KInputManager.GetMousePos();
        float   y         = mousePos2.y;
        Vector3 position  = main.transform.GetPosition();
        Vector3 position2 = new Vector3(x, y, 0f - position.z);
        Vector3 pos       = main.ScreenToWorldPoint(position2);
        Vector2 pos2      = new Vector2(pos.x, pos.y);

        if ((UnityEngine.Object)hoverOverride != (UnityEngine.Object)null)
        {
            intersections.Add(new Intersection
            {
                component = hoverOverride,
                distance  = -100f
            });
        }
        int cell = Grid.PosToCell(pos);

        if (Grid.IsValidCell(cell) && Grid.IsVisible(cell))
        {
            Game.Instance.statusItemRenderer.GetIntersections(pos2, intersections);
            ListPool <ScenePartitionerEntry, SelectTool> .PooledList pooledList = ListPool <ScenePartitionerEntry, SelectTool> .Allocate();

            int x2 = 0;
            int y2 = 0;
            Grid.CellToXY(cell, out x2, out y2);
            GameScenePartitioner.Instance.GatherEntries(x2, y2, 1, 1, GameScenePartitioner.Instance.collisionLayer, pooledList);
            foreach (ScenePartitionerEntry item in (List <ScenePartitionerEntry>)pooledList)
            {
                KCollider2D kCollider2D = item.obj as KCollider2D;
                if (!((UnityEngine.Object)kCollider2D == (UnityEngine.Object)null) && kCollider2D.Intersects(new Vector2(pos.x, pos.y)))
                {
                    T val = kCollider2D.GetComponent <T>();
                    if ((UnityEngine.Object)val == (UnityEngine.Object)null)
                    {
                        val = kCollider2D.GetComponentInParent <T>();
                    }
                    if (!((UnityEngine.Object)val == (UnityEngine.Object)null) && ((1 << val.gameObject.layer) & layer_mask) != 0 && !((UnityEngine.Object)val == (UnityEngine.Object)null) && (condition == null || condition(val)))
                    {
                        Vector3 position3 = val.transform.GetPosition();
                        float   num       = position3.z - pos.z;
                        bool    flag      = false;
                        for (int i = 0; i < intersections.Count; i++)
                        {
                            Intersection value = intersections[i];
                            if ((UnityEngine.Object)value.component.gameObject == (UnityEngine.Object)val.gameObject)
                            {
                                value.distance   = Mathf.Min(value.distance, num);
                                intersections[i] = value;
                                flag             = true;
                                break;
                            }
                        }
                        if (!flag)
                        {
                            intersections.Add(new Intersection
                            {
                                component = val,
                                distance  = num
                            });
                        }
                    }
                }
            }
            pooledList.Recycle();
        }
    }
コード例 #6
0
        static IEnumerable <List <DenormalizedRecord> > denormalizedRecords(string newClientContent, Binder errorRecordBinder, ILogger log)
        {
            var outgoingList = ListPool <DenormalizedRecord> .Allocate();

            outgoingList.Capacity = 450;
            var sizeOfListItems = 0;

            try
            {
                NSGFlowLogRecords logs = JsonConvert.DeserializeObject <NSGFlowLogRecords>(newClientContent);

                foreach (var record in logs.records)
                {
                    float version = record.properties.Version;

                    foreach (var outerFlow in record.properties.flows)
                    {
                        foreach (var innerFlow in outerFlow.flows)
                        {
                            foreach (var flowTuple in innerFlow.flowTuples)
                            {
                                var tuple = new NSGFlowLogTuple(flowTuple, version);

                                var denormalizedRecord = new DenormalizedRecord(
                                    record.properties.Version,
                                    record.time,
                                    record.category,
                                    record.operationName,
                                    record.resourceId,
                                    outerFlow.rule,
                                    innerFlow.mac,
                                    tuple);

                                var sizeOfDenormalizedRecord = denormalizedRecord.GetSizeOfJSONObject();

                                //for Event hub binding fork  -- start
                                // Event hub basic message size is 256KB and the 'if' statement below ensures that list does not exceed size this size for Eventhub

                                string outputBinding = Util.GetEnvironmentVariable("outputBinding");

                                if (outputBinding == "eventhub")
                                {
                                    if (sizeOfListItems > 120) // this will chunk below 256KB : this is ideal sample message size. Feel free to go maximum till 150 : smaller values will create lot of outbound connections.
                                    {
                                        yield return(outgoingList);

                                        outgoingList.Clear();
                                        sizeOfListItems = 0;
                                    }
                                    outgoingList.Add(denormalizedRecord);
                                    sizeOfListItems += 1;
                                }

                                //for Event hub binding fork  -- end
                                //other output bindings

                                else if (sizeOfListItems + sizeOfDenormalizedRecord > MAXTRANSMISSIONSIZE + 20)
                                {
                                    yield return(outgoingList);

                                    outgoingList.Clear();
                                    sizeOfListItems = 0;
                                }
                                outgoingList.Add(denormalizedRecord);
                                sizeOfListItems += sizeOfDenormalizedRecord;
                            }
                        }
                    }
                }
                if (sizeOfListItems > 0)
                {
                    yield return(outgoingList);
                }
            }
            finally
            {
                ListPool <DenormalizedRecord> .Free(outgoingList);
            }
        }
コード例 #7
0
        /// <summary>
        /// Adds more items to the spawner list, including geysers, artifacts, and POI items.
        /// </summary>
        /// <param name="instance">The sandbox tool menu to modify.</param>
        private static void AddToSpawnerMenu(SandboxToolParameterMenu instance)
        {
            // Transpiling it is possible (and a bit faster) but way more brittle
            var selector = instance.entitySelector;
            var filters  = ListPool <SearchFilter, SandboxToolParameterMenu> .Allocate();

            filters.AddRange(selector.filters);
            // POI Props
            filters.Add(new SearchFilter(SandboxToolsStrings.FILTER_POIPROPS,
                                         (entity) => {
                var prefab = entity as KPrefabID;
                bool ok    = prefab != null;
                if (ok)
                {
                    string name = prefab.PrefabTag.Name;
                    // Include anti-entropy thermo nullifier and neural vacillator
                    // Vacillator's ID is private, we have to make do
                    ok = (name.StartsWith("Prop") && name.Length > 4 && char.IsUpper(
                              name, 4)) || name == MassiveHeatSinkConfig.ID ||
                         name == "GeneShuffler";
                }
                return(ok);
            }, null, Def.GetUISprite(Assets.GetPrefab("PropLadder"))));
            // Artifacts
            filters.Add(new SearchFilter(SandboxToolsStrings.FILTER_ARTIFACTS,
                                         (entity) => {
                var prefab = entity as KPrefabID;
                bool ok    = prefab != null;
                if (ok)
                {
                    ok = prefab.PrefabTag.Name.StartsWith("artifact_");
                }
                return(ok);
            }, null, Def.GetUISprite(Assets.GetPrefab("artifact_eggrock"))));
            // Geysers
            filters.Add(new SearchFilter(SandboxToolsStrings.FILTER_GEYSERS,
                                         (entity) => {
                var prefab = entity as KPrefabID;
                return(prefab != null && (prefab.GetComponent <Geyser>() != null || prefab.
                                          PrefabTag.Name == "OilWell"));
            }, null, Def.GetUISprite(Assets.GetPrefab("GeyserGeneric_slush_water"))));
            // TODO Vanilla/DLC code
            if (PPatchTools.GetTypeSafe("FullereneCometConfig") == null)
            {
                // Update the special filter to add other comet types
                foreach (var filter in filters)
                {
                    if (filter.Name == STRINGS.UI.SANDBOXTOOLS.FILTERS.ENTITIES.SPECIAL)
                    {
                        var oldCondition = filter.condition;
                        filter.condition = (entity) => {
                            var prefab = entity as KPrefabID;
                            return((prefab != null && prefab.GetComponent <Comet>() != null) ||
                                   oldCondition.Invoke(entity));
                        };
                    }
                }
            }
            // Add matching assets
            var options = ListPool <object, SandboxToolParameterMenu> .Allocate();

            foreach (var prefab in Assets.Prefabs)
            {
                foreach (var filter in filters)
                {
                    if (filter.condition(prefab))
                    {
                        options.Add(prefab);
                        break;
                    }
                }
            }
#if DEBUG
            PUtil.LogDebug("Added {0:D} options to spawn menu".F(options.Count));
#endif
            selector.options = options.ToArray();
            selector.filters = filters.ToArray();
            options.Recycle();
            filters.Recycle();
        }
コード例 #8
0
    public bool FindNextChore(ref Chore.Precondition.Context out_context)
    {
        if (debug)
        {
            int num = 0;
            num++;
        }
        preconditionSnapshot.Clear();
        consumerState.Refresh();
        if (consumerState.hasSolidTransferArm)
        {
            Debug.Assert(stationaryReach > 0);
            CellOffset offset  = Grid.GetOffset(Grid.PosToCell(this));
            Extents    extents = new Extents(offset.x, offset.y, stationaryReach);
            ListPool <ScenePartitionerEntry, ChoreConsumer> .PooledList pooledList = ListPool <ScenePartitionerEntry, ChoreConsumer> .Allocate();

            GameScenePartitioner.Instance.GatherEntries(extents, GameScenePartitioner.Instance.fetchChoreLayer, pooledList);
            foreach (ScenePartitionerEntry item in pooledList)
            {
                if (item.obj == null)
                {
                    DebugUtil.Assert(false, "FindNextChore found an entry that was null");
                }
                else
                {
                    FetchChore fetchChore = item.obj as FetchChore;
                    if (fetchChore == null)
                    {
                        DebugUtil.Assert(false, "FindNextChore found an entry that wasn't a FetchChore");
                    }
                    else if (fetchChore.target == null)
                    {
                        DebugUtil.Assert(false, "FindNextChore found an entry with a null target");
                    }
                    else if (fetchChore.isNull)
                    {
                        Debug.LogWarning("FindNextChore found an entry that isNull");
                    }
                    else
                    {
                        int cell = Grid.PosToCell(fetchChore.gameObject);
                        if (consumerState.solidTransferArm.IsCellReachable(cell))
                        {
                            fetchChore.CollectChoresFromGlobalChoreProvider(consumerState, preconditionSnapshot.succeededContexts, preconditionSnapshot.failedContexts, false);
                        }
                    }
                }
            }
            pooledList.Recycle();
        }
        else
        {
            for (int i = 0; i < providers.Count; i++)
            {
                ChoreProvider choreProvider = providers[i];
                choreProvider.CollectChores(consumerState, preconditionSnapshot.succeededContexts, preconditionSnapshot.failedContexts);
            }
        }
        preconditionSnapshot.succeededContexts.Sort();
        List <Chore.Precondition.Context> succeededContexts = preconditionSnapshot.succeededContexts;
        bool flag = ChooseChore(ref out_context, succeededContexts);

        if (flag)
        {
            preconditionSnapshot.CopyTo(lastSuccessfulPreconditionSnapshot);
        }
        return(flag);
    }
コード例 #9
0
    public void Render1000ms(float dt)
    {
        DictionaryPool <int, ListPool <FetchList2, FetchListStatusItemUpdater> .PooledList, FetchListStatusItemUpdater> .PooledDictionary pooledDictionary = DictionaryPool <int, ListPool <FetchList2, FetchListStatusItemUpdater> .PooledList, FetchListStatusItemUpdater> .Allocate();

        foreach (FetchList2 fetchList in fetchLists)
        {
            if (!((Object)fetchList.Destination == (Object)null))
            {
                ListPool <FetchList2, FetchListStatusItemUpdater> .PooledList value = null;
                int instanceID = fetchList.Destination.GetInstanceID();
                if (!pooledDictionary.TryGetValue(instanceID, out value))
                {
                    value = (pooledDictionary[instanceID] = ListPool <FetchList2, FetchListStatusItemUpdater> .Allocate());
                }
                value.Add(fetchList);
            }
        }
        DictionaryPool <Tag, float, FetchListStatusItemUpdater> .PooledDictionary pooledDictionary2 = DictionaryPool <Tag, float, FetchListStatusItemUpdater> .Allocate();

        DictionaryPool <Tag, float, FetchListStatusItemUpdater> .PooledDictionary pooledDictionary3 = DictionaryPool <Tag, float, FetchListStatusItemUpdater> .Allocate();

        foreach (KeyValuePair <int, ListPool <FetchList2, FetchListStatusItemUpdater> .PooledList> item in pooledDictionary)
        {
            ListPool <Tag, FetchListStatusItemUpdater> .PooledList pooledList2 = ListPool <Tag, FetchListStatusItemUpdater> .Allocate();

            Storage destination = item.Value[0].Destination;
            foreach (FetchList2 item2 in item.Value)
            {
                item2.UpdateRemaining();
                Dictionary <Tag, float> remaining = item2.GetRemaining();
                foreach (KeyValuePair <Tag, float> item3 in remaining)
                {
                    if (!pooledList2.Contains(item3.Key))
                    {
                        pooledList2.Add(item3.Key);
                    }
                }
            }
            ListPool <Pickupable, FetchListStatusItemUpdater> .PooledList pooledList3 = ListPool <Pickupable, FetchListStatusItemUpdater> .Allocate();

            foreach (GameObject item4 in destination.items)
            {
                if (!((Object)item4 == (Object)null))
                {
                    Pickupable component = item4.GetComponent <Pickupable>();
                    if (!((Object)component == (Object)null))
                    {
                        pooledList3.Add(component);
                    }
                }
            }
            DictionaryPool <Tag, float, FetchListStatusItemUpdater> .PooledDictionary pooledDictionary4 = DictionaryPool <Tag, float, FetchListStatusItemUpdater> .Allocate();

            foreach (Tag item5 in pooledList2)
            {
                float num = 0f;
                foreach (Pickupable item6 in pooledList3)
                {
                    if (item6.KPrefabID.HasTag(item5))
                    {
                        num += item6.TotalAmount;
                    }
                }
                pooledDictionary4[item5] = num;
            }
            foreach (Tag item7 in pooledList2)
            {
                if (!pooledDictionary2.ContainsKey(item7))
                {
                    pooledDictionary2[item7] = WorldInventory.Instance.GetTotalAmount(item7);
                }
                if (!pooledDictionary3.ContainsKey(item7))
                {
                    pooledDictionary3[item7] = WorldInventory.Instance.GetAmount(item7);
                }
            }
            foreach (FetchList2 item8 in item.Value)
            {
                bool should_add  = false;
                bool should_add2 = true;
                bool should_add3 = false;
                Dictionary <Tag, float> remaining2 = item8.GetRemaining();
                foreach (KeyValuePair <Tag, float> item9 in remaining2)
                {
                    Tag   key           = item9.Key;
                    float value2        = item9.Value;
                    float num2          = pooledDictionary4[key];
                    float b             = pooledDictionary2[key];
                    float num3          = pooledDictionary3[key];
                    float num4          = Mathf.Min(value2, b);
                    float num5          = num3 + num4;
                    float minimumAmount = item8.GetMinimumAmount(key);
                    if (num2 + num5 < minimumAmount)
                    {
                        should_add = true;
                    }
                    if (num5 < value2)
                    {
                        should_add2 = false;
                    }
                    if (num2 + num5 > value2 && value2 > num5)
                    {
                        should_add3 = true;
                    }
                }
                item8.UpdateStatusItem(Db.Get().BuildingStatusItems.WaitingForMaterials, ref item8.waitingForMaterialsHandle, should_add2);
                item8.UpdateStatusItem(Db.Get().BuildingStatusItems.MaterialsUnavailable, ref item8.materialsUnavailableHandle, should_add);
                item8.UpdateStatusItem(Db.Get().BuildingStatusItems.MaterialsUnavailableForRefill, ref item8.materialsUnavailableForRefillHandle, should_add3);
            }
            pooledDictionary4.Recycle();
            pooledList3.Recycle();
            pooledList2.Recycle();
            item.Value.Recycle();
        }
        pooledDictionary3.Recycle();
        pooledDictionary2.Recycle();
        pooledDictionary.Recycle();
    }
 public FindEggsTask(int start, int end)
 {
     this.start = start;
     this.end   = end;
     eggs       = ListPool <int, EggProtectionMonitor> .Allocate();
 }
コード例 #11
0
        public void Sim1000ms(float dt)
        {
            int have = 0;

            // Count artifacts discovered
            foreach (var pair in ArtifactConfig.artifactItems)
            {
                foreach (string name in pair.Value)
                {
                    if (DiscoveredResources.Instance.IsDiscovered(Assets.GetPrefab(name).
                                                                  PrefabID()))
                    {
                        have++;
                    }
                }
            }
            ArtifactsObtained = have;
            foreach (var duplicant in Components.LiveMinionIdentities.Items)
            {
                if (duplicant != null)
                {
                    float minValue = float.MaxValue;
                    // Find the worst attribute on this Duplicant for JoaT
                    foreach (var attribute in VarietyAttributes)
                    {
                        float attrValue = attribute.Lookup(duplicant)?.GetTotalValue() ?? 0.0f;
                        if (attrValue < minValue)
                        {
                            minValue = attrValue;
                        }
                    }
                    // If this Duplicant is better than previous jester, update it
                    if (minValue >= BestVarietyValue)
                    {
                        BestVarietyValue = minValue;
                    }
                }
            }
            // For each value requested, update the value if needed
            var keys = ListPool <string, AchievementStateComponent> .Allocate();

            keys.Clear();
            keys.AddRange(BestAttributeValue.Keys);
            foreach (var attribute in keys)
            {
                // Check each duplicant for the best value
                float best = 0.0f;
                var   attr = Db.Get().Attributes.Get(attribute);
                foreach (var duplicant in Components.LiveMinionIdentities.Items)
                {
                    if (duplicant != null)
                    {
                        best = Math.Max(best, attr.Lookup(duplicant).GetTotalValue());
                    }
                }
                BestAttributeValue[attribute] = best;
            }
            keys.Recycle();
            // Mark visited worlds for DLC
            if (DlcManager.IsExpansion1Active())
            {
                foreach (var world in ClusterManager.Instance.WorldContainers)
                {
                    if (world.IsDupeVisited)
                    {
                        PlanetsVisited.Add(world.id);
                    }
                }
            }
        }
コード例 #12
0
    private void GetBuildableStates(bool force_update)
    {
        if (Assets.BuildingDefs != null && Assets.BuildingDefs.Count != 0)
        {
            if (timeSinceNotificationPing < specialNotificationEmbellishDelay)
            {
                timeSinceNotificationPing += Time.unscaledDeltaTime;
            }
            if (timeSinceNotificationPing >= notificationPingExpire)
            {
                notificationPingCount = 0;
            }
            int num = 10;
            if (force_update)
            {
                num = Assets.BuildingDefs.Count;
                buildable_state_update_idx = 0;
            }
            ListPool <HashedString, PlanScreen> .PooledList pooledList = ListPool <HashedString, PlanScreen> .Allocate();

            for (int i = 0; i < num; i++)
            {
                buildable_state_update_idx = (buildable_state_update_idx + 1) % Assets.BuildingDefs.Count;
                BuildingDef buildingDef = Assets.BuildingDefs[buildable_state_update_idx];
                if (!buildingDef.Deprecated && tagCategoryMap.TryGetValue(buildingDef.Tag, out HashedString value))
                {
                    RequirementsState requirementsState = RequirementsState.Complete;
                    if (!DebugHandler.InstantBuildMode && !Game.Instance.SandboxModeActive)
                    {
                        if (!Db.Get().TechItems.IsTechItemComplete(buildingDef.PrefabID))
                        {
                            requirementsState = RequirementsState.Tech;
                        }
                        else if (!ProductInfoScreen.MaterialsMet(buildingDef.CraftRecipe))
                        {
                            requirementsState = RequirementsState.Materials;
                        }
                    }
                    if (!buildableDefs.ContainsKey(buildingDef))
                    {
                        buildableDefs.Add(buildingDef, requirementsState);
                    }
                    else if (buildableDefs[buildingDef] != requirementsState)
                    {
                        buildableDefs[buildingDef] = requirementsState;
                        if ((UnityEngine.Object)productInfoScreen.currentDef == (UnityEngine.Object)buildingDef)
                        {
                            ignoreToolChangeMessages++;
                            productInfoScreen.ClearProduct(false);
                            productInfoScreen.Show(true);
                            productInfoScreen.ConfigureScreen(buildingDef);
                            ignoreToolChangeMessages--;
                        }
                        if (requirementsState == RequirementsState.Complete)
                        {
                            foreach (ToggleInfo item in toggleInfo)
                            {
                                HashedString x = (HashedString)item.userData;
                                if (x == value)
                                {
                                    string   text      = "NotificationPing";
                                    Animator component = item.toggle.GetComponent <Animator>();
                                    if (!component.GetCurrentAnimatorStateInfo(0).IsTag(text) && !pooledList.Contains(value))
                                    {
                                        pooledList.Add(value);
                                        item.toggle.gameObject.GetComponent <Animator>().Play(text);
                                        if (KTime.Instance.UnscaledGameTime - initTime > 1.5f)
                                        {
                                            if (timeSinceNotificationPing >= specialNotificationEmbellishDelay)
                                            {
                                                string sound = GlobalAssets.GetSound("NewBuildable_Embellishment", false);
                                                if (sound != null)
                                                {
                                                    EventInstance instance = SoundEvent.BeginOneShot(sound, SoundListenerController.Instance.transform.GetPosition());
                                                    SoundEvent.EndOneShot(instance);
                                                }
                                            }
                                            string sound2 = GlobalAssets.GetSound("NewBuildable", false);
                                            if (sound2 != null)
                                            {
                                                EventInstance instance2 = SoundEvent.BeginOneShot(sound2, SoundListenerController.Instance.transform.GetPosition());
                                                instance2.setParameterValue("playCount", (float)notificationPingCount);
                                                SoundEvent.EndOneShot(instance2);
                                            }
                                        }
                                        timeSinceNotificationPing = 0f;
                                        notificationPingCount++;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            pooledList.Recycle();
        }
    }
コード例 #13
0
        static IEnumerable <List <DenormalizedRecord> > denormalizedRecords(string newClientContent, Binder errorRecordBinder, ILogger log)
        {
            var outgoingList = ListPool <DenormalizedRecord> .Allocate();

            outgoingList.Capacity = 450;
            var sizeOfListItems = 0;

            try
            {
                NSGFlowLogRecords logs = JsonConvert.DeserializeObject <NSGFlowLogRecords>(newClientContent);

                foreach (var record in logs.records)
                {
                    float version = record.properties.Version;

                    foreach (var outerFlow in record.properties.flows)
                    {
                        foreach (var innerFlow in outerFlow.flows)
                        {
                            foreach (var flowTuple in innerFlow.flowTuples)
                            {
                                var tuple = new NSGFlowLogTuple(flowTuple, version);

                                var denormalizedRecord = new DenormalizedRecord(
                                    record.properties.Version,
                                    record.time,
                                    record.category,
                                    record.operationName,
                                    record.resourceId,
                                    outerFlow.rule,
                                    innerFlow.mac,
                                    tuple);

                                var sizeOfDenormalizedRecord = denormalizedRecord.GetSizeOfJSONObject();
                                //new-code-start
                                //if (sizeOfDenormalizedRecord > 120) // this will chunk below 256KB
                                if (sizeOfListItems > 120)
                                {
                                    yield return(outgoingList);

                                    outgoingList.Clear();
                                    sizeOfListItems = 0;
                                }
                                //new-code-end

/*
 *                              if (sizeOfListItems + sizeOfDenormalizedRecord > MAXTRANSMISSIONSIZE + 20)
 *                              {
 *                                  yield return outgoingList;
 *                                  outgoingList.Clear();
 *                                  sizeOfListItems = 0;
 *                              }
 */
                                outgoingList.Add(denormalizedRecord);
                                //sizeOfListItems += sizeOfDenormalizedRecord;
                                sizeOfListItems += 1;
                            }
                        }
                    }
                }
                if (sizeOfListItems > 0)
                {
                    yield return(outgoingList);
                }
            }
            finally
            {
                ListPool <DenormalizedRecord> .Free(outgoingList);
            }
        }
コード例 #14
0
            private static bool LoadDLLs(string harmonyId, string path)
            {
                try
                {
                    if (Testing.dll_loading == Testing.DLLLoading.Fail)
                    {
                        return(false);
                    }
                    if (Testing.dll_loading == Testing.DLLLoading.UseModLoaderDLLExclusively)
                    {
                        return(false);
                    }

                    DirectoryInfo directoryInfo = new DirectoryInfo(path);
                    if (!directoryInfo.Exists)
                    {
                        return(false);
                    }

                    List <Assembly> assemblies = new List <Assembly>();
                    FileInfo[]      files      = directoryInfo.GetFiles();
                    foreach (FileInfo file in files)
                    {
                        if (file.Name.ToLower().EndsWith(".dll"))
                        {
                            Debug.Log($"Loading MOD dll: {file.Name}");
                            logger.Info("Loading Mod DLL: {file_name}", file.Name);
                            Assembly assembly = Assembly.LoadFrom(file.FullName);
                            if (assembly != null)
                            {
                                assemblies.Add(assembly);
                            }
                        }
                    }

                    if (assemblies.Count == 0)
                    {
                        return(false);
                    }

                    ListPool <MethodInfo, Manager> .PooledList pre_patch_methods = ListPool <MethodInfo, Manager> .Allocate();

                    ListPool <MethodInfo, Manager> .PooledList post_patch_methods = ListPool <MethodInfo, Manager> .Allocate();

                    ListPool <MethodInfo, Manager> .PooledList on_load_methods_wo_params = ListPool <MethodInfo, Manager> .Allocate();

                    ListPool <MethodInfo, Manager> .PooledList on_load_methods_wi_params = ListPool <MethodInfo, Manager> .Allocate();

                    Type[] no_parameters    = new Type[0];
                    Type[] string_parameter = new Type[1] {
                        typeof(string)
                    };
                    Type[] harmony_instance_parameter = new Type[1] {
                        typeof(HarmonyInstance)
                    };

                    MethodInfo methodInfo = null;
                    foreach (Assembly assembly in assemblies)
                    {
                        Type[] types = assembly.GetTypes();
                        foreach (Type type in types)
                        {
                            if (!(type == null))
                            {
                                methodInfo = type.GetMethod("OnLoad", no_parameters);
                                if (methodInfo != null)
                                {
                                    on_load_methods_wo_params.Add(methodInfo);
                                }

                                methodInfo = type.GetMethod("OnLoad", string_parameter);
                                if (methodInfo != null)
                                {
                                    on_load_methods_wi_params.Add(methodInfo);
                                }

                                methodInfo = type.GetMethod("PrePatch", harmony_instance_parameter);
                                if (methodInfo != null)
                                {
                                    pre_patch_methods.Add(methodInfo);
                                }

                                methodInfo = type.GetMethod("PostPatch", harmony_instance_parameter);
                                if (methodInfo != null)
                                {
                                    post_patch_methods.Add(methodInfo);
                                }
                            }
                        }
                    }

                    HarmonyInstance harmonyInstance = HarmonyInstance.Create(harmonyId);
                    if (harmonyInstance != null)
                    {
                        object[] parameters = new object[1] {
                            harmonyInstance
                        };
                        foreach (MethodInfo pre_patch in pre_patch_methods)
                        {
                            logger.Debug("Running PrePatch in {module} from {assembly}", pre_patch.DeclaringType.FullName, pre_patch.Module.Name);
                            var watch = Stopwatch.StartNew();
                            try { pre_patch.Invoke(null, parameters); }
                            finally { watch.Stop(); }
                            logger.Debug("{module} PrePatch took {time}ms to complete", pre_patch.DeclaringType.FullName, watch.ElapsedMilliseconds);
                        }
                        foreach (Assembly assembly in assemblies)
                        {
                            logger.Debug("Patching assembly {assembly}", assembly.GetName());
                            var watch = Stopwatch.StartNew();
                            try { harmonyInstance.PatchAll(assembly); }
                            finally { watch.Stop(); }
                            logger.Debug("Patching {module} took {time}ms to complete", assembly.GetName(), watch.ElapsedMilliseconds);
                        }
                        foreach (MethodInfo post_patch in post_patch_methods)
                        {
                            logger.Debug("Running PostPatch in {module} from {assembly}", post_patch.DeclaringType.FullName, post_patch.Module.Name);
                            var watch = Stopwatch.StartNew();
                            try { post_patch.Invoke(null, parameters); }
                            finally { watch.Stop(); }
                            logger.Debug("{module} PostPatch took {time}ms to complete", post_patch.DeclaringType.FullName, watch.ElapsedMilliseconds);
                        }
                    }
                    pre_patch_methods.Recycle();
                    post_patch_methods.Recycle();

                    foreach (MethodInfo on_load in on_load_methods_wo_params)
                    {
                        logger.Debug("Running OnLoad in {module} from {assembly}", on_load.DeclaringType.FullName, on_load.Module.Name);
                        var watch = Stopwatch.StartNew();
                        try { on_load.Invoke(null, null); }
                        finally { watch.Stop(); }
                        logger.Debug("{module} OnLoad took {time}ms to complete", on_load.DeclaringType.FullName, watch.ElapsedMilliseconds);
                    }
                    on_load_methods_wo_params.Recycle();

                    object[] path_parameter = new object[1] {
                        path
                    };
                    foreach (MethodInfo on_load in on_load_methods_wi_params)
                    {
                        logger.Debug("Running OnLoad(path) in {module} from {assembly}", on_load.DeclaringType.FullName, on_load.Module.Name);
                        var watch = Stopwatch.StartNew();
                        try { on_load.Invoke(null, path_parameter); }
                        finally { watch.Stop(); }
                        logger.Debug("{module} OnLoad(path) took {time}ms to complete", on_load.DeclaringType.FullName, watch.ElapsedMilliseconds);
                    }
                    on_load_methods_wi_params.Recycle();

                    return(true);
                }
                catch (Exception e)
                {
                    DebugUtil.LogException(null, "Exception while loading mod " + harmonyId + " at " + path + ".", e);
                    logger.Error(e, "Failed to load mod ({modid}) from {path}", harmonyId, path);
                    return(false);
                }
            }
コード例 #15
0
        private static bool LoadDLLs(string path)
        {
            try
            {
                if (Testing.dll_loading != Testing.DLLLoading.Fail)
                {
                    if (Testing.dll_loading != Testing.DLLLoading.UseModLoaderDLLExclusively)
                    {
                        Debug.LogFormat("Using built-in mod system...looking for DLL mods in {0}", Manager.GetDirectory());
                        DirectoryInfo directoryInfo = new DirectoryInfo(path);
                        if (directoryInfo.Exists)
                        {
                            List <Assembly> list  = new List <Assembly>();
                            FileInfo[]      files = directoryInfo.GetFiles();
                            foreach (FileInfo fileInfo in files)
                            {
                                if (fileInfo.Name.ToLower().EndsWith(".dll"))
                                {
                                    Debug.Log($"Loading MOD dll: {fileInfo.Name}");
                                    Assembly assembly = Assembly.LoadFrom(fileInfo.FullName);
                                    if (assembly != null)
                                    {
                                        list.Add(assembly);
                                    }
                                }
                            }
                            if (list.Count != 0)
                            {
                                ListPool <MethodInfo, Manager> .PooledList pooledList = ListPool <MethodInfo, Manager> .Allocate();

                                ListPool <MethodInfo, Manager> .PooledList pooledList2 = ListPool <MethodInfo, Manager> .Allocate();

                                ListPool <MethodInfo, Manager> .PooledList pooledList3 = ListPool <MethodInfo, Manager> .Allocate();

                                ListPool <MethodInfo, Manager> .PooledList pooledList4 = ListPool <MethodInfo, Manager> .Allocate();

                                Type[] types  = new Type[0];
                                Type[] types2 = new Type[1]
                                {
                                    typeof(string)
                                };
                                Type[] types3 = new Type[1]
                                {
                                    typeof(HarmonyInstance)
                                };
                                MethodInfo methodInfo = null;
                                foreach (Assembly item in list)
                                {
                                    Type[] types4 = item.GetTypes();
                                    foreach (Type type in types4)
                                    {
                                        if (type != null)
                                        {
                                            methodInfo = type.GetMethod("OnLoad", types);
                                            if (methodInfo != null)
                                            {
                                                pooledList3.Add(methodInfo);
                                            }
                                            methodInfo = type.GetMethod("OnLoad", types2);
                                            if (methodInfo != null)
                                            {
                                                pooledList4.Add(methodInfo);
                                            }
                                            methodInfo = type.GetMethod("PrePatch", types3);
                                            if (methodInfo != null)
                                            {
                                                pooledList.Add(methodInfo);
                                            }
                                            methodInfo = type.GetMethod("PostPatch", types3);
                                            if (methodInfo != null)
                                            {
                                                pooledList2.Add(methodInfo);
                                            }
                                        }
                                    }
                                }
                                HarmonyInstance harmonyInstance = HarmonyInstance.Create($"OxygenNotIncluded_v{0}.{1}");
                                if (harmonyInstance != null)
                                {
                                    object[] parameters = new object[1]
                                    {
                                        harmonyInstance
                                    };
                                    foreach (MethodInfo item2 in pooledList)
                                    {
                                        item2.Invoke(null, parameters);
                                    }
                                    foreach (Assembly item3 in list)
                                    {
                                        harmonyInstance.PatchAll(item3);
                                    }
                                    foreach (MethodInfo item4 in pooledList2)
                                    {
                                        item4.Invoke(null, parameters);
                                    }
                                }
                                pooledList.Recycle();
                                pooledList2.Recycle();
                                foreach (MethodInfo item5 in pooledList3)
                                {
                                    item5.Invoke(null, null);
                                }
                                object[] parameters2 = new object[1]
                                {
                                    path
                                };
                                foreach (MethodInfo item6 in pooledList4)
                                {
                                    item6.Invoke(null, parameters2);
                                }
                                pooledList3.Recycle();
                                pooledList4.Recycle();
                                return(true);
                            }
                            return(false);
                        }
                        return(false);
                    }
                    return(false);
                }
                return(false);
            }
            catch (Exception obj)
            {
                Debug.Log("Exception LoadDLLs");
                Debug.LogException(obj);
                return(false);
            }
        }
    private static int CountNearbyPlants(int cell, int radius)
    {
        int x = 0;
        int y = 0;

        Grid.PosToXY(Grid.CellToPos(cell), out x, out y);
        int num = radius * 2;

        x -= radius;
        y -= radius;
        ListPool <ScenePartitionerEntry, GameScenePartitioner> .PooledList pooledList = ListPool <ScenePartitionerEntry, GameScenePartitioner> .Allocate();

        GameScenePartitioner.Instance.GatherEntries(x, y, num, num, GameScenePartitioner.Instance.plants, pooledList);
        int num2 = 0;

        foreach (ScenePartitionerEntry item in pooledList)
        {
            KPrefabID kPrefabID = (KPrefabID)item.obj;
            if (!(bool)kPrefabID.GetComponent <TreeBud>())
            {
                num2++;
            }
        }
        pooledList.Recycle();
        return(num2);
    }
コード例 #17
0
        /// <summary>
        /// Displays all geysers present on the given planetoid.
        /// </summary>
        /// <param name="id">The world ID to filter.</param>
        private void AddGeysers(int id)
        {
            var  geyserRows = sis.geyserRows;
            var  parent     = sis.worldGeysersPanel.Content.gameObject;
            var  spawnables = SaveGame.Instance.worldGenSpawner.spawnables;
            byte worldIndex;
            var  knownGeysers = ListPool <Tag, SimpleInfoScreen> .Allocate();

            // Add all spawned geysers
            int n = allGeysers.Length, unknownGeysers = 0;

            for (int i = 0; i < n; i++)
            {
                var geyser = allGeysers[i];
                var go     = geyser.gameObject;
                if (go.GetMyWorldId() == id)
                {
                    knownGeysers.Add(go.PrefabID());
                }
            }
            // All unknown geysers and oil wells
            n = spawnables.Count;
            for (int i = 0; i < n; i++)
            {
                var candidate = spawnables[i];
                int cell      = candidate.cell;
                if (Grid.IsValidCell(cell) && !candidate.isSpawned && (worldIndex = Grid.
                                                                                    WorldIdx[cell]) != ClusterManager.INVALID_WORLD_IDX &&
                    worldIndex == id)
                {
                    string prefabID  = candidate.spawnInfo.id;
                    Tag    prefabTag = new Tag(prefabID);
                    if (prefabID == OilWellConfig.ID)
                    {
                        knownGeysers.Add(prefabTag);
                    }
                    else if (prefabID == GeyserGenericConfig.ID)
                    {
                        unknownGeysers++;
                    }
                    else
                    {
                        var prefab = Assets.GetPrefab(prefabTag);
                        if (prefab != null && prefab.TryGetComponent(out Geyser _))
                        {
                            knownGeysers.Add(prefabTag);
                        }
                    }
                }
            }
            int totalGeysers = knownGeysers.Count;

            foreach (var pair in geyserRows)
            {
                pair.Value.SetActive(false);
            }
            for (int i = 0; i < totalGeysers; i++)
            {
                AddGeyser(knownGeysers[i], parent, null, geyserRows);
            }
            if (unknownGeysers > 0)
            {
                AddGeyser(UNKNOWN_GEYSERS, parent, STRINGS.UI.DETAILTABS.SIMPLEINFO.
                          UNKNOWN_GEYSERS.Replace("{num}", unknownGeysers.ToString()), geyserRows);
            }
            if (totalGeysers == 0)
            {
                AddGeyser(new Tag(NO_GEYSERS), parent, STRINGS.UI.DETAILTABS.SIMPLEINFO.
                          NO_GEYSERS, geyserRows);
            }
            knownGeysers.Recycle();
        }
コード例 #18
0
        /// <summary>
        /// Lays out components in the box layout container parallel to the layout axis.
        /// </summary>
        /// <param name="required">The calculated minimum and preferred sizes.</param>
        /// <param name="args">The parameters to use for layout.</param>
        /// <param name="status">The current status of layout.</param>
        private static void DoLayoutLinear(LayoutResults required, BoxLayoutParams args,
                                           LayoutStatus status)
        {
            var total      = required.total;
            var components = ListPool <ILayoutController, BoxLayoutGroup> .Allocate();

            var direction = args.Direction;
            // Determine flex size ratio
            float size = status.size, prefRatio = 0.0f, minSize = total.min, prefSize =
                total.preferred, excess = Math.Max(0.0f, size - prefSize), flexTotal = total.
                                                                                       flexible, offset = status.offset, spacing = args.Spacing;

            if (size > minSize && prefSize > minSize)
            {
                // Do not divide by 0
                prefRatio = Math.Min(1.0f, (size - minSize) / (prefSize - minSize));
            }
            if (excess > 0.0f && flexTotal == 0.0f)
            {
                // If no components can be expanded, offset all
                offset += GetOffset(args, status.direction, excess);
            }
            foreach (var child in required.children)
            {
                var obj = child.source;
                // Active objects only
                if (obj != null && obj.activeInHierarchy)
                {
                    float compSize = child.min;
                    if (prefRatio > 0.0f)
                    {
                        compSize += (child.preferred - child.min) * prefRatio;
                    }
                    if (excess > 0.0f && flexTotal > 0.0f)
                    {
                        compSize += excess * child.flexible / flexTotal;
                    }
                    // Place and size component
                    obj.AddOrGet <RectTransform>().SetInsetAndSizeFromParentEdge(status.edge,
                                                                                 offset, compSize);
                    offset += compSize + ((compSize > 0.0f) ? spacing : 0.0f);
                    // Invoke SetLayout on dependents
                    components.Clear();
                    obj.GetComponents(components);
                    foreach (var component in components)
                    {
                        if (!PUIUtils.IgnoreLayout(component))
                        {
                            if (direction == PanelDirection.Horizontal)
                            {
                                component.SetLayoutHorizontal();
                            }
                            else                             // if (direction == PanelDirection.Vertical)
                            {
                                component.SetLayoutVertical();
                            }
                        }
                    }
                }
            }
            components.Recycle();
        }
コード例 #19
0
        private void SetTemperature()
        {
            this.lastTemperatureLow  = this.maxTemp;
            this.lastTemperatureHigh = this.minTemp;

            int cell = this.NaturalBuildingCell();

            ListPool <ScenePartitionerEntry, LogicMassSensor> .PooledList pooledList = ListPool <ScenePartitionerEntry, LogicMassSensor> .Allocate();

            GameScenePartitioner.Instance.GatherEntries(Grid.CellToXY(cell).x, Grid.CellToXY(cell).y, 1, 1, GameScenePartitioner.Instance.pickupablesLayer, pooledList);
            for (int i = 0; i < pooledList.Count; i++)
            {
                Pickupable pickupable = pooledList[i].obj as Pickupable;
                if (!(pickupable == null))
                {
                    if (!pickupable.wasAbsorbed)
                    {
                        float temperature = pickupable.PrimaryElement.Temperature;

                        if (temperature > this.lastTemperatureHigh)
                        {
                            this.lastTemperatureHigh = temperature;
                        }

                        if (temperature < this.lastTemperatureLow)
                        {
                            this.lastTemperatureLow = temperature;
                        }
                    }
                }
            }
            pooledList.Recycle();
            ReadPrivate.Set(typeof(LogicTemperatureSensor), this, "averageTemp", this.activateOnWarmerThan ? this.lastTemperatureLow : this.lastTemperatureHigh);
        }
コード例 #20
0
    private void Explode(Vector3 pos, int cell, int prev_cell, Element element)
    {
        PlayImpactSound(pos);
        Vector3 pos2 = pos;

        pos2.z = Grid.GetLayerZ(Grid.SceneLayer.FXFront2);
        Game.Instance.SpawnFX(explosionEffectHash, pos2, 0f);
        Substance substance = element.substance;
        int       num       = Random.Range(explosionOreCount.x, explosionOreCount.y + 1);
        Vector2   a         = -velocity.normalized;
        Vector2   a2        = new Vector2(a.y, 0f - a.x);

        ListPool <ScenePartitionerEntry, Comet> .PooledList pooledList = ListPool <ScenePartitionerEntry, Comet> .Allocate();

        GameScenePartitioner.Instance.GatherEntries((int)pos.x - 3, (int)pos.y - 3, 6, 6, GameScenePartitioner.Instance.pickupablesLayer, pooledList);
        foreach (ScenePartitionerEntry item in pooledList)
        {
            GameObject gameObject = (item.obj as Pickupable).gameObject;
            if (!((Object)gameObject.GetComponent <MinionIdentity>() != (Object)null) && gameObject.GetDef <CreatureFallMonitor.Def>() == null)
            {
                Vector2 vector = gameObject.transform.GetPosition() - pos;
                vector  = vector.normalized;
                vector += new Vector2(0f, 0.55f);
                vector *= 0.5f * Random.Range(explosionSpeedRange.x, explosionSpeedRange.y);
                if (GameComps.Fallers.Has(gameObject))
                {
                    GameComps.Fallers.Remove(gameObject);
                }
                if (GameComps.Gravities.Has(gameObject))
                {
                    GameComps.Gravities.Remove(gameObject);
                }
                GameComps.Fallers.Add(gameObject, vector);
            }
        }
        pooledList.Recycle();
        int num2 = splashRadius + 1;

        for (int i = -num2; i <= num2; i++)
        {
            for (int j = -num2; j <= num2; j++)
            {
                int num3 = Grid.OffsetCell(cell, j, i);
                if (Grid.IsValidCell(num3) && !destroyedCells.Contains(num3))
                {
                    float num4 = (1f - (float)Mathf.Abs(j) / (float)num2) * (1f - (float)Mathf.Abs(i) / (float)num2);
                    if (num4 > 0f)
                    {
                        DamageTiles(num3, prev_cell, num4 * totalTileDamage * 0.5f);
                    }
                }
            }
        }
        float mass        = (num <= 0) ? 1f : (explosionMass / (float)num);
        float temperature = Random.Range(explosionTemperatureRange.x, explosionTemperatureRange.y);

        for (int k = 0; k < num; k++)
        {
            Vector2 normalized = (a + a2 * Random.Range(-1f, 1f)).normalized;
            Vector3 v          = normalized * Random.Range(explosionSpeedRange.x, explosionSpeedRange.y);
            Vector3 a3         = normalized.normalized * 0.75f;
            a3 += new Vector3(0f, 0.55f, 0f);
            a3 += pos;
            GameObject go = substance.SpawnResource(a3, mass, temperature, byte.MaxValue, 0, false, false, false);
            if (GameComps.Fallers.Has(go))
            {
                GameComps.Fallers.Remove(go);
            }
            GameComps.Fallers.Add(go, v);
        }
        if (addTiles > 0)
        {
            int   depthOfElement = GetDepthOfElement(cell, element);
            float num5           = 1f - (float)(depthOfElement - addTilesMinHeight) / (float)(addTilesMaxHeight - addTilesMinHeight);
            int   num6           = Mathf.Min(addTiles, Mathf.Clamp(Mathf.RoundToInt((float)addTiles * num5), 1, addTiles));
            HashSetPool <int, Comet> .PooledHashSet pooledHashSet = HashSetPool <int, Comet> .Allocate();

            HashSetPool <int, Comet> .PooledHashSet pooledHashSet2 = HashSetPool <int, Comet> .Allocate();

            QueuePool <GameUtil.FloodFillInfo, Comet> .PooledQueue pooledQueue = QueuePool <GameUtil.FloodFillInfo, Comet> .Allocate();

            pooledQueue.Enqueue(new GameUtil.FloodFillInfo
            {
                cell  = cell,
                depth = 0
            });
            pooledQueue.Enqueue(new GameUtil.FloodFillInfo
            {
                cell  = prev_cell,
                depth = 0
            });
            pooledQueue.Enqueue(new GameUtil.FloodFillInfo
            {
                cell  = Grid.OffsetCell(cell, new CellOffset(-1, 0)),
                depth = 0
            });
            pooledQueue.Enqueue(new GameUtil.FloodFillInfo
            {
                cell  = Grid.OffsetCell(cell, new CellOffset(1, 0)),
                depth = 0
            });
            GameUtil.FloodFillConditional(pooledQueue, SpawnTilesCellTest, pooledHashSet2, pooledHashSet, 10);
            float mass2 = (num6 <= 0) ? 1f : (addTileMass / (float)addTiles);
            UnstableGroundManager component = World.Instance.GetComponent <UnstableGroundManager>();
            foreach (int item2 in pooledHashSet)
            {
                if (num6 <= 0)
                {
                    break;
                }
                component.Spawn(item2, element, mass2, temperature, byte.MaxValue, 0);
                num6--;
            }
            pooledHashSet.Recycle();
            pooledHashSet2.Recycle();
            pooledQueue.Recycle();
        }
    }
        private void FindClimbableTree()
        {
            climbTarget = null;
            ListPool <ScenePartitionerEntry, GameScenePartitioner> .PooledList pooledList = ListPool <ScenePartitionerEntry, GameScenePartitioner> .Allocate();

            ListPool <KMonoBehaviour, ClimbableTreeMonitor> .PooledList pooledList2 = ListPool <KMonoBehaviour, ClimbableTreeMonitor> .Allocate();

            Vector3 position = base.master.transform.GetPosition();
            Extents extents  = new Extents(Grid.PosToCell(position), 10);

            GameScenePartitioner.Instance.GatherEntries(extents, GameScenePartitioner.Instance.plants, pooledList);
            GameScenePartitioner.Instance.GatherEntries(extents, GameScenePartitioner.Instance.completeBuildings, pooledList);
            Navigator component = GetComponent <Navigator>();

            foreach (ScenePartitionerEntry item in pooledList)
            {
                KMonoBehaviour kMonoBehaviour = item.obj as KMonoBehaviour;
                if (!kMonoBehaviour.HasTag(GameTags.Creatures.ReservedByCreature))
                {
                    int cell = Grid.PosToCell(kMonoBehaviour);
                    if (component.CanReach(cell))
                    {
                        BuddingTrunk  component2 = kMonoBehaviour.GetComponent <BuddingTrunk>();
                        StorageLocker component3 = kMonoBehaviour.GetComponent <StorageLocker>();
                        if ((Object)component2 != (Object)null)
                        {
                            if (!component2.ExtraSeedAvailable)
                            {
                                continue;
                            }
                        }
                        else
                        {
                            if (!((Object)component3 != (Object)null))
                            {
                                continue;
                            }
                            Storage component4 = component3.GetComponent <Storage>();
                            if (!component4.allowItemRemoval || component4.IsEmpty())
                            {
                                continue;
                            }
                        }
                        pooledList2.Add(kMonoBehaviour);
                    }
                }
            }
            if (pooledList2.Count > 0)
            {
                int            index           = Random.Range(0, pooledList2.Count);
                KMonoBehaviour kMonoBehaviour2 = pooledList2[index];
                climbTarget = kMonoBehaviour2.gameObject;
            }
            pooledList.Recycle();
            pooledList2.Recycle();
        }
コード例 #22
0
        public void PollForReactables(Navigator.ActiveTransition transition)
        {
            if (!IsReacting())
            {
                if (justReacted)
                {
                    justReacted = false;
                }
                else
                {
                    lastReactable = null;
                }
                for (int num = oneshotReactables.Count - 1; num >= 0; num--)
                {
                    Reactable reactable = oneshotReactables[num];
                    if (reactable.IsExpired())
                    {
                        reactable.Cleanup();
                    }
                }
                int cell = Grid.PosToCell(base.smi.gameObject);
                ListPool <ScenePartitionerEntry, ReactionMonitor> .PooledList pooledList = ListPool <ScenePartitionerEntry, ReactionMonitor> .Allocate();

                GameScenePartitioner instance = GameScenePartitioner.Instance;
                Vector2I             vector2I = Grid.CellToXY(cell);
                int      x         = vector2I.x;
                Vector2I vector2I2 = Grid.CellToXY(cell);
                instance.GatherEntries(x, vector2I2.y, 1, 1, GameScenePartitioner.Instance.objectLayers[0], pooledList);
                for (int i = 0; i < pooledList.Count; i++)
                {
                    Reactable reactable2 = pooledList[i].obj as Reactable;
                    if (reactable2 != null && reactable2 != lastReactable && (!lastReactTimes.ContainsKey(reactable2.id) || !(GameClock.Instance.GetTime() - lastReactTimes[reactable2.id] < reactable2.minReactorTime)) && reactable2.CanBegin(base.gameObject, transition))
                    {
                        justReacted   = true;
                        lastReactable = reactable2;
                        lastReactTimes[reactable2.id] = GameClock.Instance.GetTime();
                        base.sm.reactable.Set(reactable2, base.smi);
                        base.smi.GoTo(base.sm.reacting);
                        break;
                    }
                }
                pooledList.Recycle();
            }
        }
コード例 #23
0
        /// <summary>
        /// Updates the sweeper asynchronously.
        /// </summary>
        /// <param name="info">The sweeper to update.</param>
        private void AsyncUpdate(SolidTransferArmInfo info)
        {
            var sweeper        = info.sweeper;
            var reachableCells = HashSetPool <int, SolidTransferArmUpdater> .Allocate();

            int range = sweeper.pickupRange, cell = info.cell;

            Grid.CellToXY(cell, out int x, out int y);
            int maxY = Math.Min(Grid.HeightInCells, y + range), maxX = Math.Min(Grid.
                                                                                WidthInCells, x + range), minY = Math.Max(0, y - range), minX = Math.Max(0,
                                                                                                                                                         x - range);
            var oldReachable = sweeper.reachableCells;
            var go           = info.gameObject;

            // Recalculate the visible cells
            for (int ny = minY; ny <= maxY; ny++)
            {
                for (int nx = minX; nx <= maxX; nx++)
                {
                    cell = Grid.XYToCell(nx, ny);
                    if (Grid.IsPhysicallyAccessible(x, y, nx, ny, true))
                    {
                        reachableCells.Add(cell);
                    }
                }
            }
            if (!oldReachable.SetEquals(reachableCells))
            {
                // O(n) operation worst case
                oldReachable.Clear();
                oldReachable.UnionWith(reachableCells);
                info.refreshedCells = true;
            }
            // Gather stored objects not found by the partitioner
            var pickupables = sweeper.pickupables;

            pickupables.Clear();
            foreach (var entry in cached)
            {
                var pickupable = entry.pickupable;
                if (pickupable != null)
                {
                    cell = entry.storage_cell;
                    Grid.CellToXY(cell, out x, out y);
                    if (x >= minX && x <= maxX && y >= minY && y <= maxY && reachableCells.
                        Contains(cell) && CanUse(pickupable, go))
                    {
                        pickupables.Add(pickupable);
                    }
                }
            }
            var gsp = GameScenePartitioner.Instance;

            // Gather nearby pickupables with the scene partitioner, faster and more memory
            // efficient than scanning all
            if (gsp != null)
            {
                var found = ListPool <ScenePartitionerEntry, SolidTransferArmUpdater> .
                            Allocate();

                // Avoid contention, as unfortunately GSP is not very thread safe
                lock (sweepers) {
                    gsp.GatherEntries(new Extents(minX, minY, maxX - minX + 1, maxY - minY +
                                                  1), gsp.pickupablesLayer, found);
                }
                foreach (var entry in found)
                {
                    if (entry.obj is Pickupable pickupable && pickupable != null)
                    {
                        cell = pickupable.cachedCell;
                        if (reachableCells.Contains(cell) && CanUse(pickupable, go))
                        {
                            pickupables.Add(pickupable);
                        }
                    }
                }
                found.Recycle();
            }
            reachableCells.Recycle();
        }
コード例 #24
0
        /// <summary>
        /// Rebuilds the electrical networks.
        /// </summary>
        /// <param name="instance">The networks to rebuild.</param>
        private static void Rebuild(CircuitManager instance)
        {
            var circuits       = instance.circuitInfo;
            var minBatteryFull = ListPool <float, CircuitManager> .Allocate();

            int n = circuits.Count, circuitID;

            for (int i = 0; i < n; i++)
            {
                var circuit = circuits[i];
                var bridges = circuit.bridgeGroups;
                int nGroups = bridges.Length;
                circuit.generators.Clear();
                circuit.consumers.Clear();
                circuit.batteries.Clear();
                circuit.inputTransformers.Clear();
                circuit.outputTransformers.Clear();
                minBatteryFull.Add(1.0f);
                for (int j = 0; j < nGroups; j++)
                {
                    bridges[j].Clear();
                }
            }
            foreach (var consumer in instance.consumers)
            {
                if (consumer != null && (circuitID = instance.GetCircuitID(consumer)) !=
                    ushort.MaxValue)
                {
                    var circuit = circuits[circuitID];
                    if (consumer is Battery battery)
                    {
                        if (battery.powerTransformer != null)
                        {
                            circuit.inputTransformers.Add(battery);
                        }
                        else
                        {
                            circuit.batteries.Add(battery);
                            minBatteryFull[circuitID] = Mathf.Min(minBatteryFull[circuitID],
                                                                  battery.PercentFull);
                        }
                    }
                    else
                    {
                        circuit.consumers.Add(consumer);
                    }
                }
            }
            for (int i = 0; i < n; i++)
            {
                var circuit = circuits[i];
                circuit.consumers.Sort(ConsumerWattageComparer.Instance);
                circuit.minBatteryPercentFull = minBatteryFull[i];
                circuits[i] = circuit;
            }
            minBatteryFull.Recycle();
            foreach (var generator in instance.generators)
            {
                if (generator != null && (circuitID = instance.GetCircuitID(generator)) !=
                    ushort.MaxValue)
                {
                    var circuit = circuits[circuitID];
                    if (generator is PowerTransformer)
                    {
                        circuit.outputTransformers.Add(generator);
                    }
                    else
                    {
                        circuit.generators.Add(generator);
                    }
                }
            }
            foreach (var bridge in instance.bridges)
            {
                if (bridge != null && (circuitID = instance.GetCircuitID(bridge)) != ushort.
                    MaxValue)
                {
                    circuits[circuitID].bridgeGroups[(int)bridge.GetMaxWattageRating()].Add(
                        bridge);
                }
            }
            instance.dirty = false;
        }
コード例 #25
0
        /// <summary>
        /// Replace the Update function of SteamUGCService with this version that actually
        /// waits for the return and uses the same API as Mod Updater's regular mode.
        /// </summary>
        public void Process()
        {
            var toQuery = ListPool <PublishedFileId_t, SteamUGCServiceFixed> .Allocate();

            var toRemove = ListPool <PublishedFileId_t, SteamUGCServiceFixed> .Allocate();

            var toAdd = HashSetPool <PublishedFileId_t, SteamUGCServiceFixed> .Allocate();

            var toUpdate = HashSetPool <PublishedFileId_t, SteamUGCServiceFixed> .Allocate();

            var loadPreviews = ListPool <SteamUGCService.Mod, SteamUGCServiceFixed> .Allocate();

            int n = clients.Count;

            // Mass request the details of all mods at once
            foreach (var pair in allMods)
            {
                var mod = pair.Value;
                var id  = pair.Key;
                switch (mod.state)
                {
                case SteamModState.NeedsDetails:
                    toQuery.Add(id);
                    break;

                case SteamModState.PendingDestroy:
                    toRemove.Add(id);
                    break;

                case SteamModState.DetailsDirty:
                    // Details were downloaded, send out a quick update of all the mod names
                    // in mass at the beginning even if some downloads are pending
                    if (mod.clientSeen)
                    {
                        toUpdate.Add(id);
                    }
                    else
                    {
                        toAdd.Add(id);
                    }
                    mod.state = SteamModState.Subscribed;
                    break;

                default:
                    break;
                }
                if (mod.previewDirty)
                {
                    loadPreviews.Add(mod.ugcMod);
                    mod.previewDirty = false;
                }
            }
            if (toQuery.Count > 0 && onQueryComplete == null)
            {
                QueryUGCDetails(toQuery.ToArray());
            }
            toQuery.Recycle();
            bool idle = download.Idle;

            if (idle)
            {
                // Avoid spamming by only notifying when all outstanding mods are downloaded
                foreach (var pair in allMods)
                {
                    var mod = pair.Value;
                    var id  = pair.Key;
                    if (mod.state == SteamModState.Updated)
                    {
                        mod.Summon();
                        if (mod.clientSeen)
                        {
                            toUpdate.Add(id);
                        }
                        else
                        {
                            toAdd.Add(id);
                        }
                        mod.state = SteamModState.Subscribed;
                    }
                }
            }
            if (toAdd.Count > 0 || toUpdate.Count > 0 || toRemove.Count > 0 || loadPreviews.
                Count > 0)
            {
                firstEvent = true;
                // Event needs to be triggered
                for (int i = 0; i < n; i++)
                {
                    clients[i].UpdateMods(toAdd, toUpdate, toRemove, loadPreviews);
                }
                if (n > 0)
                {
                    foreach (var added in toAdd)
                    {
                        // Mods that were successfully added will be updated in the future
                        if (allMods.TryGetValue(added, out ModInfo info))
                        {
                            info.clientSeen = true;
                        }
                    }
                }
            }
            // Actually destroy all pending destroy mods
            foreach (var id in toRemove)
            {
                if (allMods.TryRemove(id, out ModInfo destroyed))
                {
                    destroyed.Dispose();
                }
            }
            loadPreviews.Recycle();
            toAdd.Recycle();
            toUpdate.Recycle();
            toRemove.Recycle();
            if (wasIdle != idle || ModUpdateDetails.ScrubConfig())
            {
                // Runs on foreground thread
                wasIdle = idle;
                ModUpdateDatePatches.UpdateMainMenu();
            }
        }
コード例 #26
0
    public void RenderEveryTick(float dt)
    {
        ListPool <Sound, LoopingSoundManager> .PooledList pooledList = ListPool <Sound, LoopingSoundManager> .Allocate();

        ListPool <int, LoopingSoundManager> .PooledList pooledList2 = ListPool <int, LoopingSoundManager> .Allocate();

        ListPool <int, LoopingSoundManager> .PooledList pooledList3 = ListPool <int, LoopingSoundManager> .Allocate();

        List <Sound> dataList    = sounds.GetDataList();
        bool         flag        = Time.timeScale == 0f;
        SoundCuller  soundCuller = CameraController.Instance.soundCuller;

        for (int i = 0; i < dataList.Count; i++)
        {
            Sound sound = dataList[i];
            if ((UnityEngine.Object)sound.transform != (UnityEngine.Object)null)
            {
                sound.pos = sound.transform.GetPosition();
                if ((UnityEngine.Object)sound.animController != (UnityEngine.Object)null)
                {
                    Vector3 offset = sound.animController.Offset;
                    sound.pos.x += offset.x;
                    sound.pos.y += offset.y;
                }
            }
            bool flag2     = !sound.IsCullingEnabled || (sound.ShouldCameraScalePosition && soundCuller.IsAudible(sound.pos, sound.falloffDistanceSq)) || soundCuller.IsAudibleNoCameraScaling(sound.pos, sound.falloffDistanceSq);
            bool isPlaying = sound.IsPlaying;
            if (flag2)
            {
                pooledList.Add(sound);
                if (!isPlaying)
                {
                    SoundDescription soundDescription = GetSoundDescription(sound.path);
                    sound.ev    = KFMOD.CreateInstance(soundDescription.path);
                    dataList[i] = sound;
                    pooledList2.Add(i);
                }
            }
            else if (isPlaying)
            {
                pooledList3.Add(i);
            }
        }
        LoopingSoundParameterUpdater.Sound sound2;
        foreach (int item in pooledList2)
        {
            Sound            value             = dataList[item];
            SoundDescription soundDescription2 = GetSoundDescription(value.path);
            value.ev.setPaused(flag && value.ShouldPauseOnGamePaused);
            Vector2 v = value.pos;
            if (value.ShouldCameraScalePosition)
            {
                v = SoundEvent.GetCameraScaledPosition(v);
            }
            value.ev.set3DAttributes(RuntimeUtils.To3DAttributes(v));
            value.ev.start();
            value.flags |= Sound.Flags.PLAYING;
            if (value.firstParameter != HashedString.Invalid)
            {
                value.ev.setParameterValueByIndex(soundDescription2.GetParameterIdx(value.firstParameter), value.firstParameterValue);
            }
            if (value.secondParameter != HashedString.Invalid)
            {
                value.ev.setParameterValueByIndex(soundDescription2.GetParameterIdx(value.secondParameter), value.secondParameterValue);
            }
            sound2             = default(LoopingSoundParameterUpdater.Sound);
            sound2.ev          = value.ev;
            sound2.path        = value.path;
            sound2.description = soundDescription2;
            sound2.transform   = value.transform;
            LoopingSoundParameterUpdater.Sound sound3     = sound2;
            SoundDescription.Parameter[]       parameters = soundDescription2.parameters;
            for (int j = 0; j < parameters.Length; j++)
            {
                SoundDescription.Parameter   parameter = parameters[j];
                LoopingSoundParameterUpdater value2    = null;
                if (parameterUpdaters.TryGetValue(parameter.name, out value2))
                {
                    value2.Add(sound3);
                }
            }
            dataList[item] = value;
        }
        pooledList2.Recycle();
        foreach (int item2 in pooledList3)
        {
            Sound            value3            = dataList[item2];
            SoundDescription soundDescription3 = GetSoundDescription(value3.path);
            sound2             = default(LoopingSoundParameterUpdater.Sound);
            sound2.ev          = value3.ev;
            sound2.path        = value3.path;
            sound2.description = soundDescription3;
            sound2.transform   = value3.transform;
            LoopingSoundParameterUpdater.Sound sound4      = sound2;
            SoundDescription.Parameter[]       parameters2 = soundDescription3.parameters;
            for (int k = 0; k < parameters2.Length; k++)
            {
                SoundDescription.Parameter   parameter2 = parameters2[k];
                LoopingSoundParameterUpdater value4     = null;
                if (parameterUpdaters.TryGetValue(parameter2.name, out value4))
                {
                    value4.Remove(sound4);
                }
            }
            if (value3.ShouldCameraScalePosition)
            {
                value3.ev.stop(STOP_MODE.IMMEDIATE);
            }
            else
            {
                value3.ev.stop(STOP_MODE.ALLOWFADEOUT);
            }
            value3.flags &= ~Sound.Flags.PLAYING;
            value3.ev.release();
            dataList[item2] = value3;
        }
        pooledList3.Recycle();
        float velocityScale = TuningData <Tuning> .Get().velocityScale;

        foreach (Sound item3 in pooledList)
        {
            Sound         current3   = item3;
            ATTRIBUTES_3D attributes = SoundEvent.GetCameraScaledPosition(current3.pos).To3DAttributes();
            attributes.velocity = (current3.velocity * velocityScale).ToFMODVector();
            current3.ev.set3DAttributes(attributes);
        }
        foreach (KeyValuePair <HashedString, LoopingSoundParameterUpdater> parameterUpdater in parameterUpdaters)
        {
            parameterUpdater.Value.Update(dt);
        }
        pooledList.Recycle();
    }
コード例 #27
0
    private void ProcessRegistrations()
    {
        ListPool <KBatchedAnimController, KBatchedAnimUpdater> .PooledList pooledList = ListPool <KBatchedAnimController, KBatchedAnimUpdater> .Allocate();

        for (int i = 0; i < queuedRegistrations.Count; i++)
        {
            RegistrationInfo info = queuedRegistrations[i];
            if (info.register)
            {
                if (!((UnityEngine.Object)info.controller == (UnityEngine.Object)null))
                {
                    int instanceID = info.controller.GetInstanceID();
                    DebugUtil.Assert(!controllerChunkInfos.ContainsKey(instanceID));
                    ControllerChunkInfo controllerChunkInfo = default(ControllerChunkInfo);
                    controllerChunkInfo.controller = info.controller;
                    controllerChunkInfo.chunkXY    = PosToChunkXY(info.controller.PositionIncludingOffset);
                    ControllerChunkInfo value = controllerChunkInfo;
                    controllerChunkInfos[instanceID] = value;
                    Singleton <CellChangeMonitor> .Instance.RegisterMovementStateChanged(info.controller.transform, OnMovementStateChanged);

                    List <KBatchedAnimController> controllerList = GetControllerList(value.chunkXY);
                    if (controllerList != null)
                    {
                        DebugUtil.Assert(!controllerList.Contains(info.controller));
                        controllerList.Add(info.controller);
                    }
                    if (Singleton <CellChangeMonitor> .Instance.IsMoving(info.controller.transform))
                    {
                        movingControllerInfos.Add(new MovingControllerInfo
                        {
                            controllerInstanceId = instanceID,
                            controller           = info.controller,
                            chunkXY = value.chunkXY
                        });
                    }
                    if (controllerList != null && visibleChunkGrid[value.chunkXY.x, value.chunkXY.y])
                    {
                        pooledList.Add(info.controller);
                    }
                }
            }
            else
            {
                ControllerChunkInfo value2 = default(ControllerChunkInfo);
                if (controllerChunkInfos.TryGetValue(info.controllerInstanceId, out value2))
                {
                    if ((UnityEngine.Object)info.controller != (UnityEngine.Object)null)
                    {
                        List <KBatchedAnimController> controllerList2 = GetControllerList(value2.chunkXY);
                        if (controllerList2 != null)
                        {
                            DebugUtil.Assert(controllerList2.Contains(info.controller));
                            controllerList2.Remove(info.controller);
                        }
                    }
                    movingControllerInfos.RemoveAll((MovingControllerInfo x) => x.controllerInstanceId == info.controllerInstanceId);
                    Singleton <CellChangeMonitor> .Instance.UnregisterMovementStateChanged(info.transformId, OnMovementStateChanged);

                    controllerChunkInfos.Remove(info.controllerInstanceId);
                    pooledList.Remove(info.controller);
                }
            }
        }
        queuedRegistrations.Clear();
        foreach (KBatchedAnimController item in pooledList)
        {
            if ((UnityEngine.Object)item != (UnityEngine.Object)null)
            {
                item.SetVisiblity(true);
            }
        }
        pooledList.Recycle();
    }
コード例 #28
0
        /// <summary>
        /// Attempts to move the pickupable to a position better suited for accessibility. If
        /// the pickupable is not inside a solid (and thus does not need moving), nothing
        /// happens.
        /// </summary>
        /// <param name="material">The pickupable to move.</param>
        private static void MovePreferredPosition(Pickupable material)
        {
            int cell = Grid.PosToCell(material);
            var inst = CleanDropManager.Instance;
            var obj  = material.gameObject;
            LastUsedDirection direction;

            if (inst != null && Grid.IsValidCell(cell) && (direction = inst[cell]) !=
                LastUsedDirection.None && obj.GetSMI <DeathMonitor.Instance>()?.IsDead() !=
                false && ((Grid.Solid[cell] && Grid.Foundation[cell]) || Grid.Properties[
                              cell] != 0))
            {
                var tryFirst = ListPool <int, CleanDropManager> .Allocate();

#if DEBUG
                Grid.CellToXY(cell, out int x, out int y);
                PUtil.LogDebug("Item {0} in cell ({1:D}, {2:D}) last direction = {2}".F(
                                   material.PrimaryElement.Element.name, x, y, direction));
#endif
                // Direction based on workable cell; default direction is U D R L
                switch (direction)
                {
                case LastUsedDirection.Down:
                    tryFirst.Add(Grid.CellBelow(cell));
                    tryFirst.Add(Grid.CellDownRight(cell));
                    tryFirst.Add(Grid.CellDownLeft(cell));
                    break;

                case LastUsedDirection.DownLeft:
                    tryFirst.Add(Grid.CellDownLeft(cell));
                    tryFirst.Add(Grid.CellBelow(cell));
                    tryFirst.Add(Grid.CellLeft(cell));
                    break;

                case LastUsedDirection.DownRight:
                    tryFirst.Add(Grid.CellDownRight(cell));
                    tryFirst.Add(Grid.CellBelow(cell));
                    tryFirst.Add(Grid.CellRight(cell));
                    break;

                case LastUsedDirection.Left:
                    tryFirst.Add(Grid.CellLeft(cell));
                    tryFirst.Add(Grid.CellUpLeft(cell));
                    tryFirst.Add(Grid.CellDownLeft(cell));
                    break;

                case LastUsedDirection.Right:
                    tryFirst.Add(Grid.CellRight(cell));
                    tryFirst.Add(Grid.CellUpRight(cell));
                    tryFirst.Add(Grid.CellDownRight(cell));
                    break;

                case LastUsedDirection.Up:
                    tryFirst.Add(Grid.CellAbove(cell));
                    tryFirst.Add(Grid.CellUpRight(cell));
                    tryFirst.Add(Grid.CellUpLeft(cell));
                    break;

                case LastUsedDirection.UpLeft:
                    tryFirst.Add(Grid.CellUpLeft(cell));
                    tryFirst.Add(Grid.CellAbove(cell));
                    tryFirst.Add(Grid.CellLeft(cell));
                    break;

                case LastUsedDirection.UpRight:
                    tryFirst.Add(Grid.CellUpRight(cell));
                    tryFirst.Add(Grid.CellAbove(cell));
                    tryFirst.Add(Grid.CellRight(cell));
                    break;

                default:
                    break;
                }
                foreach (int tryCell in tryFirst)
                {
                    if (Grid.IsValidCell(tryCell) && !Grid.Solid[tryCell])
                    {
                        var position = Grid.CellToPosCBC(tryCell, Grid.SceneLayer.Move);
                        var collider = obj.GetComponent <KCollider2D>();
                        // Adjust for material's bounding box
                        if (collider != null)
                        {
                            position.y += obj.transform.GetPosition().y - collider.bounds.min.y;
                        }
                        obj.transform.SetPosition(position);
                        // Make the pickupable start falling if not a dupe/critter
                        if (obj.GetComponent <Health>() == null)
                        {
                            if (GameComps.Fallers.Has(obj))
                            {
                                GameComps.Fallers.Remove(obj);
                            }
                            GameComps.Fallers.Add(obj, Vector2.zero);
                        }
                        break;
                    }
                }
                // Do not reset the direction to None since multiple items could drop from
                // one workable
                tryFirst.Recycle();
            }
        }
    private void AddChoreEntry(Chore chore)
    {
        HierarchyReferences choreEntry = GetChoreEntry(GameUtil.GetChoreName(chore, null), chore.choreType, choreGroup.GetReference <RectTransform>("EntriesContainer"));
        FetchChore          fetchChore = chore as FetchChore;

        ListPool <Chore.Precondition.Context, BuildingChoresPanel> .PooledList pooledList = ListPool <Chore.Precondition.Context, BuildingChoresPanel> .Allocate();

        foreach (MinionIdentity item in Components.LiveMinionIdentities.Items)
        {
            pooledList.Clear();
            ChoreConsumer component = item.GetComponent <ChoreConsumer>();
            Chore.Precondition.Context         context = default(Chore.Precondition.Context);
            ChoreConsumer.PreconditionSnapshot lastPreconditionSnapshot = component.GetLastPreconditionSnapshot();
            if (lastPreconditionSnapshot.doFailedContextsNeedSorting)
            {
                lastPreconditionSnapshot.failedContexts.Sort();
                lastPreconditionSnapshot.doFailedContextsNeedSorting = false;
            }
            pooledList.AddRange(lastPreconditionSnapshot.failedContexts);
            pooledList.AddRange(lastPreconditionSnapshot.succeededContexts);
            int num  = -1;
            int num2 = 0;
            for (int num3 = pooledList.Count - 1; num3 >= 0; num3--)
            {
                Chore.Precondition.Context context2 = pooledList[num3];
                if ((UnityEngine.Object)context2.chore.driver != (UnityEngine.Object)null)
                {
                    Chore.Precondition.Context context3 = pooledList[num3];
                    if ((UnityEngine.Object)context3.chore.driver != (UnityEngine.Object)component.choreDriver)
                    {
                        continue;
                    }
                }
                bool flag = pooledList[num3].IsPotentialSuccess();
                if (flag)
                {
                    num2++;
                }
                Chore.Precondition.Context context4       = pooledList[num3];
                FetchAreaChore             fetchAreaChore = context4.chore as FetchAreaChore;
                Chore.Precondition.Context context5       = pooledList[num3];
                if (context5.chore == chore || (fetchChore != null && fetchAreaChore != null && fetchAreaChore.smi.SameDestination(fetchChore)))
                {
                    num     = ((!flag) ? 2147483647 : num2);
                    context = pooledList[num3];
                    break;
                }
            }
            if (num >= 0)
            {
                DupeEntryDatas.Add(new DupeEntryData
                {
                    consumer         = component,
                    context          = context,
                    personalPriority = component.GetPersonalPriority(chore.choreType),
                    rank             = num
                });
            }
        }
        pooledList.Recycle();
        DupeEntryDatas.Sort();
        foreach (DupeEntryData dupeEntryData in DupeEntryDatas)
        {
            GetDupeEntry(dupeEntryData, choreEntry.GetReference <RectTransform>("DupeContainer"));
        }
        DupeEntryDatas.Clear();
    }
コード例 #30
0
    public void RenderEveryTick(float dt)
    {
        ListPool <SpriteSheetAnimator.AnimInfo, BubbleManager> .PooledList pooledList = ListPool <SpriteSheetAnimator.AnimInfo, BubbleManager> .Allocate();

        SpriteSheetAnimator spriteSheetAnimator = SpriteSheetAnimManager.instance.GetSpriteSheetAnimator("liquid_splash1");

        foreach (Bubble bubble2 in bubbles)
        {
            Bubble bubble = bubble2;
            SpriteSheetAnimator.AnimInfo animInfo = default(SpriteSheetAnimator.AnimInfo);
            animInfo.frame       = spriteSheetAnimator.GetFrameFromElapsedTimeLooping(bubble.elapsedTime);
            animInfo.elapsedTime = bubble.elapsedTime;
            animInfo.pos         = new Vector3(bubble.position.x, bubble.position.y, 0f);
            animInfo.rotation    = Quaternion.identity;
            animInfo.size        = Vector2.one;
            animInfo.colour      = new Color32(byte.MaxValue, byte.MaxValue, byte.MaxValue, byte.MaxValue);
            SpriteSheetAnimator.AnimInfo item = animInfo;
            pooledList.Add(item);
        }
        pooledList.Recycle();
    }