protected override bool OnWorkTick(Worker worker, float dt)
        {
            base.OnWorkTick(worker, dt);
            HandSanitizer component     = GetComponent <HandSanitizer>();
            Storage       component2    = GetComponent <Storage>();
            float         massAvailable = component2.GetMassAvailable(component.consumedElement);

            if (massAvailable == 0f)
            {
                return(true);
            }
            PrimaryElement component3 = worker.GetComponent <PrimaryElement>();
            float          a          = component.massConsumedPerUse * dt / workTime;
            float          num        = Mathf.Min(a, massAvailable);
            int            num2       = Math.Min((int)(dt / workTime * (float)component.diseaseRemovalCount), component3.DiseaseCount);

            diseaseRemoved += num2;
            SimUtil.DiseaseInfo invalid = SimUtil.DiseaseInfo.Invalid;
            invalid.idx   = component3.DiseaseIdx;
            invalid.count = num2;
            component3.ModifyDiseaseCount(-num2, "HandSanitizer.OnWorkTick");
            component.maxPossiblyRemoved += num2;
            SimUtil.DiseaseInfo disease_info = SimUtil.DiseaseInfo.Invalid;
            component2.ConsumeAndGetDisease(ElementLoader.FindElementByHash(component.consumedElement).tag, num, out disease_info, out float aggregate_temperature);
            if (component.outputElement != SimHashes.Vacuum)
            {
                disease_info = SimUtil.CalculateFinalDiseaseInfo(invalid, disease_info);
                component2.AddLiquid(component.outputElement, num, aggregate_temperature, disease_info.idx, disease_info.count, false, true);
            }
            return(diseaseRemoved > component.diseaseRemovalCount);
        }
Ejemplo n.º 2
0
        protected override bool OnWorkTick(Worker worker, float dt)
        {
            base.OnWorkTick(worker, dt);
            OreScrubber    component     = GetComponent <OreScrubber>();
            Storage        component2    = GetComponent <Storage>();
            PrimaryElement firstInfected = GetFirstInfected(worker.GetComponent <Storage>());
            int            num           = 0;

            SimUtil.DiseaseInfo invalid = SimUtil.DiseaseInfo.Invalid;
            if ((UnityEngine.Object)firstInfected != (UnityEngine.Object)null)
            {
                num             = Math.Min((int)(dt / workTime * (float)component.diseaseRemovalCount), firstInfected.DiseaseCount);
                diseaseRemoved += num;
                invalid.idx     = firstInfected.DiseaseIdx;
                invalid.count   = num;
                firstInfected.ModifyDiseaseCount(-num, "OreScrubber.OnWorkTick");
            }
            component.maxPossiblyRemoved += num;
            float num2 = component.massConsumedPerUse * dt / workTime;

            SimUtil.DiseaseInfo disease_info = SimUtil.DiseaseInfo.Invalid;
            component2.ConsumeAndGetDisease(ElementLoader.FindElementByHash(component.consumedElement).tag, num2, out disease_info, out float aggregate_temperature);
            if (component.outputElement != SimHashes.Vacuum)
            {
                disease_info = SimUtil.CalculateFinalDiseaseInfo(invalid, disease_info);
                component2.AddLiquid(component.outputElement, num2, aggregate_temperature, disease_info.idx, disease_info.count, false, true);
            }
            return(diseaseRemoved > component.diseaseRemovalCount);
        }
Ejemplo n.º 3
0
    private void OnAbsorb(object data)
    {
        Pickupable pickupable = (Pickupable)data;

        if ((UnityEngine.Object)pickupable != (UnityEngine.Object)null)
        {
            PrimaryElement component      = GetComponent <PrimaryElement>();
            PrimaryElement primaryElement = pickupable.PrimaryElement;
            if ((UnityEngine.Object)primaryElement != (UnityEngine.Object)null)
            {
                float temperature = 0f;
                float mass        = component.Mass;
                float mass2       = primaryElement.Mass;
                if (mass > 0f && mass2 > 0f)
                {
                    temperature = SimUtil.CalculateFinalTemperature(mass, component.Temperature, mass2, primaryElement.Temperature);
                }
                else if (primaryElement.Mass > 0f)
                {
                    temperature = primaryElement.Temperature;
                }
                component.SetMassTemperature(mass + mass2, temperature);
                if ((UnityEngine.Object)CameraController.Instance != (UnityEngine.Object)null)
                {
                    string sound = GlobalAssets.GetSound("Ore_absorb", false);
                    if (sound != null && CameraController.Instance.IsAudibleSound(pickupable.transform.GetPosition(), sound))
                    {
                        PlaySound3D(sound);
                    }
                }
            }
        }
    }
Ejemplo n.º 4
0
    void Update()
    {
        //check for a navmesh hit
        foundPlacementPoint = PlacementManager.GetPlacementPoint(transform.position, Cam.transform.forward, Cam, ReachDistance, MaxPlaceDistance, ref placementPoint);

        if (inventoryObject != null && Input.GetKeyDown(KeyCode.P))
        {
            if (inventoryObject.gameObject.activeSelf)
            {
                SimUtil.TakeItem(inventoryObject);
            }
            else if (foundPlacementPoint)
            {
                PlacementManager.PlaceObjectAtPoint(inventoryObject, placementPoint);
            }
        }

        switch (Method)
        {
        case TestMethod.CheckVisibility:
        default:
            SimObjsInView = SimUtil.GetAllVisibleSimObjs(Cam, MaxDistance);
            FoundSimObjs  = SimObjsInView.Length > 0;
            NumItems      = SimObjsInView.Length;
            break;
        }


        //resize the array to avoid confusion in the test
        if (SimObjsInView.Length != NumItems)
        {
            Array.Resize <SimObj> (ref SimObjsInView, NumItems);
        }
    }
        public void PutObject(ServerAction response)
        {
            bool success = false;

            if (inventory.ContainsKey(response.objectId))
            {
                foreach (SimObj rso in VisibleSimObjs(response.forceVisible))
                {
                    if (rso.IsReceptacle && (rso.UniqueID == response.receptacleObjectId || rso.Type == response.ReceptableSimObjType()))
                    {
                        SimObj so = removeObjectInventory(response.objectId);

                        if ((!IsOpenable(rso) || IsOpen(rso)) &&
                            ((response.forceVisible && SimUtil.AddItemToReceptacle(so, rso.Receptacle)) ||
                             SimUtil.AddItemToVisibleReceptacle(so, rso.Receptacle, m_Camera)))
                        {
                            success = true;
                        }
                        else
                        {
                            addObjectInventory(so);
                        }


                        break;
                    }
                }
            }
            actionFinished(success);
        }
