private void Emit(EnergyGenerator.OutputItem output, float dt, PrimaryElement root_pe) { Element element = ElementLoader.FindElementByHash(output.element); float num = output.creationRate * dt; if (output.store) { if (element.IsGas) { this.storage.AddGasChunk(output.element, num, root_pe.Temperature, 255, 0, true, true); } else if (element.IsLiquid) { this.storage.AddLiquid(output.element, num, root_pe.Temperature, 255, 0, true, true); } else { GameObject go = element.substance.SpawnResource(base.transform.GetPosition(), num, root_pe.Temperature, 255, 0, false, false, false); this.storage.Store(go, true, false, true, false); } } else { int cell = Grid.PosToCell(base.transform.GetPosition()); int num2 = Grid.OffsetCell(cell, output.emitOffset); float temperature = Mathf.Max(root_pe.Temperature, output.minTemperature); if (element.IsGas) { SimMessages.ModifyMass(num2, num, 255, 0, CellEventLogger.Instance.EnergyGeneratorModifyMass, temperature, output.element); } else if (element.IsLiquid) { int elementIndex = ElementLoader.GetElementIndex(output.element); FallingWater.instance.AddParticle(num2, (byte)elementIndex, num, temperature, 255, 0, true, false, false, false); } else { element.substance.SpawnResource(Grid.CellToPosCCC(num2, Grid.SceneLayer.Front), num, temperature, 255, 0, true, false, false); } } }
private static void AbsorbHeat(StatesInstance smi, float dt) { float num1 = smi.master._kjConsumptionRate * dt; Vector2I vector2I = smi.master._maxCheckOffset - smi.master._minCheckOffset + 1; int num2 = vector2I.x * vector2I.y; float num3 = num1 / num2; Grid.PosToXY(smi.master.transform.position, out var x1, out var y1); for (int y2 = smi.master._minCheckOffset.y; y2 <= smi.master._maxCheckOffset.y; ++y2) { for (int x2 = smi.master._minCheckOffset.x; x2 <= smi.master._maxCheckOffset.x; ++x2) { int cell = Grid.XYToCell(x1 + x2, y1 + y2); if (Grid.IsValidCell(cell) && Grid.Temperature[cell] > (double)smi.master._minTemperature) { smi.master._kjConsumed += num3; SimMessages.ModifyEnergy(cell, -num3, 3000f, SimMessages.EnergySourceID.HeatBulb); } } } }
private void CheckStorage() { //var bleachStoneTag = SimHashes.BleachStone.CreateTag(); for (int i = 0; i < storage.items.Count; i++) { GameObject storageItem = storage.items[i]; if (storageItem != null) { if (storageItem.HasTag(GameTags.AnyWater)) { continue; } i--; storage.Remove(storageItem); PrimaryElement element = storageItem.GetComponent <PrimaryElement>(); int disease_count = (int)(element.DiseaseCount * element.Mass); SimMessages.AddRemoveSubstance(Grid.PosToCell(transform.GetPosition()), element.Element.id, CellEventLogger.Instance.ConduitConsumerWrongElement, element.Mass, element.Temperature, element.DiseaseIdx, disease_count); } } }
private void CoolContents(float dt) { if (gasStorage.items.Count != 0) { float num = float.PositiveInfinity; float num2 = 0f; float num3 = 0f; foreach (GameObject item in gasStorage.items) { PrimaryElement component = item.GetComponent <PrimaryElement>(); if (!((Object)component == (Object)null) && !(component.Mass < 0.1f) && !(component.Temperature < minCooledTemperature)) { num2 = GameUtil.GetThermalEnergy(component); if (num > num2) { num = num2; } } } foreach (GameObject item2 in gasStorage.items) { PrimaryElement component = item2.GetComponent <PrimaryElement>(); if (!((Object)component == (Object)null) && !(component.Mass < 0.1f) && !(component.Temperature < minCooledTemperature)) { float num4 = Mathf.Min(num, 10f); GameUtil.DeltaThermalEnergy(component, 0f - num4, minCooledTemperature); num3 += num4; } } float num5 = Mathf.Abs(num3 * waterKGConsumedPerKJ); Game.Instance.accumulators.Accumulate(base.smi.master.waterConsumptionAccumulator, num5); if (num5 != 0f) { liquidStorage.ConsumeAndGetDisease(GameTags.Water, num5, out SimUtil.DiseaseInfo disease_info, out float _); SimMessages.ModifyDiseaseOnCell(Grid.PosToCell(base.gameObject), disease_info.idx, disease_info.count); UpdateMeter(); } } }
private unsafe static void OnSetTemperature(PrimaryElement primary_element, float temperature) { if (temperature <= 0f) { KCrashReporter.Assert(false, "STT.OnSetTemperature - Tried to set <= 0 degree temperature"); temperature = 293f; } SimTemperatureTransfer component = primary_element.GetComponent <SimTemperatureTransfer>(); if (Sim.IsValidHandle(component.simHandle)) { float mass = primary_element.Mass; float heat_capacity = (!(mass >= 0.01f)) ? 0f : (mass * primary_element.Element.specificHeatCapacity); SimMessages.SetElementChunkData(component.simHandle, temperature, heat_capacity); int handleIndex = Sim.GetHandleIndex(component.simHandle); Game.Instance.simData.elementChunks[handleIndex].temperature = temperature; } else { primary_element.InternalTemperature = temperature; } }
protected override void OnCleanUp() { UpdateDoorState(true); List <int> list = new List <int>(); int[] placementCells = building.PlacementCells; foreach (int num in placementCells) { SimMessages.ClearCellProperties(num, 12); Grid.RenderedByWorld[num] = Grid.Element[num].substance.renderedByWorld; Grid.FakeFloor[num] = false; if (Grid.Element[num].IsSolid) { SimMessages.ReplaceAndDisplaceElement(num, SimHashes.Vacuum, CellEventLogger.Instance.DoorOpen, 0f, -1f, byte.MaxValue, 0, -1); } Pathfinding.Instance.AddDirtyNavGridCell(num); if (rotatable.IsRotated) { list.Add(Grid.CellAbove(num)); list.Add(Grid.CellBelow(num)); } else { list.Add(Grid.CellLeft(num)); list.Add(Grid.CellRight(num)); } } int[] placementCells2 = building.PlacementCells; foreach (int num2 in placementCells2) { Grid.HasDoor[num2] = false; Grid.HasAccessDoor[num2] = false; Game.Instance.SetDupePassableSolid(num2, false, Grid.Solid[num2]); Grid.CritterImpassable[num2] = false; Grid.DupeImpassable[num2] = false; Pathfinding.Instance.AddDirtyNavGridCell(num2); } base.OnCleanUp(); }
private void PumpHeat(float dt) { #if CONSUME_ALL_HEAT float workHeat = heatToPumpDTU; #else float workHeat = heatToPumpDTU * currentEfficiency; #endif #if PRODUCE_LEFTOVER_HEAT currentGeneratedHeat = Mathf.Clamp(heatToPumpDTU - workHeat, 0, heatToPumpDTU); #elif PRODUCE_CONSTANT_HEAT currentGeneratedHeat = 0f; #elif PRODUCE_PROPORTIONAL_HEAT currentGeneratedHeat = workHeat * wasteHeatRatio; #else currentGeneratedHeat = 1f; #endif currentGeneratedPower = Mathf.Clamp(HeatToWatts(workHeat), 0, heatToPumpDTU); SimMessages.ModifyEnergy(heatSourceCell, -(heatToPumpDTU * dt / 1000f), 5000f, SimMessages.EnergySourceID.StructureTemperature); }
public void ModifyDiseaseCount(int delta, string reason) { if ((bool)diseaseRedirectTarget) { diseaseRedirectTarget.ModifyDiseaseCount(delta, reason); } else if (useSimDiseaseInfo) { int gameCell = Grid.PosToCell(this); SimMessages.ModifyDiseaseOnCell(gameCell, byte.MaxValue, delta); } else if (delta != 0 && diseaseHandle.IsValid()) { int num = GameComps.DiseaseContainers.ModifyDiseaseCount(diseaseHandle, delta); if (num <= 0 && !forcePermanentDiseaseContainer) { Trigger(-1689370368, false); GameComps.DiseaseContainers.Remove(base.gameObject); diseaseHandle.Clear(); } } }
private void UpdateFromNeighbours(int cellPos, Element cellElement, ref int cellCount) { foreach (int pos in new int[] { Grid.CellAbove(cellPos), Grid.CellBelow(cellPos), Grid.CellLeft(cellPos), Grid.CellBelow(cellPos) }) { if (!Grid.IsValidCell(pos)) { continue; } var element = Grid.Element[pos]; if (element.state == cellElement.state) { continue; } if (Grid.DiseaseIdx[pos] != radiationIdx) { continue; } int diff = Grid.DiseaseCount[pos] - cellCount; if (diff <= 0) { continue; } var growth = radiationDisease.GetGrowthRuleForElement(element); int increase = Mathf.RoundToInt(diff * growth.diffusionScale / 2); if (increase <= 0) { continue; } SimMessages.ModifyDiseaseOnCell(pos, radiationIdx, -increase); SimMessages.ModifyDiseaseOnCell(cellPos, radiationIdx, increase); cellCount += increase; } }
private void EmitContents() { if (gasStorage.items.Count != 0) { float num = 0.1f; float num2 = num; PrimaryElement primaryElement = null; for (int i = 0; i < gasStorage.items.Count; i++) { PrimaryElement component = gasStorage.items[i].GetComponent <PrimaryElement>(); if (component.Mass > num2 && component.Element.IsGas) { primaryElement = component; num2 = primaryElement.Mass; } } if ((Object)primaryElement != (Object)null) { SimMessages.AddRemoveSubstance(Grid.CellRight(Grid.CellAbove(Grid.PosToCell(base.gameObject))), ElementLoader.GetElementIndex(primaryElement.ElementID), CellEventLogger.Instance.ExhaustSimUpdate, primaryElement.Mass, primaryElement.Temperature, primaryElement.DiseaseIdx, primaryElement.DiseaseCount, true, -1); gasStorage.ConsumeIgnoringDisease(primaryElement.gameObject); } } }
public void SetupRiverTest() { InitDebugScenario(); int num = Mathf.Min(64, Grid.WidthInCells); int num2 = Mathf.Min(64, Grid.HeightInCells); List <Element> list = new List <Element>(); foreach (Element element in ElementLoader.elements) { if (element.IsLiquid) { list.Add(element); } } for (int i = 0; i < num2; i++) { for (int j = 0; j < num; j++) { SimHashes new_element = (i != 0) ? SimHashes.Oxygen : SimHashes.Unobtanium; SimMessages.ReplaceElement(Grid.XYToCell(j, i), new_element, CellEventLogger.Instance.Scenario, 1000f, -1f, byte.MaxValue, 0, -1); } } }
protected override void OnSpawn() { base.OnSpawn(); Subscribe(824508782, OnActiveChangedDelegate); smi = new StatesInstance(this); smi.StartSM(); accumulator = Game.Instance.accumulators.Add("Element", this); BuildingDef def = GetComponent <BuildingComplete>().Def; int cell = Grid.PosToCell(this); for (int i = 0; i < def.WidthInCells; i++) { int x = i - (def.WidthInCells - 1) / 2; int num = Grid.OffsetCell(cell, new CellOffset(x, 0)); SimMessages.SetCellProperties(num, 39); Grid.Foundation[num] = true; Grid.SetSolid(num, true, CellEventLogger.Instance.SimCellOccupierForceSolid); World.Instance.OnSolidChanged(num); GameScenePartitioner.Instance.TriggerEvent(num, GameScenePartitioner.Instance.solidChangedLayer, null); Grid.RenderedByWorld[num] = false; } meter = new MeterController(GetComponent <KBatchedAnimController>(), "meter_target", "meter", Meter.Offset.Infront, Grid.SceneLayer.NoLayer, "meter_target", "meter_fill", "meter_frame", "meter_OL"); }
protected override void OnPaintCell(int cell, int distFromOrigin) { base.OnPaintCell(cell, distFromOrigin); if (!recentlyAffectedCells.Contains(cell)) { recentlyAffectedCells.Add(cell); Game.CallbackInfo item = new Game.CallbackInfo(delegate { recentlyAffectedCells.Remove(cell); }, false); int index = Game.Instance.callbackManager.Add(item).index; float num = Grid.Temperature[cell]; num += SandboxToolParameterMenu.instance.settings.temperatureAdditive; num = Mathf.Clamp(num, 1f, 9999f); int gameCell = cell; SimHashes id = Grid.Element[cell].id; CellElementEvent sandBoxTool = CellEventLogger.Instance.SandBoxTool; float mass = Grid.Mass[cell]; float temperature = num; int callbackIdx = index; SimMessages.ReplaceElement(gameCell, id, sandBoxTool, mass, temperature, Grid.DiseaseIdx[cell], Grid.DiseaseCount[cell], callbackIdx); } }
/// <summary> /// Destroys the element (liquid, solid, or gas) in the cell. /// </summary> /// <param name="cell">The cell to destroy.</param> private void DestroyElement(int cell) { pendingCells.Add(cell); // Register a sim callback to unhighlight the cells when destroyed int index = Game.Instance.callbackManager.Add(new Game.CallbackInfo(delegate() { pendingCells.Remove(cell); })).index; SimMessages.ReplaceElement(cell, SimHashes.Vacuum, CellEventLogger.Instance. SandBoxTool, 0.0f, 0.0f, Klei.SimUtil.DiseaseInfo.Invalid.idx, 0, index); // Destroy any solid tiles / doors on the area as well to avoid bad states var destroy = HashSetPool <GameObject, FilteredDestroyTool> .Allocate(); for (int i = 0; i < (int)ObjectLayer.NumLayers; i++) { var obj = Grid.Objects[cell, i]; if (obj != null && obj.GetComponentSafe <SimCellOccupier>() != null) { destroy.Add(obj); } } DestroyAndRecycle(destroy); }
private static void AbsorbHeat(StatesInstance smi, float dt) { var consumedSinceLastUpdate = smi.master._kjConsumptionRate * dt; var vector2I = smi.master._maxCheckOffset - smi.master._minCheckOffset + 1; var affectedCells = vector2I.x * vector2I.y; var consumptionPerCell = consumedSinceLastUpdate / affectedCells; Grid.PosToXY(smi.master.transform.position, out var x1, out var y1); for (var y2 = smi.master._minCheckOffset.y; y2 <= smi.master._maxCheckOffset.y; ++y2) { for (var x2 = smi.master._minCheckOffset.x; x2 <= smi.master._maxCheckOffset.x; ++x2) { var cell = Grid.XYToCell(x1 + x2, y1 + y2); if (Grid.IsValidCell(cell) && Grid.Temperature[cell] > smi.master._minTemperature) { smi.master._kjConsumed += consumptionPerCell; SimMessages.ModifyEnergy(cell, -consumptionPerCell, 3000f, SimMessages.EnergySourceID.HeatBulb); } } } }
private void Emit(object data) { GameObject gameObject = (GameObject)data; float value = Db.Get().Amounts.Temperature.Lookup(this).value; Equippable equippable = GetComponent <SuitEquipper>().IsWearingAirtightSuit(); if ((Object)equippable != (Object)null) { equippable.GetComponent <Storage>().AddGasChunk(SimHashes.Methane, 0.1f, value, byte.MaxValue, 0, false, true); } else { Components.Cmps <MinionIdentity> liveMinionIdentities = Components.LiveMinionIdentities; Vector2 a = gameObject.transform.GetPosition(); for (int i = 0; i < liveMinionIdentities.Count; i++) { MinionIdentity minionIdentity = liveMinionIdentities[i]; if ((Object)minionIdentity.gameObject != (Object)gameObject.gameObject) { Vector2 b = minionIdentity.transform.GetPosition(); float num = Vector2.SqrMagnitude(a - b); if (num <= 2.25f) { minionIdentity.Trigger(508119890, Strings.Get("STRINGS.DUPLICANTS.DISEASES.PUTRIDODOUR.CRINGE_EFFECT").String); minionIdentity.gameObject.GetSMI <ThoughtGraph.Instance>().AddThought(Db.Get().Thoughts.PutridOdour); } } } int gameCell = Grid.PosToCell(gameObject.transform.GetPosition()); SimMessages.AddRemoveSubstance(gameCell, SimHashes.Methane, CellEventLogger.Instance.ElementConsumerSimUpdate, 0.1f, value, byte.MaxValue, 0, true, -1); KBatchedAnimController kBatchedAnimController = FXHelpers.CreateEffect("odor_fx_kanim", gameObject.transform.GetPosition(), gameObject.transform, true, Grid.SceneLayer.Front, false); kBatchedAnimController.Play(WorkLoopAnims, KAnim.PlayMode.Once); kBatchedAnimController.destroyOnAnimComplete = true; } KFMOD.PlayOneShot(GlobalAssets.GetSound("Dupe_Flatulence", false), base.transform.GetPosition()); }
protected void SimRegister() { if (base.isSpawned && simHandle == -1 && base.enabled) { PrimaryElement component = GetComponent <PrimaryElement>(); if (component.Mass > 0f) { Element element = component.Element; if (!element.IsTemperatureInsulated) { int gameCell = Grid.PosToCell(base.transform.GetPosition()); simHandle = -2; HandleVector <Game.ComplexCallbackInfo <int> > .Handle handle = Game.Instance.simComponentCallbackManager.Add(OnSimRegisteredCallback, this, "SimTemperatureTransfer.SimRegister"); float num = component.InternalTemperature; if (num <= 0f) { component.InternalTemperature = 293f; num = 293f; } SimMessages.AddElementChunk(gameCell, component.ElementID, component.Mass, num, surfaceArea, thickness, groundTransferScale, handle.index); } } } }
private void CleanSim(int cell) { if (!Grid.IsValidCell(cell)) { return; } Grid.Foundation[cell] = false; Grid.HasDoor[cell] = false; Game.Instance.SetDupePassableSolid(cell, false, Grid.Solid[cell]); Grid.CritterImpassable[cell] = false; Grid.DupeImpassable[cell] = false; var flags = Sim.Cell.Properties.GasImpermeable | Sim.Cell.Properties.Unbreakable | Sim.Cell.Properties.Transparent; if (!AllowLiquidThrough) { flags |= Sim.Cell.Properties.LiquidImpermeable; } SimMessages.ClearCellProperties(cell, (byte)flags); SimMessages.ReplaceAndDisplaceElement(cell, SimHashes.Vacuum, CellEventLogger.Instance.DoorOpen, 0); Pathfinding.Instance.AddDirtyNavGridCell(cell); }
private void TryEmit(PrimaryElement primary_elem) { if (primary_elem.Mass >= emitMass) { plasticMeter.SetPositionPercent(0f); GameObject gameObject = storage.Drop(primary_elem.gameObject, true); Rotatable component = GetComponent <Rotatable>(); Vector3 vector = component.transform.GetPosition() + component.GetRotatedOffset(emitOffset); int i = Grid.PosToCell(vector); if (Grid.Solid[i]) { vector += component.GetRotatedOffset(Vector3.left); } gameObject.transform.SetPosition(vector); PrimaryElement primaryElement = storage.FindPrimaryElement(exhaustElement); if ((Object)primaryElement != (Object)null) { int gameCell = Grid.PosToCell(vector); SimMessages.AddRemoveSubstance(gameCell, primaryElement.ElementID, null, primaryElement.Mass, primaryElement.Temperature, primaryElement.DiseaseIdx, primaryElement.DiseaseCount, true, -1); primaryElement.Mass = 0f; primaryElement.ModifyDiseaseCount(-2147483648, "Polymerizer.Exhaust"); } } }
/// <summary> /// Applied before InstantlyFinish runs. /// </summary> internal static bool Prefix(Diggable __instance, Worker worker, ref bool __result) { bool cont = true; if (__instance != null) { int cell = Grid.PosToCell(__instance); Element element; // Complete by removing the cell instantaneously if (Grid.IsValidCell(cell) && (element = Grid.Element[cell]) != null && element.hardness > 254) { if (worker != null) { // Give some experience worker.Work(1.0f); } SimMessages.Dig(cell); __result = true; cont = false; } } return(cont); }
private static bool Prefix(GasBreatherFromWorldProvider __instance, ref bool __result, ref OxygenBreather oxygen_breather, ref float gas_consumed) { //Debug.Log(" === AmphibiousMod_GasBreatherFromWorldProvider_ConsumeGas === "); Klei.AI.Traits traits = oxygen_breather.gameObject.GetComponent <Klei.AI.Traits>(); bool flag = traits.GetTraitIds().Contains("Amphibious"); if (!flag) { return(true); } SimHashes getBreathableElement = oxygen_breather.GetBreathableElement; if (getBreathableElement == SimHashes.Vacuum) { __result = false; return(false); } //HandleVector<Game.ComplexCallbackInfo<Sim.MassConsumedCallback>>.Handle handle = Game.Instance.massConsumedCallbackManager.Add(OnSimConsumeCallback, __instance, "GasBreatherFromWorldProvider"); //SimMessages.ConsumeMass(oxygen_breather.mouthCell, getBreathableElement, gas_consumed/5f, 3, handle.index); SimMessages.ConsumeMass(oxygen_breather.mouthCell, getBreathableElement, gas_consumed / 5f, 1); __result = true; return(false); }
public static void Emit(Instance smi, float dt) { if ((bool)smi.navigator) { GameObject gameObject = smi.sm.owner.Get(smi); if ((bool)gameObject) { int gameCell = Grid.PosToCell(gameObject.transform.GetPosition()); float a = 0.1f * dt; a = Mathf.Min(a, smi.jet_suit_tank.amount); smi.jet_suit_tank.amount -= a; float num = a * 3f; if (num > 1.401298E-45f) { SimMessages.AddRemoveSubstance(gameCell, SimHashes.CarbonDioxide, CellEventLogger.Instance.ElementConsumerSimUpdate, num, 473.15f, byte.MaxValue, 0, true, -1); } if (smi.jet_suit_tank.amount == 0f) { smi.navigator.AddTag(GameTags.JetSuitOutOfFuel); smi.navigator.SetCurrentNavType(NavType.Floor); } } } }
private void ConduitUpdate(float dt) { //If the building is broken, nothing normally stops it from operating! if (gameObject.GetComponent <BuildingHP>().HitPoints == 0) { return; } ConduitFlow manager = Conduit.GetFlowManager(valveBase.conduitType); ConduitFlow.Conduit inputConduit = manager.GetConduit(InputCell); ConduitFlow.Conduit outputConduit = manager.GetConduit(OutputCell); if (!manager.HasConduit(InputCell) || !manager.HasConduit(OutputCell)) { valveBase.UpdateAnim(); } else { ConduitFlow.ConduitContents inputContents = inputConduit.GetContents(manager); if (!bufferMode) { float valveFlow = valveBase.CurrentFlow * dt; float maxFlow; float temp; SimHashes element; byte diseaseIdx; float ratio; int disease_count; bool fromStorage = false; Tag storedTag = Tag.Invalid; if (!storage.IsEmpty()) { //If there is still mass within the storage but we are not in buffer mode, take nothing in until the storage is emptied! (while still following the limit mode settings) fromStorage = true; GameObject item = storage.items.FirstOrDefault(); PrimaryElement storedPrimary = item.GetComponent <PrimaryElement>(); maxFlow = Mathf.Min(valveFlow, storedPrimary.Mass); element = storedPrimary.ElementID; temp = storedPrimary.Temperature; diseaseIdx = storedPrimary.DiseaseIdx; ratio = maxFlow / storedPrimary.Mass; disease_count = (int)(ratio * (float)storedPrimary.DiseaseCount); storedTag = storedPrimary.Element.tag; } else { maxFlow = Mathf.Min(inputContents.mass, valveBase.CurrentFlow * dt); element = inputContents.element; temp = inputContents.temperature; diseaseIdx = inputContents.diseaseIdx; ratio = maxFlow / inputContents.mass; disease_count = (int)(ratio * (float)inputContents.diseaseCount); } if (maxFlow > 0f) { float movableMass = manager.AddElement(OutputCell, element, maxFlow, temp, diseaseIdx, disease_count); Game.Instance.accumulators.Accumulate(flowAccumulator, movableMass); if (movableMass > 0f) { //If we took the mass from storage, make sure we use the right function if (!fromStorage) { manager.RemoveElement(InputCell, movableMass); } else { storage.ConsumeIgnoringDisease(storedTag, movableMass); } } } } else { float availableInput = inputContents.mass; GameObject storedItem = storage.items.FirstOrDefault(); Element storedElement = storedItem?.GetComponent <PrimaryElement>().Element; float storedMass = storedItem != null?storedItem.GetComponent <PrimaryElement>().Mass : 0f; float maxOutputCapacity = Integration.GetMaxCapacityAt(OutputCell, valveBase.conduitType); //Override the set current flow if the output pipe cannot support a flow that large. This prevents the valve from storing, for example, 3KG, when it can only output 1KG at a time. float minimumOutput = Mathf.Min(maxOutputCapacity, valveBase.CurrentFlow); storage.capacityKg = maxOutputCapacity; float movableToStorage = Mathf.Min(availableInput, storage.RemainingCapacity()); if (movableToStorage > 0f) { Element inputElement = ElementLoader.FindElementByHash(inputContents.element); float ratio = movableToStorage / inputContents.mass; int transferredDisease = (int)((float)inputContents.diseaseCount * ratio); if (inputElement == storedElement || storedItem == null) { if (valveBase.conduitType == ConduitType.Gas) { storage.AddGasChunk(inputContents.element, movableToStorage, inputContents.temperature, inputContents.diseaseIdx, transferredDisease, false); } else { storage.AddLiquid(inputContents.element, movableToStorage, inputContents.temperature, inputContents.diseaseIdx, transferredDisease, false); } storedMass += movableToStorage; if (storedItem == null) { storedElement = inputElement; } } else { //The input has a different element than what is in storage! Deal damage and remove however much mass attempted to flow into the valve. Trigger(-794517298, new BuildingHP.DamageSourceInfo { damage = 1, source = STRINGS.BUILDINGS.DAMAGESOURCES.BAD_INPUT_ELEMENT, popString = STRINGS.UI.GAMEOBJECTEFFECTS.DAMAGE_POPS.WRONG_ELEMENT }); SimMessages.AddRemoveSubstance(Grid.PosToCell(base.transform.GetPosition()), inputContents.element, CellEventLogger.Instance.ConduitConsumerWrongElement, movableToStorage, inputContents.temperature, inputContents.diseaseIdx, transferredDisease); } manager.RemoveElement(InputCell, movableToStorage); } ConduitFlow.ConduitContents outputContents = outputConduit.GetContents(manager); float initialOutputMass = outputContents.mass; Element outputElement = ElementLoader.FindElementByHash(outputContents.element); //If we can create a packet of at least size CurrentFlow, including if we combined the valve's output into what is already in the output conduit //Debug.Log($"[TogglableValve] InitialOut: {initialOutputMass}, StoredMass: {storedMass}, MinimumOutput: {minimumOutput}, MaxOutputCapacity: {maxOutputCapacity}, AvailableInput: {availableInput}, MovableToStorage: {movableToStorage}"); if (initialOutputMass + storedMass >= minimumOutput && (storedElement == outputElement || outputElement == null || outputElement.id == SimHashes.Vacuum)) { float movableToOut = Mathf.Min(storedMass, maxOutputCapacity - initialOutputMass); if (movableToOut > 0f) { PrimaryElement storedPrimary = storage.items.FirstOrDefault()?.GetComponent <PrimaryElement>(); float ratio = movableToOut / storedMass; int transferredDisease = (int)((float)storedPrimary.DiseaseCount * ratio); float totalMovedOut = manager.AddElement(OutputCell, storedPrimary.ElementID, storedMass, storedPrimary.Temperature, storedPrimary.DiseaseIdx, transferredDisease); Game.Instance.accumulators.Accumulate(flowAccumulator, totalMovedOut); if (totalMovedOut > 0f) { storage.ConsumeIgnoringDisease(storedPrimary.Element.tag, totalMovedOut); } } } } valveBase.UpdateAnim(); } }
public void OnKeyDown(KButtonEvent e) { if (!enabled) { return; } if (e.TryConsume(Action.DebugSpawnMinion)) { SpawnMinion(); } else if (e.TryConsume(Action.DebugSpawnStressTest)) { for (int i = 0; i < 60; i++) { SpawnMinion(); } } else if (e.TryConsume(Action.DebugSuperTestMode)) { if (!superTestMode) { Time.timeScale = 15f; superTestMode = true; } else { Time.timeScale = 1f; superTestMode = false; } } else if (e.TryConsume(Action.DebugUltraTestMode)) { if (!ultraTestMode) { Time.timeScale = 30f; ultraTestMode = true; } else { Time.timeScale = 1f; ultraTestMode = false; } } else if (e.TryConsume(Action.DebugSlowTestMode)) { if (!slowTestMode) { Time.timeScale = 0.06f; slowTestMode = true; } else { Time.timeScale = 1f; slowTestMode = false; } } else if (e.TryConsume(Action.DebugDig)) { int mouseCell = GetMouseCell(); SimMessages.Dig(mouseCell, -1); } else if (e.TryConsume(Action.DebugInstantBuildMode)) { InstantBuildMode = !InstantBuildMode; if ((UnityEngine.Object)Game.Instance == (UnityEngine.Object)null) { return; } if ((UnityEngine.Object)PlanScreen.Instance != (UnityEngine.Object)null) { PlanScreen.Instance.Refresh(); } if ((UnityEngine.Object)BuildMenu.Instance != (UnityEngine.Object)null) { BuildMenu.Instance.Refresh(); } if ((UnityEngine.Object)OverlayMenu.Instance != (UnityEngine.Object)null) { OverlayMenu.Instance.Refresh(); } if ((UnityEngine.Object)ConsumerManager.instance != (UnityEngine.Object)null) { ConsumerManager.instance.RefreshDiscovered(null); } if ((UnityEngine.Object)ManagementMenu.Instance != (UnityEngine.Object)null) { ManagementMenu.Instance.CheckResearch(null); ManagementMenu.Instance.CheckSkills(null); ManagementMenu.Instance.CheckStarmap(null); } Game.Instance.Trigger(1594320620, "all_the_things"); } else if (e.TryConsume(Action.DebugExplosion)) { Vector3 mousePos = KInputManager.GetMousePos(); Vector3 position = Camera.main.transform.GetPosition(); mousePos.z = 0f - position.z - Grid.CellSizeInMeters; Vector3 explosion_pos = Camera.main.ScreenToWorldPoint(mousePos); GameUtil.CreateExplosion(explosion_pos); } else if (e.TryConsume(Action.DebugLockCursor)) { if (GenericGameSettings.instance.developerDebugEnable) { KInputManager.isMousePosLocked = !KInputManager.isMousePosLocked; KInputManager.lockedMousePos = KInputManager.GetMousePos(); } } else if (e.TryConsume(Action.DebugDiscoverAllElements)) { if ((UnityEngine.Object)WorldInventory.Instance != (UnityEngine.Object)null) { foreach (Element element in ElementLoader.elements) { WorldInventory.Instance.Discover(element.tag, element.GetMaterialCategoryTag()); } } } else if (e.TryConsume(Action.DebugToggleUI)) { ToggleScreenshotMode(); } else if (e.TryConsume(Action.SreenShot1x)) { string filename = Path.ChangeExtension(SaveLoader.GetActiveSaveFilePath(), ".png"); ScreenCapture.CaptureScreenshot(filename, 1); } else if (e.TryConsume(Action.SreenShot2x)) { string filename2 = Path.ChangeExtension(SaveLoader.GetActiveSaveFilePath(), ".png"); ScreenCapture.CaptureScreenshot(filename2, 2); } else if (e.TryConsume(Action.SreenShot8x)) { string filename3 = Path.ChangeExtension(SaveLoader.GetActiveSaveFilePath(), ".png"); ScreenCapture.CaptureScreenshot(filename3, 8); } else if (e.TryConsume(Action.SreenShot32x)) { string filename4 = Path.ChangeExtension(SaveLoader.GetActiveSaveFilePath(), ".png"); ScreenCapture.CaptureScreenshot(filename4, 32); } else if (e.TryConsume(Action.DebugCellInfo)) { DebugCellInfo = !DebugCellInfo; } else if (e.TryConsume(Action.DebugToggle)) { if ((UnityEngine.Object)Game.Instance != (UnityEngine.Object)null) { Game.Instance.UpdateGameActiveRegion(0, 0, Grid.WidthInCells, Grid.HeightInCells); SaveGame.Instance.worldGenSpawner.SpawnEverything(); } if ((UnityEngine.Object)DebugPaintElementScreen.Instance != (UnityEngine.Object)null) { bool activeSelf = DebugPaintElementScreen.Instance.gameObject.activeSelf; DebugPaintElementScreen.Instance.gameObject.SetActive(!activeSelf); if ((bool)DebugElementMenu.Instance && DebugElementMenu.Instance.root.activeSelf) { DebugElementMenu.Instance.root.SetActive(false); } DebugBaseTemplateButton.Instance.gameObject.SetActive(!activeSelf); PropertyTextures.FogOfWarScale = (float)((!activeSelf) ? 1 : 0); if ((UnityEngine.Object)CameraController.Instance != (UnityEngine.Object)null) { CameraController.Instance.EnableFreeCamera(!activeSelf); } } } else if (e.TryConsume(Action.DebugCollectGarbage)) { GC.Collect(); } else if (e.TryConsume(Action.DebugInvincible)) { InvincibleMode = !InvincibleMode; } else if (e.TryConsume(Action.DebugVisualTest)) { Scenario.Instance.SetupVisualTest(); } else if (e.TryConsume(Action.DebugGameplayTest)) { Scenario.Instance.SetupGameplayTest(); } else if (e.TryConsume(Action.DebugElementTest)) { Scenario.Instance.SetupElementTest(); } else if (e.TryConsume(Action.ToggleProfiler)) { Sim.SIM_HandleMessage(-409964931, 0, null); } else if (e.TryConsume(Action.DebugRefreshNavCell)) { Pathfinding.Instance.RefreshNavCell(GetMouseCell()); } else if (e.TryConsume(Action.DebugToggleSelectInEditor)) { SetSelectInEditor(!SelectInEditor); } else if (e.TryConsume(Action.DebugGotoTarget)) { Debug.Log("Debug GoTo"); Game.Instance.Trigger(775300118, null); foreach (Brain item in Components.Brains.Items) { item.GetSMI <DebugGoToMonitor.Instance>()?.GoToCursor(); item.GetSMI <CreatureDebugGoToMonitor.Instance>()?.GoToCursor(); } } else if (e.TryConsume(Action.DebugTeleport)) { if ((UnityEngine.Object)SelectTool.Instance == (UnityEngine.Object)null) { return; } KSelectable selected = SelectTool.Instance.selected; if ((UnityEngine.Object)selected != (UnityEngine.Object)null) { int mouseCell2 = GetMouseCell(); if (!Grid.IsValidBuildingCell(mouseCell2)) { PopFXManager.Instance.SpawnFX(PopFXManager.Instance.sprite_Negative, UI.DEBUG_TOOLS.INVALID_LOCATION, null, GetMousePos(), 1.5f, false, true); return; } selected.transform.SetPosition(Grid.CellToPosCBC(mouseCell2, Grid.SceneLayer.Move)); } } else if (!e.TryConsume(Action.DebugPlace) && !e.TryConsume(Action.DebugSelectMaterial)) { if (e.TryConsume(Action.DebugNotification)) { if (GenericGameSettings.instance.developerDebugEnable) { Tutorial.Instance.DebugNotification(); } } else if (e.TryConsume(Action.DebugNotificationMessage)) { if (GenericGameSettings.instance.developerDebugEnable) { Tutorial.Instance.DebugNotificationMessage(); } } else if (e.TryConsume(Action.DebugSuperSpeed)) { if ((UnityEngine.Object)SpeedControlScreen.Instance != (UnityEngine.Object)null) { SpeedControlScreen.Instance.ToggleRidiculousSpeed(); } } else if (e.TryConsume(Action.DebugGameStep)) { if ((UnityEngine.Object)SpeedControlScreen.Instance != (UnityEngine.Object)null) { SpeedControlScreen.Instance.DebugStepFrame(); } } else if (e.TryConsume(Action.DebugSimStep)) { Game.Instance.ForceSimStep(); } else if (e.TryConsume(Action.DebugToggleMusic)) { AudioDebug.Get().ToggleMusic(); } else if (e.TryConsume(Action.DebugRiverTest)) { Scenario.Instance.SetupRiverTest(); } else if (e.TryConsume(Action.DebugTileTest)) { Scenario.Instance.SetupTileTest(); } else if (e.TryConsume(Action.DebugForceLightEverywhere)) { PropertyTextures.instance.ForceLightEverywhere = !PropertyTextures.instance.ForceLightEverywhere; } else if (e.TryConsume(Action.DebugPathFinding)) { DebugPathFinding = !DebugPathFinding; Debug.Log("DebugPathFinding=" + DebugPathFinding); } else if (!e.TryConsume(Action.DebugFocus)) { if (e.TryConsume(Action.DebugReportBug)) { if (GenericGameSettings.instance.developerDebugEnable) { int num = 0; string validSaveFilename; while (true) { validSaveFilename = SaveScreen.GetValidSaveFilename("bug_report_savefile_" + num.ToString()); if (!File.Exists(validSaveFilename)) { break; } num++; } string save_file = "No save file (front end)"; if ((UnityEngine.Object)SaveLoader.Instance != (UnityEngine.Object)null) { save_file = SaveLoader.Instance.Save(validSaveFilename, false, false); } KCrashReporter.ReportBug("Bug Report", save_file); } else { Debug.Log("Debug crash keys are not enabled."); } } else if (e.TryConsume(Action.DebugTriggerException)) { if (GenericGameSettings.instance.developerDebugEnable) { string str = Guid.NewGuid().ToString(); StackTrace stackTrace = new StackTrace(1, true); str = str + "\n" + stackTrace.ToString(); KCrashReporter.ReportError("Debug crash with random stack", str, null, ScreenPrefabs.Instance.ConfirmDialogScreen, string.Empty); } } else if (e.TryConsume(Action.DebugTriggerError)) { if (GenericGameSettings.instance.developerDebugEnable) { Debug.LogError("Oooops! Testing error!"); } } else if (e.TryConsume(Action.DebugDumpGCRoots)) { GarbageProfiler.DebugDumpRootItems(); } else if (e.TryConsume(Action.DebugDumpGarbageReferences)) { GarbageProfiler.DebugDumpGarbageStats(); } else if (e.TryConsume(Action.DebugDumpEventData)) { if (GenericGameSettings.instance.developerDebugEnable) { KObjectManager.Instance.DumpEventData(); } } else if (e.TryConsume(Action.DebugDumpSceneParitionerLeakData)) { if (!GenericGameSettings.instance.developerDebugEnable) { goto IL_0b5e; } } else if (e.TryConsume(Action.DebugCrashSim)) { if (GenericGameSettings.instance.developerDebugEnable) { Sim.SIM_DebugCrash(); } } else if (e.TryConsume(Action.DebugNextCall)) { DebugNextCall = true; } else if (e.TryConsume(Action.DebugTogglePersonalPriorityComparison)) { Chore.ENABLE_PERSONAL_PRIORITIES = !Chore.ENABLE_PERSONAL_PRIORITIES; } } } goto IL_0b5e; IL_0b5e: if (e.Consumed && (UnityEngine.Object)Game.Instance != (UnityEngine.Object)null) { Game.Instance.debugWasUsed = true; KCrashReporter.debugWasUsed = true; } }
private void AddToSim(int cell, int particleIdx, ref int num_particles) { bool flag = false; do { Element element = Grid.Element[cell]; Element.State state = element.state & Element.State.Solid; if (state == Element.State.Solid || (Grid.Properties[cell] & 2) != 0) { cell += Grid.WidthInCells; if (!Grid.IsValidCell(cell)) { return; } } else { flag = true; } }while (!flag); ParticleProperties particleProperties = this.particleProperties[particleIdx]; SimMessages.AddRemoveSubstance(cell, particleProperties.elementIdx, CellEventLogger.Instance.FallingWaterAddToSim, particleProperties.mass, particleProperties.temperature, particleProperties.diseaseIdx, particleProperties.diseaseCount, true, -1); RemoveParticle(particleIdx, ref num_particles); float time = GetTime(); float num = lastSpawnTime[cell]; if (time - num >= minSpawnDelay) { lastSpawnTime[cell] = time; Vector3 vector = Grid.CellToPosCCC(cell, Grid.SceneLayer.TileMain); if (CameraController.Instance.IsAudibleSound(vector)) { bool flag2 = true; if (splashSounds.TryGetValue(cell, out SoundInfo value)) { value.splashCount++; if (value.splashCount > splashCountLoopThreshold) { if (value.handle == HandleVector <int> .InvalidHandle) { value.handle = LoopingSoundManager.StartSound(liquid_splash_loop, vector, true, true); } LoopingSoundManager.Get().UpdateFirstParameter(value.handle, HASH_LIQUIDDEPTH, SoundUtil.GetLiquidDepth(cell)); LoopingSoundManager.Get().UpdateSecondParameter(value.handle, HASH_LIQUIDVOLUME, GetParticleVolume(particleProperties.mass)); flag2 = false; } } else { value = default(SoundInfo); value.handle = HandleVector <int> .InvalidHandle; } value.startTime = time; splashSounds[cell] = value; if (flag2) { EventInstance instance = SoundEvent.BeginOneShot(liquid_splash_initial, vector); instance.setParameterValue("liquidDepth", SoundUtil.GetLiquidDepth(cell)); instance.setParameterValue("liquidVolume", GetParticleVolume(particleProperties.mass)); SoundEvent.EndOneShot(instance); } } } }
protected override void ConduitTick(float delta) { if (!AlwaysConsume && !operational.IsOperational) { return; } IConduitFlow conduitFlow = GetConduitManager(); if (ConduitType != ConduitType.Solid) { ConduitFlow mngr = conduitFlow as ConduitFlow; ConduitFlow.ConduitContents contents = mngr.GetContents(portCell); if (contents.mass <= 0) { return; } Element element = ElementLoader.FindElementByHash(contents.element); bool matchesTag = StoreTag == GameTags.Any || element.HasTag(StoreTag); float rateAmount = ConsumptionRate * delta; float maxTake = 0f; float storageContains = storage.MassStored(); float storageLeft = storage.capacityKg - storageContains; float portContains = StoreTag == GameTags.Any ? storageContains : storage.GetMassAvailable(StoreTag); float portLeft = MaximumStore - portContains; maxTake = Mathf.Min(storageLeft, portLeft); maxTake = Mathf.Min(rateAmount, maxTake); float removed = 0f; if (maxTake > 0f) { ConduitFlow.ConduitContents removedContents = mngr.RemoveElement(portCell, maxTake); removed = removedContents.mass; LastConsumedElement = removedContents.element; float ratio = removed / contents.mass; if (!matchesTag) { BuildingHP.DamageSourceInfo damage = new BuildingHP.DamageSourceInfo { damage = 1, source = BUILDINGS.DAMAGESOURCES.BAD_INPUT_ELEMENT, popString = UI.GAMEOBJECTEFFECTS.DAMAGE_POPS.WRONG_ELEMENT }; Trigger((int)GameHashes.DoBuildingDamage, damage); if (WrongElement == WrongElementResult.Dump) { int buildingCell = Grid.PosToCell(_parent.transform.GetPosition()); SimMessages.AddRemoveSubstance(buildingCell, contents.element, CellEventLogger.Instance.ConduitConsumerWrongElement, removed, contents.temperature, contents.diseaseIdx, contents.diseaseIdx); return; } } if (ConduitType == ConduitType.Gas) { if (!element.IsGas) { Debug.LogWarning($"[MultIO] Gas input port attempted to consume non gass: {element.id.ToString()}"); } else { storage.AddGasChunk(element.id, removed, contents.temperature, contents.diseaseIdx, contents.diseaseCount, KeepZeroMassObject, false); } } else if (ConduitType == ConduitType.Liquid) { if (!element.IsLiquid) { Debug.LogWarning($"[MultIO] Liquid input port attempted to consume non liquid: {element.id.ToString()}"); } else { storage.AddLiquid(element.id, removed, contents.temperature, contents.diseaseIdx, contents.diseaseCount, KeepZeroMassObject, false); } } } } else { SolidConduitFlow mngr = conduitFlow as SolidConduitFlow; SolidConduitFlow.ConduitContents contents = mngr.GetContents(portCell); if (contents.pickupableHandle.IsValid() && (AlwaysConsume || operational.IsOperational)) { float stored = StoreTag == GameTags.Any ? storage.MassStored() : storage.GetMassAvailable(StoreTag); float maxStorage = Mathf.Min(storage.capacityKg, MaximumStore); float availableStorage = Mathf.Max(0f, maxStorage - stored); if (availableStorage > 0f) { Pickupable tmp = mngr.GetPickupable(contents.pickupableHandle); bool matchesTag = StoreTag == GameTags.Any || tmp.HasTag(StoreTag); if (matchesTag) { if (tmp.PrimaryElement.Mass <= stored || tmp.PrimaryElement.Mass > maxStorage) { Pickupable take = mngr.RemovePickupable(portCell); if (take != null) { storage.Store(take.gameObject, true); } } } else { Pickupable take = mngr.RemovePickupable(portCell); take.transform.SetPosition(Grid.CellToPos(portCell)); //TODO: Add a PopFX. Likely will not do damage. } } } } }
public void Poop() { float num = 0f; Tag tag = Tag.Invalid; byte disease_idx = byte.MaxValue; int num2 = 0; bool flag = false; for (int i = 0; i < caloriesConsumed.Count; i++) { CaloriesConsumedEntry value = caloriesConsumed[i]; if (!(value.calories <= 0f)) { Diet.Info dietInfo = diet.GetDietInfo(value.tag); if (dietInfo != null && (!(tag != Tag.Invalid) || !(tag != dietInfo.producedElement))) { num += dietInfo.ConvertConsumptionMassToProducedMass(dietInfo.ConvertCaloriesToConsumptionMass(value.calories)); tag = dietInfo.producedElement; disease_idx = dietInfo.diseaseIdx; num2 = (int)(dietInfo.diseasePerKgProduced * num); value.calories = 0f; caloriesConsumed[i] = value; flag = (flag || dietInfo.produceSolidTile); } } } if (!(num <= 0f) && !(tag == Tag.Invalid)) { Element element = ElementLoader.GetElement(tag); Debug.Assert(element != null, "TODO: implement non-element tag spawning"); int num3 = Grid.PosToCell(owner.transform.GetPosition()); float temperature = owner.GetComponent <PrimaryElement>().Temperature; if (element.IsLiquid) { FallingWater.instance.AddParticle(num3, element.idx, num, temperature, disease_idx, num2, true, false, false, false); } else if (element.IsGas) { SimMessages.AddRemoveSubstance(num3, element.idx, CellEventLogger.Instance.ElementConsumerSimUpdate, num, temperature, disease_idx, num2, true, -1); } else if (flag) { Facing component = owner.GetComponent <Facing>(); int num4 = component.GetFrontCell(); if (!Grid.IsValidCell(num4)) { Debug.LogWarningFormat("{0} attemping to Poop {1} on invalid cell {2} from cell {3}", owner, element.name, num4, num3); num4 = num3; } SimMessages.AddRemoveSubstance(num4, element.idx, CellEventLogger.Instance.ElementConsumerSimUpdate, num, temperature, disease_idx, num2, true, -1); } else { element.substance.SpawnResource(Grid.CellToPosCCC(num3, Grid.SceneLayer.Ore), num, temperature, disease_idx, num2, false, false, false); } KPrefabID component2 = owner.GetComponent <KPrefabID>(); if (!Game.Instance.savedInfo.creaturePoopAmount.ContainsKey(component2.PrefabTag)) { Game.Instance.savedInfo.creaturePoopAmount.Add(component2.PrefabTag, 0f); } Dictionary <Tag, float> creaturePoopAmount; Tag prefabTag; (creaturePoopAmount = Game.Instance.savedInfo.creaturePoopAmount)[prefabTag = component2.PrefabTag] = creaturePoopAmount[prefabTag] + num; PopFXManager.Instance.SpawnFX(PopFXManager.Instance.sprite_Resource, element.name, owner.transform, 1.5f, false); } }
public JsonResult BuildSimulationScript(List<PacketViewModel> packets) { var r = Request; List<Message> msgList = new List<Message>(); HashSet<Type> types = new HashSet<Type>(); packets.ForEach(id => { var info = PacketRepository.GetByPacketId(id.PacketId); if (info != null) { var msg = info.ToMessage(); msgList.Add(msg); types.Add(msg.GetType()); } }); SimMessages simMsg = new SimMessages(); simMsg.Messages = msgList; string simScriptsFolder = Url.Content(string.Format("~/Content/SimScripts")); if (!Directory.Exists(simScriptsFolder)) { Directory.CreateDirectory(simScriptsFolder); } string fileName =simScriptsFolder + string.Format("/sim-script-{0}.xml", Guid.NewGuid()); string scriptPath = Server.MapPath(fileName); using (TextWriter textWriter = new StreamWriter(scriptPath)) { XmlSerializer serializer = new XmlSerializer(typeof(SimMessages), types.ToArray()); serializer.Serialize(textWriter, simMsg); } return Json( new { script = fileName, success = true }, JsonRequestBehavior.AllowGet); //byte[] fileContents = System.Text.ASCIIEncoding.ASCII.GetBytes(script); //return File(fileContents, "application/xml", string.Format("simulation-script-{0}.xml", DateTime.Now.ToString("dd-mm-yyyy"))); }
private void Consume(float dt, ConduitFlow conduit_mgr) { this.IsSatisfied = false; if (this.building.Def.CanMove) { this.utilityCell = this.GetInputCell(); } if (!this.IsConnected) { return; } ConduitFlow.ConduitContents contents = conduit_mgr.GetContents(this.utilityCell); if ((double)contents.mass <= 0.0) { return; } this.IsSatisfied = true; if (!this.alwaysConsume && !this.operational.IsOperational) { return; } float delta = Mathf.Min(this.ConsumptionRate * dt, this.space_remaining_kg); float mass = 0.0f; if ((double)delta > 0.0) { ConduitFlow.ConduitContents conduitContents = conduit_mgr.RemoveElement(this.utilityCell, delta); mass = conduitContents.mass; this.lastConsumedElement = conduitContents.element; } bool flag = ElementLoader.FindElementByHash(contents.element).HasTag(this.capacityTag); if ((double)mass > 0.0 && this.capacityTag != GameTags.Any && !flag) { this.Trigger(-794517298, (object)new BuildingHP.DamageSourceInfo() { damage = 1, source = (string)BUILDINGS.DAMAGESOURCES.BAD_INPUT_ELEMENT, popString = (string)UI.GAMEOBJECTEFFECTS.DAMAGE_POPS.WRONG_ELEMENT }); } if (flag || this.wrongElementResult == ConduitConsumer2.WrongElementResult.Store || (contents.element == SimHashes.Vacuum || this.capacityTag == GameTags.Any)) { if ((double)mass <= 0.0) { return; } int disease_count = (int)((double)contents.diseaseCount * ((double)mass / (double)contents.mass)); Element elementByHash = ElementLoader.FindElementByHash(contents.element); switch (this.conduitType) { case ConduitType.Gas: if (elementByHash.IsGas) { this.storage.AddGasChunk(contents.element, mass, contents.temperature, contents.diseaseIdx, disease_count, this.keepZeroMassObject, false); break; } Debug.LogWarning((object)("Gas conduit consumer consuming non gas: " + elementByHash.id.ToString())); break; case ConduitType.Liquid: if (elementByHash.IsLiquid) { this.storage.AddLiquid(contents.element, mass, contents.temperature, contents.diseaseIdx, disease_count, this.keepZeroMassObject, false); break; } Debug.LogWarning((object)("Liquid conduit consumer consuming non liquid: " + elementByHash.id.ToString())); break; } } else { if ((double)mass <= 0.0 || this.wrongElementResult != ConduitConsumer2.WrongElementResult.Dump) { return; } int disease_count = (int)((double)contents.diseaseCount * ((double)mass / (double)contents.mass)); SimMessages.AddRemoveSubstance(Grid.PosToCell(this.transform.GetPosition()), contents.element, CellEventLogger.Instance.ConduitConsumerWrongElement, mass, contents.temperature, contents.diseaseIdx, disease_count, true, -1); } }
public void Sim200ms(float dt) { if (mobileLamp) { lampXY = Grid.PosToXY(gameObject.transform.position); } if (alwaysOn || (operational != null && operational.IsOperational)) { if (operational != null) { operational.SetActive(true); } HashSet <GameObject> buildingsAlreadySeen = new HashSet <GameObject>(); // Delete germs in area for (int dy = aoeBottom; dy < aoeBottom + aoeHeight; dy++) { int y = lampXY.Y + dy; for (int dx = aoeLeft; dx < aoeLeft + aoeWidth; dx++) { int x = lampXY.X + dx; if (FlashReachesCell(x, y)) { int cell = Grid.XYToCell(x, y); // Delete germs in the cell byte cellGermIndex = Grid.DiseaseIdx[cell]; if (diseasesKilled.Contains(cellGermIndex)) { int cellGermCount = Grid.DiseaseCount[cell]; int cellGermsToKill = GermsToKill(cellGermCount); SimMessages.ModifyDiseaseOnCell(cell, cellGermIndex, -cellGermsToKill); } // Delete germs on pickupables in the cell var pickupablesInCell = Grid.Objects[cell, (int)ObjectLayer.Pickupables]; if (pickupablesInCell != null) { var currentPickupable = pickupablesInCell.GetComponent <Pickupable>().objectLayerListItem; while (currentPickupable != null) { var pickupable = currentPickupable.gameObject.GetComponent <Pickupable>(); currentPickupable = currentPickupable.nextItem; if (pickupable != null) { byte pickupableDiseaseIndex = pickupable.PrimaryElement.DiseaseIdx; if (diseasesKilled.Contains(pickupableDiseaseIndex)) { int pickupableGermCount = pickupable.PrimaryElement.DiseaseCount; int pickupableGermsToKill = GermsToKill(pickupableGermCount); pickupable.PrimaryElement.ModifyDiseaseCount(-pickupableGermsToKill, GermicideLampConfig.ID); } if (applySunburn) { var minion = pickupable.GetComponent <MinionIdentity>(); if (minion != null) { var sunburn = new SicknessExposureInfo(Db.Get().Sicknesses.Sunburn.Id, ModStrings.STRINGS.BUILDINGS.GERMICIDELAMP.NAME); var sicknesses = minion.GetSicknesses(); bool hasSunburn = false; if (sicknesses.IsInfected()) { foreach (SicknessInstance item in sicknesses) { if (item.ExposureInfo.sicknessID == Db.Get().Sicknesses.Sunburn.Id) { hasSunburn = true; break; } } } if (!hasSunburn) { sicknesses.Infect(sunburn); } } } } } } // Delete germs on solid conduit items in the cell var conduit = Game.Instance.solidConduitFlow.GetConduit(cell); if (!conduit.Equals(SolidConduitFlow.Conduit.Invalid())) { var conduitContents = conduit.GetContents(Game.Instance.solidConduitFlow); var conduitPickupable = Game.Instance.solidConduitFlow.GetPickupable(conduitContents.pickupableHandle); if (conduitPickupable != null) { byte conduitDiseaseIndex = conduitPickupable.PrimaryElement.DiseaseIdx; if (diseasesKilled.Contains(conduitDiseaseIndex)) { int cpuCount = conduitPickupable.PrimaryElement.DiseaseCount; int cpuGermsToKill = GermsToKill(cpuCount); conduitPickupable.PrimaryElement.ModifyDiseaseCount(-cpuGermsToKill, GermicideLampConfig.ID); } } } // Delete germs on buildings in the cell var buildingInCell = Grid.Objects[cell, (int)ObjectLayer.Building]; if (buildingInCell != null && !buildingsAlreadySeen.Contains(buildingInCell)) { var buildingElement = buildingInCell.GetComponent <PrimaryElement>(); if (buildingElement != null) { byte buildingDiseaseIndex = buildingElement.DiseaseIdx; if (diseasesKilled.Contains(buildingDiseaseIndex)) { int buildingGermCount = buildingElement.DiseaseCount; int buildingGermsToKill = GermsToKill(buildingGermCount); buildingElement.ModifyDiseaseCount(-buildingGermsToKill, GermicideLampConfig.ID); } } buildingsAlreadySeen.Add(buildingInCell); } } } } } else { if (operational != null) { operational.SetActive(false); } } }
private void ConvertMass() { float filterAmt = 0; List <GameObject> items = this.storage.items; PrimaryElement elem = null; foreach (GameObject item in items) { elem = item.GetComponent <PrimaryElement>(); if (elem.ElementID == SimHashes.BleachStone) { filterAmt += elem.Mass; } } if (filterAmt <= 0) { return; } float maxGerms = Mathf.Min(GERMS_PER_KG * MAX_KG_PER_SEC, (int)(filterAmt * GERMS_PER_KG)); float removedAmount = 0; ConduitFlow flowManager = Conduit.GetFlowManager(ConduitType.Liquid); if (!flowManager.HasConduit(inCell) || !flowManager.HasConduit(outCell)) { return; } foreach (GameObject item in items) { elem = item.GetComponent <PrimaryElement>(); if (elem.Element.IsLiquid) { float mass = Mathf.Min(10f, elem.Mass); float disease = elem.DiseaseCount / elem.Mass * mass; if (elem.DiseaseIdx == Byte.MaxValue) { disease = 0; } if (disease > maxGerms) { mass = mass * maxGerms / disease; disease = maxGerms; } float trueMass = flowManager.AddElement(outCell, elem.ElementID, mass, elem.Temperature, Byte.MaxValue, 0); if (trueMass < mass) { disease = disease * trueMass / mass; mass = trueMass; } elem.Mass -= mass; elem.ModifyDiseaseCount(-(int)disease, ""); removedAmount = disease; Game.Instance.accumulators.Accumulate(fluidProcessedLastTick, mass); if (mass > 0) { break; } } } if (removedAmount > 0) { float removal = (float)removedAmount / GERMS_PER_KG; storage.ConsumeIgnoringDisease(ElementLoader.FindElementByHash(filterIn).tag, removal); Game.Instance.accumulators.Accumulate(filterConsumedLastTick, removal); if (EMIT_CHLORINE) { float addition = (float)removedAmount / GERMS_PER_KG; Element elementByHash = ElementLoader.FindElementByHash(filterOut); Vector3 outVector3 = new Vector3(this.transform.GetPosition().x, this.transform.GetPosition().y, 0.0f); int outCell = Grid.PosToCell(outVector3); SimMessages.AddRemoveSubstance(outCell, filterOut, CellEventLogger.Instance.OxygenModifierSimUpdate, addition, 273.15f + 45f, Byte.MaxValue, 0); } } //TODO: find out what the nice name is this.storage.Trigger(-1697596308, (object)this.gameObject); }