Ejemplo n.º 6
0
    void CheckForClearAndDelete(Receptacle r, int index, ref int deletedPivotIndex)
    {
        EditorGUILayout.BeginVertical();
        Rect deleteArea = GUILayoutUtility.GetRect(
            100.0f,
            25.0f);

        GUI.color = Color.Lerp(Color.grey, Color.yellow, 0.5f);
        if (GUI.Button(deleteArea, "Delete pivot"))
        {
            if (EditorUtility.DisplayDialog("Delete pivot", "Are you sure you want to delete pivot?", "Yes", "Cancel"))
            {
                deletedPivotIndex = index;
            }
        }
        Rect removeArea = GUILayoutUtility.GetRect(
            100.0f,
            25.0f);

        if (r.Pivots[index].childCount > 0)
        {
            GUI.color = Color.white;
        }
        else
        {
            GUI.color = Color.grey;
        }
        if (GUI.Button(removeArea, "Clear pivot") && r.Pivots[index].transform.childCount > 0)
        {
            Transform item = r.Pivots[index].GetChild(0);
            SimUtil.TakeItem(item.GetComponent <SimObj>());
        }
        EditorGUILayout.EndVertical();
    }
    public void AddDisease(HandleVector <int> .Handle h, byte disease_idx, int disease_count)
    {
        Data data = GetData(h);

        SimUtil.DiseaseInfo diseaseInfo = SimUtil.CalculateFinalDiseaseInfo(disease_idx, disease_count, data.diseaseIdx, data.diseaseCount);
        data.diseaseIdx   = diseaseInfo.idx;
        data.diseaseCount = diseaseInfo.count;
        SetData(h, data);
    }
        private void SpawnGeneShuffler()
        {
            // sacrifice morb
            var morb = smi.GetMorb();

            if (morb != null)
            {
                storage.Drop(morb);
                morb.DeleteObject();
            }
            // спавним новый калибратор но без заряда и без лора
            var geneShuffler = GameUtil.KInstantiate(Assets.GetPrefab("GeneShuffler"), gameObject.transform.GetPosition(), Grid.SceneLayer.Building);

            geneShuffler.GetComponent <GeneShuffler>().IsConsumed = true;
            var loreBearer = geneShuffler.GetComponent <LoreBearer>();

            if (loreBearer != null)
            {
                BeenClicked.Set(loreBearer, true);
            }
            var builded = geneShuffler.GetComponent <BuildedGeneShuffler>();

            builded.isBuilded = true;
            // список конструкционных материалов
            var tag_list  = new List <Tag>();
            var mass_list = new List <float>();

            for (int i = 0; i < deconstructable.constructionElements.Length; i++)
            {
                tag_list.Add(deconstructable.constructionElements[i]);
                mass_list.Add(building.Def.Mass[i]);
            }
            // вычисляем конечную температуру и микробов, с учетом самой постройки и хранилищща
            var geneShufflerPE = geneShuffler.GetComponent <PrimaryElement>();
            var MyPE           = GetComponent <PrimaryElement>();

            geneShufflerPE.SetElement(MyPE.ElementID);
            geneShufflerPE.AddDisease(MyPE.DiseaseIdx, MyPE.DiseaseCount, "");
            float mass = MyPE.Mass;
            float temp = MyPE.Temperature;

            for (int i = 0; i < storage.Count; i++)
            {
                var itemPE = storage.items[i].GetComponent <PrimaryElement>();
                tag_list.Add(itemPE.Element.tag);
                mass_list.Add(itemPE.Mass);
                temp  = SimUtil.CalculateFinalTemperature(mass * MyPE.Element.specificHeatCapacity, temp, itemPE.Mass * itemPE.Element.specificHeatCapacity, itemPE.Temperature);
                mass += itemPE.Mass;
                geneShufflerPE.AddDisease(itemPE.DiseaseIdx, itemPE.DiseaseCount, "");
            }
            geneShufflerPE.Temperature = temp;
            geneShuffler.GetComponent <Deconstructable>().constructionElements = tag_list.ToArray();
            builded.constructionMass = mass_list.ToArray();
            storage.ConsumeAllIgnoringDisease();
            geneShuffler.SetActive(true);
            gameObject.DeleteObject();
        }
Ejemplo n.º 9
0
    private void OnSplitFromChunk(object data)
    {
        Pickupable pickupable = (Pickupable)data;

        if (!((UnityEngine.Object)pickupable == (UnityEngine.Object)null))
        {
            float percent = Units / (Units + pickupable.PrimaryElement.Units);
            SimUtil.DiseaseInfo percentOfDisease = SimUtil.GetPercentOfDisease(pickupable.PrimaryElement, percent);
            AddDisease(percentOfDisease.idx, percentOfDisease.count, "PrimaryElement.SplitFromChunk");
            pickupable.PrimaryElement.ModifyDiseaseCount(-percentOfDisease.count, "PrimaryElement.SplitFromChunk");
        }
    }
    public void Sim200ms(float dt)
    {
        average_kilowatts_exchanged.AddSample(currentExchangeWattage * 0.001f);
        averageTemperatureTransferPerSecond.SetValue(SimUtil.EnergyFlowToTemperatureDelta(average_kilowatts_exchanged.GetWeightedAverage, primaryElement.Element.specificHeatCapacity, primaryElement.Mass));
        float num = 0f;

        foreach (AttributeModifier nonSimTemperatureModifier in NonSimTemperatureModifiers)
        {
            num += nonSimTemperatureModifier.Value;
        }
        if (Sim.IsValidHandle(simHandle))
        {
            SimMessages.ModifyElementChunkEnergy(simHandle, num * dt * (primaryElement.Mass * 1000f) * primaryElement.Element.specificHeatCapacity * 0.001f);
        }
    }
Ejemplo n.º 11
0
    private static Color GetDiseaseColour(SimDebugView instance, int cell)
    {
        Color result = Color.black;

        if (Grid.DiseaseIdx[cell] != 255)
        {
            Disease disease = Db.Get().Diseases[Grid.DiseaseIdx[cell]];
            result   = disease.overlayColour;
            result.a = SimUtil.DiseaseCountToAlpha(Grid.DiseaseCount[cell]);
        }
        else
        {
            result.a = 0f;
        }
        return(result);
    }
Ejemplo n.º 12
0
        public void PickupObject(ServerAction action)
        {
            bool success = false;

            bool objectVisible = false;

            foreach (SimObj so in VisibleSimObjs(action))
            {
                objectVisible = true;
                Debug.Log(" got sim object: " + so.UniqueID);
                if (!so.IsReceptacle && (!IsOpenable(so) || so.Manipulation == SimObjManipType.Inventory))
                {
                    if (inventory.Count == 0)
                    {
                        Debug.Log("trying to take item: " + so.UniqueID);
                        SimUtil.TakeItem(so);
                        addObjectInventory(so);
                        success = true;
                    }
                    else
                    {
                        errorCode = ServerActionErrorCode.InventoryFull;
                    }
                    break;
                }
                else
                {
                    errorCode = ServerActionErrorCode.ObjectNotPickupable;
                }
            }

            if (success)
            {
                errorCode = ServerActionErrorCode.Undefined;
            }
            else
            {
                if (!objectVisible)
                {
                    errorCode = ServerActionErrorCode.ObjectNotVisible;
                }
            }
            Debug.Log("error code: " + errorCode);

            StartCoroutine(checkWaitAction(success));
        }
Ejemplo n.º 13
0
    public void ReleaseGasPressure(float dt)
    {
        PrimaryElement primaryElement = storage.FindPrimaryElement(gasElement);

        if ((Object)primaryElement != (Object)null && primaryElement.Mass > 0f)
        {
            float num = releaseGasRate * dt;
            if ((Object)base.worker != (Object)null)
            {
                num *= GetEfficiencyMultiplier(base.worker);
            }
            num = Mathf.Min(num, primaryElement.Mass);
            SimUtil.DiseaseInfo percentOfDisease = SimUtil.GetPercentOfDisease(primaryElement, num / primaryElement.Mass);
            primaryElement.Mass -= num;
            Game.Instance.accumulators.Accumulate(accumulator, num);
            SimMessages.AddRemoveSubstance(Grid.PosToCell(this), ElementLoader.GetElementIndex(gasElement), null, num, primaryElement.Temperature, percentOfDisease.idx, percentOfDisease.count, true, -1);
        }
        UpdatePressurePercent();
    }
Ejemplo n.º 14
0
        private void PutObject_ray(string item)
        {
            int        x   = Screen.width / 2;
            int        y   = Screen.height / 2;
            Ray        ray = m_Camera.GetComponent <Camera>().ScreenPointToRay(new Vector3(x, y));
            RaycastHit hit = new RaycastHit();

            if (Physics.Raycast(ray, out hit))
            {
                //check if the receptacle is in visible range
                bool inrange = false;
                //check if the object we are trying to put something in is in visible range
                foreach (SimObj o in currentVisibleObjects)
                {
                    //check if the ID of the object we are looking at is in array of visible objects
                    if (hit.transform.GetComponent <SimObj>().UniqueID == o.UniqueID)
                    {
                        inrange = true;
                    }
                }

                if (inrange)
                {
                    //if (SimUtil.AddItemToVisibleReceptacle(inventory[current_Object_In_Inventory], hit.transform.GetComponent<Receptacle>(), gameObject.GetComponentInChildren<Camera>()) == false)


                    if (SimUtil.AddItemToReceptacle(inventory[current_Object_In_Inventory], hit.transform.GetComponent <Receptacle>()) == false)
                    {
                        Debug.Log("There's no space for that!");
                    }

                    else
                    {
                        removeObjectInventory(current_Object_In_Inventory);
                    }
                }

                if (!inrange)
                {
                    Debug.Log("It's too far away to put stuff in");
                }
            }
        }
Ejemplo n.º 15
0
        private void ConduitUpdate(float dt)
        {
            var flowManager = Conduit.GetFlowManager(Type);

            if (flowManager == null)
            {
                return;
            }

            var inputContents = flowManager.GetContents(inputCell);

            if (!TeleStorageData.Instance.storedElementsMap.ContainsKey(inputContents.element))
            {
                TeleStorageData.Instance.storedElementsMap[inputContents.element] = new StoredItem();
            }
            StoredItem inputStored = TeleStorageData.Instance.storedElementsMap[inputContents.element];

            if (inputContents.mass > 0.0f && !float.IsNaN(inputStored.temperature) && !float.IsNaN(inputContents.temperature))
            {
                inputStored.temperature = GameUtil.GetFinalTemperature(inputStored.temperature, inputStored.mass, inputContents.temperature, inputContents.mass);
                inputStored.mass       += inputContents.mass;
                SimUtil.DiseaseInfo diseaseInfo = SimUtil.CalculateFinalDiseaseInfo(inputContents.diseaseIdx, inputContents.diseaseCount, inputStored.diseaseIdx, inputStored.diseaseCount);
                inputStored.diseaseIdx   = diseaseInfo.idx;
                inputStored.diseaseCount = diseaseInfo.count;
                TeleStorageData.Instance.FireRefresh();
                flowManager.RemoveElement(inputCell, inputContents.mass);
            }

            if (!IsOperational || !TeleStorageData.Instance.storedElementsMap.ContainsKey(FilteredElement))
            {
                return;
            }
            StoredItem outputStored   = TeleStorageData.Instance.storedElementsMap[FilteredElement];
            var        possibleOutput = Math.Min(outputStored.mass, Flow / TeleStorageFlowControl.GramsPerKilogram);

            if (possibleOutput > 0.0f)
            {
                var delta = flowManager.AddElement(outputCell, FilteredElement, possibleOutput, outputStored.temperature, 0, 0);
                outputStored.mass -= delta;
                TeleStorageData.Instance.FireRefresh();
            }
        }
Ejemplo n.º 16
0
 private void OnSimConsume(Sim.MassConsumedCallback mass_cb_info)
 {
     if (consumedAmount == 0f)
     {
         temperature = mass_cb_info.temperature;
     }
     else
     {
         temperature = GameUtil.GetFinalTemperature(temperature, consumedAmount, mass_cb_info.temperature, mass_cb_info.mass);
     }
     consumedAmount += mass_cb_info.mass;
     lastTickAmount  = mass_cb_info.mass;
     diseaseInfo     = SimUtil.CalculateFinalDiseaseInfo(diseaseInfo.idx, diseaseInfo.count, mass_cb_info.diseaseIdx, mass_cb_info.diseaseCount);
     if (consumedAmount >= amountToPickup)
     {
         amountPerTick  = 0f;
         lastTickAmount = 0f;
     }
     ConsumeMass();
 }
Ejemplo n.º 17
0
 private void OnSimConsume(Sim.MassConsumedCallback mass_cb_info)
 {
     if (mass_cb_info.mass > 0f)
     {
         this.storedTemperature = SimUtil.CalculateFinalTemperature(this.storedMass, this.storedTemperature, mass_cb_info.mass, mass_cb_info.temperature);
         this.storedMass       += mass_cb_info.mass;
         SimUtil.DiseaseInfo diseaseInfo = SimUtil.CalculateFinalDiseaseInfo(this.diseaseIdx, this.diseaseCount, mass_cb_info.diseaseIdx, mass_cb_info.diseaseCount);
         this.diseaseIdx   = diseaseInfo.idx;
         this.diseaseCount = diseaseInfo.count;
         if (this.storedMass > this.minConvertMass && this.simEmitCBHandle.IsValid())
         {
             Game.Instance.massEmitCallbackManager.GetItem(this.simEmitCBHandle);
             this.gasStorage.AddGasChunk(this.srcElem, this.storedMass, this.storedTemperature, this.diseaseIdx, this.diseaseCount, true, true);
             this.storedMass        = 0f;
             this.storedTemperature = 0f;
             this.diseaseIdx        = 255;
             this.diseaseCount      = 0;
         }
     }
 }
        public void PickupObject(ServerAction action)
        {
            bool success = false;

            foreach (SimObj so in VisibleSimObjs(action))
            {
                Debug.Log(" got sim object: " + so.UniqueID);
                if (!so.IsReceptacle && (!IsOpenable(so) || so.Manipulation == SimObjManipType.Inventory))
                {
                    if (inventory.Count == 0)
                    {
                        Debug.Log("trying to take item: " + so.UniqueID);
                        SimUtil.TakeItem(so);
                        addObjectInventory(so);
                        success = true;
                    }
                    break;
                }
            }
            actionFinished(success);
        }
Ejemplo n.º 19
0
    protected override bool OnWorkTick(Worker worker, float dt)
    {
        PrimaryElement component = worker.GetComponent <PrimaryElement>();

        if (component.DiseaseCount > 0)
        {
            SimUtil.DiseaseInfo diseaseInfo = default(SimUtil.DiseaseInfo);
            diseaseInfo.idx   = component.DiseaseIdx;
            diseaseInfo.count = Mathf.CeilToInt((float)component.DiseaseCount * (1f - Mathf.Pow(fractionalDiseaseRemoval, dt)) - (float)absoluteDiseaseRemoval);
            SimUtil.DiseaseInfo b = diseaseInfo;
            component.ModifyDiseaseCount(-b.count, "Shower.RemoveDisease");
            accumulatedDisease = SimUtil.CalculateFinalDiseaseInfo(accumulatedDisease, b);
            Storage        component2     = GetComponent <Storage>();
            PrimaryElement primaryElement = component2.FindPrimaryElement(outputTargetElement);
            if ((Object)primaryElement != (Object)null)
            {
                PrimaryElement component3 = primaryElement.GetComponent <PrimaryElement>();
                component3.AddDisease(accumulatedDisease.idx, accumulatedDisease.count, "Shower.RemoveDisease");
                accumulatedDisease = SimUtil.DiseaseInfo.Invalid;
            }
        }
        return(false);
    }
Ejemplo n.º 20
0
    public int AddDisease(HandleVector <int> .Handle h, byte disease_idx, int disease_count)
    {
        GetData(h, out DiseaseHeader header, out DiseaseContainer payload);
        SimUtil.DiseaseInfo diseaseInfo = SimUtil.CalculateFinalDiseaseInfo(disease_idx, disease_count, header.diseaseIdx, header.diseaseCount);
        bool flag = header.diseaseIdx != diseaseInfo.idx;

        header.diseaseIdx   = diseaseInfo.idx;
        header.diseaseCount = diseaseInfo.count;
        if (flag && diseaseInfo.idx != 255)
        {
            EvaluateGrowthConstants(header, ref payload);
            SetData(h, header, ref payload);
        }
        else
        {
            SetHeader(h, header);
        }
        if (flag)
        {
            header.primaryElement.Trigger(-283306403, null);
        }
        return(header.diseaseCount);
    }
Ejemplo n.º 21
0
        public void Initialize(ServerAction response)
        {
            sceneConfig = sceneConfigList.configs [response.sceneConfigIndex];
            Dictionary <string, SimObj> simobjLookup = new Dictionary <string, SimObj> ();

            SimObj[] simObjects = GameObject.FindObjectsOfType(typeof(SimObj)) as SimObj[];

            for (int i = 0; i < simObjects.Length; i++)
            {
                SimObj so = simObjects [i];
                simobjLookup [so.UniqueID] = so;
                // only pick everything up if we have a list of receptacle/object pairs
                if (IsPickupable(so) && sceneConfig.receptacleObjectPairs.Length > 0)
                {
                    SimUtil.TakeItem(so);
                }
                if (IsOpenable(so))
                {
                    if (Array.IndexOf(sceneConfig.openReceptacles, so.UniqueID) >= 0)
                    {
                        openSimObj(so);
                    }
                    else
                    {
                        closeSimObj(so);
                    }
                }
            }
            foreach (ReceptacleObjectPair rop in sceneConfig.receptacleObjectPairs)
            {
                SimObj o = simobjLookup [rop.objectId];
                SimObj r = simobjLookup [rop.receptacleObjectId];
                SimUtil.AddItemToReceptaclePivot(o, r.Receptacle.Pivots [rop.pivot]);
            }

            InitializePositionRotation(response);
        }
        // empty target receptacle and put object into receptacle

        public void Replace(ServerAction response)
        {
            bool success = false;

            SimObj[] simObjs = SceneManager.Current.ObjectsInScene.ToArray();
            foreach (SimObj rso in simObjs)
            {
                if (response.receptacleObjectId == rso.UniqueID)
                {
                    foreach (SimObj so in SimUtil.GetItemsFromReceptacle(rso.Receptacle))
                    {
                        SimUtil.TakeItem(so);
                    }
                    foreach (SimObj so in simObjs)
                    {
                        if (so.UniqueID == response.objectId && SimUtil.AddItemToReceptaclePivot(so, rso.Receptacle.Pivots[response.pivot]))
                        {
                            success = true;
                        }
                    }
                }
            }
            actionFinished(success);
        }
Ejemplo n.º 23
0
 private void OnSimEmitted(Sim.MassEmittedCallback info)
 {
     if (info.suceeded != 1)
     {
         this.storedTemperature = SimUtil.CalculateFinalTemperature(this.storedMass, this.storedTemperature, info.mass, info.temperature);
         this.storedMass       += info.mass;
         if (info.diseaseIdx != 255)
         {
             SimUtil.DiseaseInfo a = new SimUtil.DiseaseInfo
             {
                 idx   = this.diseaseIdx,
                 count = this.diseaseCount
             };
             SimUtil.DiseaseInfo b = new SimUtil.DiseaseInfo
             {
                 idx   = info.diseaseIdx,
                 count = info.diseaseCount
             };
             SimUtil.DiseaseInfo diseaseInfo = SimUtil.CalculateFinalDiseaseInfo(a, b);
             this.diseaseIdx   = diseaseInfo.idx;
             this.diseaseCount = diseaseInfo.count;
         }
     }
 }
Ejemplo n.º 24
0
 public SimObj[] VisibleSimObjs()
 {
     return(SimUtil.GetAllVisibleSimObjs(m_Camera, maxVisibleDistance));
 }
Ejemplo n.º 25
0
        private ObjectMetadata[] generateObjectMetadataForTag(string tag, bool isAnimated)
        {
            // Encode these in a json string and send it to the server
            SimObj[] simObjects = GameObject.FindObjectsOfType(typeof(SimObj)) as SimObj[];

            HashSet <SimObj> visibleObjectIds = new HashSet <SimObj> ();

            foreach (SimObj so in VisibleSimObjs())
            {
                visibleObjectIds.Add(so);
            }
            int numObj = simObjects.Length;
            List <ObjectMetadata> metadata = new List <ObjectMetadata> ();

            for (int k = 0; k < numObj; k++)
            {
                ObjectMetadata meta   = new ObjectMetadata();
                SimObj         simObj = simObjects [k];
                if (this.excludeObject(simObj))
                {
                    continue;
                }
                GameObject o = simObj.gameObject;


                meta.name     = o.name;
                meta.position = o.transform.position;
                meta.rotation = o.transform.eulerAngles;

                meta.objectType = Enum.GetName(typeof(SimObjType), simObj.Type);
                meta.receptacle = simObj.IsReceptacle;
                meta.openable   = IsOpenable(simObj);
                if (meta.openable)
                {
                    meta.isopen = IsOpen(simObj);
                }
                meta.pickupable = IsPickupable(simObj);

                if (meta.receptacle)
                {
                    List <string> receptacleObjectIds = new List <string> ();
                    foreach (SimObj cso in SimUtil.GetItemsFromReceptacle(simObj.Receptacle))
                    {
                        receptacleObjectIds.Add(cso.UniqueID);
                    }
                    List <PivotSimObj> pivotSimObjs = new List <PivotSimObj> ();
                    for (int i = 0; i < simObj.Receptacle.Pivots.Length; i++)
                    {
                        Transform t = simObj.Receptacle.Pivots [i];
                        if (t.childCount > 0)
                        {
                            SimObj      psimobj = t.GetChild(0).GetComponent <SimObj> ();
                            PivotSimObj pso     = new PivotSimObj();
                            pso.objectId = psimobj.UniqueID;
                            pso.pivotId  = i;
                            pivotSimObjs.Add(pso);
                        }
                    }
                    meta.pivotSimObjs        = pivotSimObjs.ToArray();
                    meta.receptacleObjectIds = receptacleObjectIds.ToArray();
                    meta.receptacleCount     = simObj.Receptacle.Pivots.Length;
                }

                meta.objectId = simObj.UniqueID;


                meta.visible  = (visibleObjectIds.Contains(simObj));
                meta.distance = Vector3.Distance(transform.position, o.transform.position);

                metadata.Add(meta);
            }
            return(metadata.ToArray());
        }
Ejemplo n.º 26
0
        private void Update()
        {
            RotateView();


            SimObj[] simObjects = GameObject.FindObjectsOfType(typeof(SimObj)) as SimObj[];


//			if (pickupObject) {
//				GameObject hand = GameObject.Find ("FirstPersonHand");
//
//				foreach (SimObj so in simObjects) {
//					if (so.UniqueID == "Lettuce|+01.36|+00.99|+00.79") {
//						Rigidbody rb = so.GetComponentInChildren (typeof(Rigidbody)) as Rigidbody;
//						rb.useGravity = false;
//						so.transform.position = hand.transform.position;
//						so.transform.parent = this.transform;
//						so.transform.parent = m_CharacterController.transform;
//
//					}
//				}
//				Vector3 target = new Vector3 (hand.transform.position.x - 0.5f, hand.transform.position.y, hand.transform.position.z);
//				hand.transform.position = Vector3.MoveTowards (hand.transform.position, target, 0.01f);
//			} else {
//				foreach (SimObj so in simObjects) {
//					if (so.UniqueID == "Lettuce|+01.36|+00.99|+00.79") {
//						Rigidbody rb = so.GetComponentInChildren (typeof(Rigidbody)) as Rigidbody;
//						rb.useGravity = true;
//						so.transform.parent = null;
//
//					}
//				}
//			}
//

            if (captureScreenshot)
            {
                screenshotCounter++;
                StartCoroutine(EmitFrame());
                captureScreenshot = false;
            }

            // the jump state needs to read here to make sure it is not missed
            if (!m_Jump)
            {
                m_Jump = CrossPlatformInputManager.GetButtonDown("Jump");
            }

            if (!m_PreviouslyGrounded && m_CharacterController.isGrounded)
            {
                StartCoroutine(m_JumpBob.DoBobCycle());
                m_MoveDir.y = 0f;
                m_Jumping   = false;
            }
            if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded)
            {
                m_MoveDir.y = 0f;
            }

            currentVisibleObjects = SimUtil.GetAllVisibleSimObjs(m_Camera, MaxDistance);


            m_PreviouslyGrounded = m_CharacterController.isGrounded;
        }
Ejemplo n.º 27
0
    void TryToAddItem(UnityEngine.Object item, Transform pivot, Receptacle r)
    {
        if (pivot.childCount > 0)
        {
            Debug.Log("Pivot is already filled, not adding item");
            return;
        }

        if (EditorUtility.IsPersistent(r))
        {
            Debug.Log("Can't add items to a recepticle when not in scene, not adding");
            return;
        }

        GameObject itemGo = null;

        try {
            itemGo = (GameObject)item;
        } catch (Exception e) {
            Debug.Log(e);
            return;
        }

        if (item == null)
        {
            Debug.Log("Item was null, not adding");
            return;
        }

        if (itemGo == r.gameObject || itemGo.transform.IsChildOf(r.transform))
        {
            Debug.Log("Can't add item to itself, not adding");
            return;
        }

        if (EditorUtility.IsPersistent(itemGo))
        {
            // instantiate the object
            Debug.Log("Instantiating " + itemGo.name + " and placing in the scene");
            itemGo = GameObject.Instantiate(itemGo) as GameObject;
            return;
        }

        SimObj o = itemGo.GetComponent <SimObj>();

        if (o == null)
        {
            Debug.Log("Item was not a SimObj, not adding");
            return;
        }

        for (int i = 0; i < r.Pivots.Length; i++)
        {
            if (r.Pivots[i].childCount > 0)
            {
                foreach (Transform c in r.Pivots[i])
                {
                    if (c == itemGo.transform)
                    {
                        Debug.Log("Item is already in a pivot, not adding");
                        return;
                    }
                }
            }
        }

        // if we've made it this far the item is OK
        // parent it under the receptacle
        SimUtil.AddItemToReceptacle(o, r);
        // don't scale the item
    }
 public static float PotentialEnergyFlowToCreature(int cell, PrimaryElement transfererPrimaryElement, SimTemperatureTransfer temperatureTransferer, float deltaTime = 1f)
 {
     return(SimUtil.CalculateEnergyFlowCreatures(cell, transfererPrimaryElement.Temperature, transfererPrimaryElement.Element.specificHeatCapacity, transfererPrimaryElement.Element.thermalConductivity, temperatureTransferer.SurfaceArea, temperatureTransferer.Thickness));
 }
Ejemplo n.º 29
0
    public override void OnInspectorGUI()
    {
        SceneManager sm = (SceneManager)target;

        GUI.color = Color.white;
        EditorGUILayout.LabelField("Scene Options", EditorStyles.miniLabel);
        GUI.color = Color.grey;
        EditorGUILayout.BeginVertical(EditorStyles.helpBox);
        GUI.color           = Color.white;
        sm.SceneNumber      = EditorGUILayout.IntField("Scene Number", sm.SceneNumber);
        sm.LocalSceneType   = (SceneType)EditorGUILayout.EnumPopup("Scene Type", sm.LocalSceneType);
        sm.LocalPhysicsMode = (ScenePhysicsMode)EditorGUILayout.EnumPopup("Physics Mode", sm.LocalPhysicsMode);
        sm.AnimationMode    = (SceneAnimationMode)EditorGUILayout.EnumPopup("Animation Mode", sm.AnimationMode);

        EditorUtility.SetDirty(sm.gameObject);
        EditorUtility.SetDirty(sm);
        if (!Application.isPlaying)
        {
            UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene());
        }

        sm.FPSControllerPrefab = (GameObject)EditorGUILayout.ObjectField("FPS controller prefab:", sm.FPSControllerPrefab, typeof(GameObject), false);
        EditorGUILayout.LabelField("Actions:", EditorStyles.miniLabel);
        if (GUILayout.Button("Check for required object types", GUILayout.MaxWidth(300)))
        {
            TypesNotFound = sm.CheckSceneForRequiredTypes();
            ShowRequiredTypeCheckResult = true;
        }
        if (ShowRequiredTypeCheckResult)
        {
            if (TypesNotFound != null && TypesNotFound.Length > 0)
            {
                GUI.color = Color.Lerp(Color.red, Color.white, 0.5f);
                EditorGUILayout.LabelField("The following required types were NOT found:", EditorStyles.boldLabel);
                for (int i = 0; i < TypesNotFound.Length; i++)
                {
                    EditorGUILayout.LabelField(" - " + TypesNotFound [i].ToString(), EditorStyles.miniLabel);
                }
            }
            else
            {
                GUI.color = Color.Lerp(Color.green, Color.white, 0.5f);
                EditorGUILayout.LabelField("All required types were found!", EditorStyles.boldLabel);
            }
            if (GUILayout.Button("OK", GUILayout.MaxWidth(125)))
            {
                ShowRequiredTypeCheckResult = false;
            }
        }
        GUI.color = Color.white;
        if (GUILayout.Button("Gather SimObjs and assign unique IDs", GUILayout.MaxWidth(300)))
        {
            sm.GatherSimObjsInScene();
        }
        if (GUILayout.Button("Gather objects under parent folders", GUILayout.MaxWidth(300)))
        {
            sm.GatherObjectsUnderParents();
        }

        /*if (GUILayout.Button ("Set up FPS controller", GUILayout.MaxWidth(300))) {
         *      sm.SetUpFPSController ();
         * }*/
        if (GUILayout.Button("Replace generics with platonic objects", GUILayout.MaxWidth(300)))
        {
            if (EditorUtility.DisplayDialog("Confirm replace", "Are you SURE you want to do this?", "Yes", "Cancel"))
            {
                sm.ReplaceGenerics();
                sm.GatherSimObjsInScene();
            }
        }
        EditorGUILayout.EndVertical();

        GUI.color = Color.grey;
        EditorGUILayout.BeginVertical(EditorStyles.helpBox);
        GUI.color = Color.white;

        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.LabelField("Objects in scene:", EditorStyles.miniLabel);
        if (GUILayout.Button("Show / Hide", EditorStyles.toolbarButton, GUILayout.MaxWidth(125)))
        {
            ShowSceneObjects = !ShowSceneObjects;
        }
        EditorGUILayout.EndHorizontal();

        if (ShowSceneObjects)
        {
            if (sm.ObjectsInScene.Count == 0)
            {
                GUI.color = Color.Lerp(Color.white, Color.red, 0.5f);
                EditorGUILayout.LabelField("(None found)");
            }
            else
            {
                HashSet <string> uniqueIDsSoFar = new HashSet <string> ();
                for (int i = 0; i < sm.ObjectsInScene.Count; i++)
                {
                    if (sm.ObjectsInScene [i] == null)
                    {
                        Debug.Log("Found null items in sm objects list, returning");
                        sm.ObjectsInScene.Clear();
                        break;
                    }
                    if (!string.IsNullOrEmpty(sm.ObjectsInScene [i].Error))
                    {
                        GUI.color = Color.Lerp(Color.red, Color.white, 0.5f);
                    }
                    else
                    {
                        GUI.color = Color.white;
                    }
                    string buttonText = string.Empty;
                    if (!SimUtil.IsUniqueIDValid(sm.ObjectsInScene [i].UniqueID))
                    {
                        buttonText = sm.ObjectsInScene [i].Type.ToString() + ": (No ID)";
                    }
                    else
                    {
                        if (!uniqueIDsSoFar.Add(sm.ObjectsInScene [i].UniqueID))
                        {
                            GUI.color  = Color.Lerp(Color.red, Color.white, 0.5f);
                            buttonText = "ERROR: DUPLICATE ID! " + sm.ObjectsInScene [i].UniqueID;
                        }
                        else
                        {
                            buttonText = sm.ObjectsInScene [i].UniqueID;
                        }
                    }
                    if (GUILayout.Button(buttonText, EditorStyles.miniButton))
                    {
                        UnityEditor.Selection.activeGameObject = sm.ObjectsInScene [i].gameObject;
                    }
                }
            }
        }
        EditorGUILayout.EndVertical();

        GUI.color = Color.grey;
        EditorGUILayout.BeginVertical(EditorStyles.helpBox);
        GUI.color = Color.white;
        EditorGUILayout.LabelField("Item placement:", EditorStyles.miniLabel);
        if (GUILayout.Button("Auto-assign navmesh layers", GUILayout.MaxWidth(300)))
        {
            sm.AutoStructureNavigation();
        }
        EditorGUILayout.EndVertical();


        GUI.color = Color.white;
        EditorGUILayout.LabelField("Build Options", EditorStyles.miniLabel);
        GUI.color = Color.grey;
        EditorGUILayout.BeginVertical(EditorStyles.helpBox);
        GUI.color = Color.white;

        /*if (!showBuildOptions) {
         *      if (GUILayout.Button ("Show", EditorStyles.miniButton)) {
         *              showBuildOptions = true;
         *      }
         * } else if (GUILayout.Button ("Hide", EditorStyles.miniButton)) {
         *      showBuildOptions = false;
         * }*/

        string      scenePath   = string.Empty;
        string      buildName   = string.Empty;
        BuildTarget buildTarget = BuildTarget.StandaloneOSXIntel;

        if (showBuildOptions)
        {
            //figure out what scene we want to build
            List <string> dropdownOptions = new List <string> ();
            foreach (UnityEngine.Object scene in sm.Scenes)
            {
                dropdownOptions.Add(scene.name);
            }
            dropdownOptions.Sort(new NaturalStringComparer());
            sceneSelection = EditorGUILayout.Popup("Scene to build", sceneSelection, dropdownOptions.ToArray());
            string sceneToBuild = dropdownOptions [sceneSelection];

            EditorGUILayout.BeginHorizontal();
            if (string.IsNullOrEmpty(outputPath))
            {
                if (string.IsNullOrEmpty(SimUtil.DefaultBuildDirectory))
                {
                    outputPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                }
                else
                {
                    outputPath = SimUtil.DefaultBuildDirectory;
                }
            }
            outputPath = EditorGUILayout.TextField("Output Path", outputPath);
            if (GUILayout.Button("Choose..."))
            {
                outputPath = EditorUtility.OpenFolderPanel("Scene output path", outputPath, string.Empty);
            }
            EditorGUILayout.EndHorizontal();

            launchOnBuild = EditorGUILayout.Toggle("Launch on build", launchOnBuild);

            GUI.color = Color.yellow;
            foreach (BuildTarget bt in Targets)
            {
                if (GUILayout.Button("BUILD -> " + bt.ToString()))
                {
                    if (string.IsNullOrEmpty(outputPath) || !System.IO.Directory.Exists(outputPath))
                    {
                        EditorUtility.DisplayDialog("Invalid output path!", "Select a valid scene output path", "OK");
                    }
                    else
                    {
                        foreach (UnityEngine.Object sceneObject in sm.Scenes)
                        {
                            if (sceneObject.name == sceneToBuild)
                            {
                                scenePath = AssetDatabase.GetAssetPath(sceneObject);
                                buildName = sceneObject.name.Replace(".unity", "");
                            }
                        }
                    }
                }
            }
        }

        EditorGUILayout.EndVertical();

        if (!string.IsNullOrEmpty(scenePath))
        {
            SimUtil.BuildScene(scenePath, buildName, outputPath, buildTarget, launchOnBuild);
            return;
        }
    }
    private void ConvertMass()
    {
        float speedMultiplier = GetSpeedMultiplier();
        float num             = 1f * speedMultiplier;
        float num2            = 1f;

        for (int i = 0; i < consumedElements.Length; i++)
        {
            ConsumedElement consumedElement = consumedElements[i];
            float           num3            = consumedElement.massConsumptionRate * num * num2;
            if (num3 <= 0f)
            {
                num2 = 0f;
                break;
            }
            float num4 = 0f;
            for (int j = 0; j < storage.items.Count; j++)
            {
                GameObject gameObject = storage.items[j];
                if (!((UnityEngine.Object)gameObject == (UnityEngine.Object)null) && gameObject.HasTag(consumedElement.tag))
                {
                    PrimaryElement component = gameObject.GetComponent <PrimaryElement>();
                    float          num5      = Mathf.Min(num3, component.Mass);
                    num4 += num5 / num3;
                }
            }
            num2 = Mathf.Min(num2, num4);
        }
        if (!(num2 <= 0f))
        {
            SimUtil.DiseaseInfo diseaseInfo = SimUtil.DiseaseInfo.Invalid;
            diseaseInfo.idx   = byte.MaxValue;
            diseaseInfo.count = 0;
            float num6 = 0f;
            float num7 = 0f;
            float num8 = 0f;
            for (int k = 0; k < consumedElements.Length; k++)
            {
                ConsumedElement consumedElement2 = consumedElements[k];
                float           num9             = consumedElement2.massConsumptionRate * num * num2;
                Game.Instance.accumulators.Accumulate(consumedElement2.accumulator, num9);
                for (int l = 0; l < storage.items.Count; l++)
                {
                    GameObject gameObject2 = storage.items[l];
                    if (!((UnityEngine.Object)gameObject2 == (UnityEngine.Object)null))
                    {
                        if (gameObject2.HasTag(consumedElement2.tag))
                        {
                            PrimaryElement component2 = gameObject2.GetComponent <PrimaryElement>();
                            component2.KeepZeroMassObject = true;
                            float num10 = Mathf.Min(num9, component2.Mass);
                            float num11 = num10 / component2.Mass;
                            int   num12 = (int)(num11 * (float)component2.DiseaseCount);
                            float num13 = num10 * component2.Element.specificHeatCapacity;
                            num8            += num13;
                            num7            += num13 * component2.Temperature;
                            component2.Mass -= num10;
                            component2.ModifyDiseaseCount(-num12, "ElementConverter.ConvertMass");
                            num6       += num10;
                            diseaseInfo = SimUtil.CalculateFinalDiseaseInfo(diseaseInfo.idx, diseaseInfo.count, component2.DiseaseIdx, num12);
                            num9       -= num10;
                            if (num9 <= 0f)
                            {
                                break;
                            }
                        }
                        if (num9 <= 0f)
                        {
                            Debug.Assert(num9 <= 0f);
                        }
                    }
                }
            }
            float num14 = (!(num8 > 0f)) ? 0f : (num7 / num8);
            if (onConvertMass != null && num6 > 0f)
            {
                onConvertMass(num6);
            }
            if (outputElements != null && outputElements.Length > 0)
            {
                for (int m = 0; m < outputElements.Length; m++)
                {
                    OutputElement       outputElement = outputElements[m];
                    SimUtil.DiseaseInfo a             = diseaseInfo;
                    if (totalDiseaseWeight <= 0f)
                    {
                        a.idx   = byte.MaxValue;
                        a.count = 0;
                    }
                    else
                    {
                        float num15 = outputElement.diseaseWeight / totalDiseaseWeight;
                        a.count = (int)((float)a.count * num15);
                    }
                    if (outputElement.addedDiseaseIdx != 255)
                    {
                        a = SimUtil.CalculateFinalDiseaseInfo(a, new SimUtil.DiseaseInfo
                        {
                            idx   = outputElement.addedDiseaseIdx,
                            count = outputElement.addedDiseaseCount
                        });
                    }
                    float num16 = outputElement.massGenerationRate * OutputMultiplier * num * num2;
                    Game.Instance.accumulators.Accumulate(outputElement.accumulator, num16);
                    float num17 = 0f;
                    num17 = ((!outputElement.useEntityTemperature && (num14 != 0f || outputElement.minOutputTemperature != 0f)) ? Mathf.Max(outputElement.minOutputTemperature, num14) : GetComponent <PrimaryElement>().Temperature);
                    Element element = ElementLoader.FindElementByHash(outputElement.elementHash);
                    if (outputElement.storeOutput)
                    {
                        PrimaryElement primaryElement = storage.AddToPrimaryElement(outputElement.elementHash, num16, num17);
                        if ((UnityEngine.Object)primaryElement == (UnityEngine.Object)null)
                        {
                            if (element.IsGas)
                            {
                                storage.AddGasChunk(outputElement.elementHash, num16, num17, a.idx, a.count, true, true);
                            }
                            else if (element.IsLiquid)
                            {
                                storage.AddLiquid(outputElement.elementHash, num16, num17, a.idx, a.count, true, true);
                            }
                            else
                            {
                                GameObject go = element.substance.SpawnResource(base.transform.GetPosition(), num16, num17, a.idx, a.count, true, false, false);
                                storage.Store(go, true, false, true, false);
                            }
                        }
                        else
                        {
                            primaryElement.AddDisease(a.idx, a.count, "ElementConverter.ConvertMass");
                        }
                    }
                    else
                    {
                        Vector3 position  = base.transform.GetPosition();
                        float   x         = position.x + outputElement.outputElementOffset.x;
                        Vector3 position2 = base.transform.GetPosition();
                        Vector3 vector    = new Vector3(x, position2.y + outputElement.outputElementOffset.y, 0f);
                        int     num18     = Grid.PosToCell(vector);
                        if (element.IsLiquid)
                        {
                            int idx = element.idx;
                            FallingWater.instance.AddParticle(num18, (byte)idx, num16, num17, a.idx, a.count, true, false, false, false);
                        }
                        else if (element.IsSolid)
                        {
                            element.substance.SpawnResource(vector, num16, num17, a.idx, a.count, false, false, false);
                        }
                        else
                        {
                            SimMessages.AddRemoveSubstance(num18, outputElement.elementHash, CellEventLogger.Instance.OxygenModifierSimUpdate, num16, num17, a.idx, a.count, true, -1);
                        }
                    }
                    if (outputElement.elementHash == SimHashes.Oxygen)
                    {
                        ReportManager.Instance.ReportValue(ReportManager.ReportType.OxygenCreated, num16, base.gameObject.GetProperName(), null);
                    }
                }
            }
            storage.Trigger(-1697596308, base.gameObject);
        }
    }