Exemplo n.º 1
0
        // *** The important function controlling the mining ***
        /// <summary>
        /// The controlling function of the mining. Calls individual/granular functions and decides whether to continue
        /// collecting resources or not.
        /// </summary>
        /// <param name="offlineCollecting">Bool parameter, signifies if this collection is done in catch-up mode (i.e. after the focus has been on another vessel).</param>
        /// <param name="deltaTime">Double, signifies the amount of time since last Fixed Update (Unity).</param>
        private void MineResources(bool offlineCollecting, double deltaTime)
        {
            if (!offlineCollecting)
            {
                double percentPower = HasEnoughPower(deltaTime);

                if (percentPower < minimumPowerNeeded)
                {
                    if (powerCountdown > 0)
                    {
                        powerCountdown -= 1;
                        return;
                    }

                    ScreenMessages.PostScreenMessage(Localizer.Format("#LOC_KSPIE_UniversalCrustExtractor_PostMsg1"), 3.0f, ScreenMessageStyle.LOWER_CENTER);//"Not enough power to run the universal drill."
                    DisableCollector();
                    return;
                }

                reasonNotCollecting = CheckIfCollectingPossible();

                if (!string.IsNullOrEmpty(reasonNotCollecting)) // collecting not possible due to some reasons.
                {
                    ScreenMessages.PostScreenMessage(reasonNotCollecting, 3.0f, ScreenMessageStyle.LOWER_CENTER);

                    DisableCollector();
                    return; // let's get out of here, no mining for now
                }

                if (!GetResourceData())                                                                                                                       // if the resource data was not okay, no mining
                {
                    ScreenMessages.PostScreenMessage(Localizer.Format("#LOC_KSPIE_UniversalCrustExtractor_PostMsg2"), 3.0f, ScreenMessageStyle.LOWER_CENTER); //"The universal drill is not sure where you are trying to mine. Please contact the mod author, tell him the details of this situation and provide the output log."
                    DisableCollector();
                    return;
                }

                if (!CalculateCrustThickness(vessel.altitude, FlightGlobals.currentMainBody, out var crustThickness)) // crust thickness calculation off, no mining
                {
                    DisableCollector();
                    return;
                }

                double minedAmount      = crustThickness * drillSize * effectiveness * percentPower;
                double minedAmountStock = 0.0005 * drillSize * effectiveness * percentPower;

                StoreDataForOfflineMining(minedAmount);

                foreach (CrustalResource resource in localResources)
                {
                    CrustalResourceAbundanceDict.TryGetValue(resource.ResourceName, out var abundance);

                    if (abundance == null)
                    {
                        continue;
                    }

                    if (resource.ResourceName == "Ore")
                    {
                        resource.Production = minedAmountStock * abundance.Local;
                    }
                    else
                    {
                        resource.Production = minedAmount * abundance.Local;
                    }

                    CalculateSpareRoom(resource);

                    if (resource.SpareRoom > 0) // if there's space, add the resource
                    {
                        AddResource(resource.Production * deltaTime, resource.ResourceName);
                    }
                }
            }
            else // this is offline collecting, so use the simplified version
            {
                // ensure the drill doesn't turn itself off too quickly
                powerCountdown = powerCountdownMax;

                // these are helper variables for the message
                double totalAmount       = 0;
                int    numberOfResources = 0;

                // get the resource data
                if (!GetResourceData()) // if getting the resource data went wrong, no offline mining
                {
                    Debug.Log("[KSPI]: Universal Drill - Error while getting resource data for offline mining calculations.");
                    return;
                }

                // go through each resource, calculate the percentage, abundance, amount collected and spare room in tanks. If possible, add the resource
                foreach (CrustalResource resource in localResources)
                {
                    CrustalResourceAbundanceDict.TryGetValue(resource.ResourceName, out var abundance);
                    if (abundance == null)
                    {
                        continue;
                    }

                    //amount = CalculateResourceAmountCollected(dLastPseudoMinedAmount, abundance.GlobalWithVariance, abundance.Local, deltaTime);
                    resource.Production = dLastPseudoMinedAmount * abundance.Local;
                    CalculateSpareRoom(resource);
                    if (resource.SpareRoom > 0 && resource.Production > 0)
                    {
                        var additionFixed = resource.Production * deltaTime;
                        AddResource(additionFixed, resource.ResourceName);
                        totalAmount += (additionFixed > resource.SpareRoom) ? resource.SpareRoom : additionFixed; // add the mined amount to the total for the message, but only the amount that actually got into the tanks
                        numberOfResources++;
                    }
                }
                // inform the player about the offline processing
                ScreenMessages.PostScreenMessage(Localizer.Format("#LOC_KSPIE_UniversalCrustExtractor_PostMsg3", deltaTime.ToString("0"), totalAmount.ToString("0.000"), numberOfResources), 10.0f, ScreenMessageStyle.LOWER_CENTER);//"Universal drill mined offline for <<1>> seconds, drilling out <<2>> units of <<3>> resources."
            }
        }
Exemplo n.º 2
0
        void DrawWindow(int windowID)
        {
            GUIContent closeContent = new GUIContent(Textures.BtnRedCross, "Close Window");
            Rect       closeRect    = new Rect(windowRect.width - 21, 4, 16, 16);

            if (GUI.Button(closeRect, closeContent, Textures.ClosebtnStyle))
            {
                showGUI = !showGUI;
                return;
            }
            GUILayout.BeginVertical();
            scrollViewBodiesVector = GUILayout.BeginScrollView(scrollViewBodiesVector, GUILayout.MaxHeight(200f));
            GUILayout.BeginVertical();
            GUILayout.Label(Locales.currentLocale.Values["start_availableBodies"], Textures.sectionTitleStyle);
            foreach (var body in Database.instance.CelestialBodies)
            {
                if (body.Value.isResearched)
                {
                    GUILayout.Label(body.Key.GetName() + " - " + body.Value.researchState.ToString("N0") + "%", Textures.PartListPartStyle);
                }
            }
            GUILayout.EndVertical();
            GUILayout.EndScrollView();

            scrollViewVector = GUILayout.BeginScrollView(scrollViewVector);
            GUILayout.BeginVertical();
            GUILayout.Label(string.Format(Locales.currentLocale.Values["telescope_trackBodies_EC"], electricChargeRequest));
            if (GUILayout.Button(Locales.currentLocale.Values["telescope_trackBodies"]))
            {
                foundBody                = false;
                withParent               = false;
                foundBodyTooWeak         = false;
                searchButtonDisplayTimer = Planetarium.GetUniversalTime();
                searchButtonDisplay      = true;
                nothing = Database.instance.NothingHere[random.Next(Database.instance.NothingHere.Count)];
                BodiesInView.Clear();
                //Check part dependency.. Unusual, But ok.
                if (requiresPart)
                {
                    bool local = false;
                    foreach (Part part in this.vessel.Parts)
                    {
                        if (part.name.Contains(requiredPart))
                        {
                            local = true;
                        }
                    }
                    if (!local)
                    {
                        canResearch = false;
                        ScreenMessages.PostScreenMessage(string.Format(Locales.currentLocale.Values["telescope_mustHavePart"], requiredPart), 3.0f, ScreenMessageStyle.UPPER_CENTER);
                    }
                }

                if (canResearch)                                                                                           //Part check is OK
                {
                    var totalElecreceived = Utilities.RequestResource(this.part, "ElectricCharge", electricChargeRequest); //get power
                    if (totalElecreceived >= electricChargeRequest * 0.99)                                                 //If we got power
                    {
                        var randomMax = Database.instance.chances + difficulty;                                            //Calculate the randomness (sic) and if we found something. This needs to be replaced with something better.
                        var randomNum = random.Next(randomMax);
                        if (randomNum == 1 || randomNum == 2)
                        {
                            //Scan the list of CB's and find anything in range?
                            foreach (CelestialBody body in Database.instance.BodyList)
                            {
                                hostPos   = this.part.transform.position;
                                targetPos = body.transform.position;
                                angle     = Vector3.Angle(targetPos - hostPos, this.part.transform.up);
                                distance  = Vector3d.Distance(body.transform.position, this.vessel.transform.position);
                                //Is it within the acceptable Angle?
                                if (angle <= viewAngle)
                                {
                                    //Is it within the maximum tracking distance of this part?
                                    if (distance <= maxTrackDistance)
                                    {
                                        BodiesInView.Add(body);  //We got one!
                                    }
                                    //Too far away.
                                    else
                                    {
                                        foundBodyTooWeak = true;
                                    }
                                }
                            }
                            if (BodiesInView.Count > 0)  //did we find anything?
                            {
                                //Remove any already researched.
                                BodiesInViewResearched.Clear();
                                for (int i = BodiesInView.Count - 1; i >= 0; --i)
                                {
                                    if (Database.instance.CelestialBodies[BodiesInView[i]].isResearched)
                                    {
                                        BodiesInViewResearched.Add(BodiesInView[i]);
                                    }
                                }
                                BodiesInViewResearched.ForEach(id => BodiesInView.Remove(id));
                                if (BodiesInView.Count > 0)                                    //Do we still have any? If so:
                                {
                                    bodyFound = BodiesInView[random.Next(BodiesInView.Count)]; //Randomly pick one.
                                    foundBody = true;
                                    ScreenMessages.PostScreenMessage("Celestial Body Discovered !", 5f);
                                    difficulty = startingdifficulty; //Reset the difficulty factor to the starting factor now that we found something.
                                    ResearchBodiesController.FoundBody(scienceReward, bodyFound, out withParent, out parentBody);
                                }
                            }
                        }
                        else
                        {
                            //We didn't find anything. Reduce the difficulty by one until we do.
                            foundBody = false;
                            if (randomMax > 2)
                            {
                                difficulty--;
                            }
                        }
                    }
                    else  // There wasn't enough EC!
                    {
                        ScreenMessages.PostScreenMessage(string.Format(Locales.currentLocale.Values["ec_notEnough"]), 3.0f, ScreenMessageStyle.UPPER_CENTER);
                    }
                }
            } //endif button
            if (searchButtonDisplay)
            {
                if (Planetarium.GetUniversalTime() - searchButtonDisplayTimer > 60)
                {
                    searchButtonDisplayTimer = 0;
                    searchButtonDisplay      = false;
                }
                //Populate text box on discovery.
                if (foundBody)      //Did we end up finding anything?
                {
                    if (withParent) //And was a parent body also discovered?
                    {
                        GUILayout.Label(Database.instance.CelestialBodies[bodyFound].discoveryMessage);
                        GUILayout.Label(Database.instance.CelestialBodies[parentBody].discoveryMessage);
                    }
                    else
                    {
                        GUILayout.Label(Database.instance.CelestialBodies[bodyFound].discoveryMessage);
                    }
                }
                else  //Nope, didn't find anything.
                {
                    if (foundBodyTooWeak) //Was there something just out of telescope range?
                    {
                        GUILayout.Label(Locales.currentLocale.Values["telescope_weaksignal"], HighLogic.Skin.label);
                    }
                    else  //Nope there was absolutely nothing to see here.
                    {
                        GUILayout.Label(nothing, HighLogic.Skin.label);
                    }
                }
            }

            GUILayout.EndVertical();
            GUILayout.EndScrollView();
            GUILayout.EndVertical();
            GUI.DragWindow();
        }
Exemplo n.º 3
0
        public void ExperimentRequirementsMet(string experimentID, float chanceOfSuccess, float resultRoll)
        {
            float        efficiencyModifier = 0.1f;
            int          planetID           = this.part.vessel.mainBody.flightGlobalsIndex;
            HarvestTypes harvestType        = HarvestTypes.Planetary;

            CBAttributeMapSO.MapAttribute biome = Utils.GetCurrentBiome(this.part.vessel);
            string biomeName       = biome.name;
            string modifierName    = "";
            string processChanged  = "";
            string resultsPreamble = string.Empty;

            switch (experimentID)
            {
            case "WBISoilAnalysis":
                modifierName   = EfficiencyData.kHabitationMod;
                processChanged = kLifeSupport;
                break;

            case "WBIMetallurgyAnalysis":
                modifierName   = EfficiencyData.kIndustryMod;
                processChanged = kManufacturing;
                break;

            case "WBIExtractionAnalysis":
                modifierName        = EfficiencyData.kExtractionMod;
                processChanged      = kExtraction;
                efficiencyModifier /= 2.0f;
                break;

            default:
            case "WBIChemicalAnalysis":
                modifierName   = EfficiencyData.kScienceMod;
                processChanged = kChemicalProducts;
                break;
            }

            //Factor success/fail
            if (resultRoll >= chanceOfSuccess)
            {
                resultsPreamble = kBetterEfficiency;
            }

            else //Worse results
            {
                resultsPreamble    = kWorseEfficiency;
                efficiencyModifier = efficiencyModifier * -1.0f;
            }

            //Get existing modifier
            float currentModifer = WBIPathfinderScenario.Instance.GetEfficiencyModifier(planetID, biome.name, harvestType, modifierName);

            //Add improvement
            currentModifer += efficiencyModifier;
            WBIPathfinderScenario.Instance.SetEfficiencyData(planetID, biome.name, harvestType, modifierName, currentModifer);

            //Inform user
            string message = string.Format(resultsPreamble, efficiencyModifier * 100f) + processChanged;

            ScreenMessages.PostScreenMessage(message, 8.0f, ScreenMessageStyle.UPPER_CENTER);
        }
        public void FixedUpdate()
        {
            if (!HighLogic.LoadedSceneIsFlight)
            {
                return;
            }

            try
            {
                if (part == null ||
                    !part.Modules.Contains("ModuleHullBreach") ||
                    !part.Modules.Contains("HitpointTracker")
                    )
                {
                    return;
                }
            }
            catch (Exception)
            { }

            part.rigidAttachment = true;

            if (vessel.situation != Vessel.Situations.SPLASHED)
            {
                return;
            }

            if (part.WaterContact & ShipIsDamaged() & isHullBreached & hull)
            {
                if (FlightGlobals.ActiveVessel)
                {
                    if (DamageState == "Critical")
                    {
                        ScreenMessages.PostScreenMessage("Warning: Critical Hull Breach", 5.0f, ScreenMessageStyle.UPPER_CENTER);
                    }
                    else
                    {
                        ScreenMessages.PostScreenMessage("Warning: Hull Breach", 5.0f, ScreenMessageStyle.UPPER_CENTER);
                    }
                }

                switch (DamageState)
                {
                case "Normal":
                    vessel.IgnoreGForces(240);
                    part.RequestResource("SeaWater", (0 - (flowRate * (0.1 + part.submergedPortion) * flowMultiplier)));
                    break;

                case "Critical":
                    vessel.IgnoreGForces(240);
                    part.RequestResource("SeaWater",
                                         (0 - (critFlowRate * (0.1 + part.submergedPortion) * flowMultiplier)));
                    break;
                }
            }

            //If part underwater add heat (damage) at a greater rate based on depth to simulate pressure
            //sumergedPortion = Math.Round(this.part.submergedPortion, 4);

            if (part.submergedPortion == 1.00 & hydroExplosive)
            {
                part.temperature += (0.1 * part.depth);
            }
            else if (crushable && part.submergedPortion == 1.00 && !part.localRoot.name.StartsWith("Sub"))
            {
                if (config.ecDrain)
                {
                    part.RequestResource("ElectricCharge", 1000); //kill EC if sumberged
                }
                if (crushable)
                {
                    part.buoyancy = -1.0f;            // trying to kill floaty bits that never sink
                }
                if (warnTimer > 0f)
                {
                    warnTimer -= Time.deltaTime;
                }
                if (part.depth > warnDepth && oldVesselDepth > warnDepth && warnTimer <= 0)
                {
                    if (FlightGlobals.ActiveVessel)
                    {
                        if (DepthCharge == false)
                        {
                            ScreenMessages.PostScreenMessage(
                                "Warning! Vessel will be crushed at " + (crushDepth) + "m depth!", 3,
                                ScreenMessageStyle.LOWER_CENTER);
                        }
                        else
                        {
                            ScreenMessages.PostScreenMessage(
                                (crushDepth) + "m Charge Deployed!", 3,
                                ScreenMessageStyle.LOWER_CENTER);
                        }
                    }
                    warnTimer = 5;
                }
                oldVesselDepth = part.depth;
                crushingDepth();
            }
        }
Exemplo n.º 5
0
 private void setCrewTrainingLevel(ProtoCrewMember crew, int level)
 {
     crew.flightLog.AddEntry(new FlightLog.Entry(crew.flightLog.Flight, trainingArr[level], "Kerbin"));
     ScreenMessages.PostScreenMessage(levelNumber[level] + " Training Complete : " + crew.name);
 }
Exemplo n.º 6
0
        public void UpdateWarpSpeed()
        {
            if (!inWarp || minimumRequiredExoticMatter <= 0)
            {
                return;
            }

            // Check this out
            if (this.vessel.altitude < this.vessel.mainBody.atmosphereDepth * 3)
            {
                if (vesselWasInOuterspace)
                {
                    ScreenMessages.PostScreenMessage("Atmosphere is too close! Dropping out of warp!", 7.0f);
                    alarm = true;
                    DeactivateWarpDrive();
                    return;
                }
            }
            else
            {
                vesselWasInOuterspace = true;
            }


            // Check for heading changes
            Vector3d newPartHeading = new Vector3d(part.transform.up.x, part.transform.up.z, part.transform.up.y);

            magnitudeDiff       = (partHeading - newPartHeading).magnitude;
            magnitudeChange     = (previousPartHeading - newPartHeading).magnitude;
            previousPartHeading = newPartHeading;

            bool headingChanged    = magnitudeDiff > 0.05 && magnitudeChange < 0.0001;
            bool factorChanged     = previousFactor != currentFactor;
            bool gravityDisbalance = currentFactor > maximumFactor;

            if (gravityDisbalance)
            {
                currentFactor = maximumFactor;
                if (currentFactor < lowEnergyFactor)
                {
                    ScreenMessages.PostScreenMessage("Gravity too strong, dropping out of warp!", 7.0f);
                    alarm = true;
                    DeactivateWarpDrive();
                    return;
                }
                ScreenMessages.PostScreenMessage("Gravity pull increased, speed dropped down!", 7.0f);
            }

            if (gravityDisbalance || headingChanged || factorChanged)
            {
                previousFactor = currentFactor;

                vessel.GoOnRails();
                vessel.orbit.UpdateFromStateVectors(vessel.orbit.pos, vessel.orbit.vel - warpVector, vessel.orbit.referenceBody, Planetarium.GetUniversalTime());

                warpVector           = newPartHeading * Constants.C * warpFactors [currentFactor];
                partHeading          = newPartHeading;
                serialisedWarpVector = ConfigNode.WriteVector(warpVector);

                vessel.orbit.UpdateFromStateVectors(vessel.orbit.pos, vessel.orbit.vel + warpVector, vessel.orbit.referenceBody, Planetarium.GetUniversalTime());
                vessel.GoOffRails();
            }
        }
Exemplo n.º 7
0
        private IEnumerator RefreshPartInfo()
        {
            if (CurrentSettings == null || PartLoader.LoadedPartsList == null)
            {
                yield break;
            }
            ScreenMessages.PostScreenMessage("Database Part Info reloading started", 1, ScreenMessageStyle.UPPER_CENTER);
            this.IsReady = false;
            yield return(null);

            float lastTime = Time.realtimeSinceStartup;

            var apList = PartLoader.LoadedPartsList.Where(ap => ap.partPrefab.Modules != null);
            int totcnt = 1;

            if (apList == null)
            {
                Log.Info("apList is null");
            }
            else
            {
                totcnt = apList.Count();
            }
            int cnt = 0;

            try
            {
                foreach (var ap in PartLoader.LoadedPartsList.Where(ap => ap.partPrefab.Modules != null))
                {
                    cnt++;
                    if (Time.realtimeSinceStartup - lastTime > 2)
                    {
                        lastTime = Time.realtimeSinceStartup;
                        int intPercent = Mathf.CeilToInt(((float)cnt / (float)totcnt * 100f));
                        ScreenMessages.PostScreenMessage("Database reloading " + intPercent + "%", 1, ScreenMessageStyle.UPPER_CENTER);
                    }

                    AvailablePart.ModuleInfo target = null;
                    foreach (var mi in ap.moduleInfos)
                    {
                        if (mi.moduleName == "Reliability Info")
                        {
                            target = mi;
                        }
                    }

                    if (target != null & !this.CurrentSettings.EnabledForSave)
                    {
                        ap.moduleInfos.Remove(target);
                    }

                    if (this.CurrentSettings.EnabledForSave)
                    {
                        if (target != null)
                        {
                            ap.moduleInfos.Remove(target);
                        }

                        IEnumerable <ModuleReliabilityInfo> reliabilityModules = ap.partPrefab.Modules.OfType <ModuleReliabilityInfo>();
                        if (reliabilityModules.Count() != 0)
                        {
                            AvailablePart.ModuleInfo newModuleInfo = new AvailablePart.ModuleInfo();
                            newModuleInfo.moduleName = "Reliability Info";
                            newModuleInfo.info       = reliabilityModules.First().GetInfo();
                            ap.moduleInfos.Add(newModuleInfo);
                        }
                    }
                }
                Log.Info("Refresh Finished");
                this.IsReady = true;
            }
            catch (Exception e)
            {
                Log.Info("ERROR [" + e.GetType().ToString() + "]: " + e.Message + "\n" + e.StackTrace);
            }
            ScreenMessages.PostScreenMessage("Database Part Info reloading finished", 2, ScreenMessageStyle.UPPER_CENTER);
        }
 private void ScreenMsg3(string msg)
 {
     ScreenMessages.PostScreenMessage(new ScreenMessage(msg, 1, ScreenMessageStyle.UPPER_CENTER));
 }
Exemplo n.º 9
0
        protected void FixedUpdate()
        {
            int pC;

            if (HighLogic.LoadedSceneIsFlight && part.CrewCapacity > 0 && (pC = part.protoModuleCrew.Count) > 0)
            {
                double UT = KSPUtils.GetUT();
                if (nextCheck < 0d)
                {
                    nextCheck = UT + checkInterval;
                }
                else if (UT > nextCheck)
                {
                    if (pressureAtKillAltitude == default)
                    {
                        pressureAtKillAltitude = FlightGlobals.GetHomeBody().GetPressureAtm(crewDeathAltitude);
                        _origDoStockGCalcs     = ProtoCrewMember.doStockGCalcs;
                    }

                    nextCheck = UT + checkInterval;
                    if (part.staticPressureAtm < pressureAtKillAltitude)
                    {
                        ScreenMessages.PostScreenMessage($"Cockpit is above the safe altitude which will lead to crew incapacitation and eventually to death", 1f, ScreenMessageStyle.UPPER_CENTER, XKCDColors.Red);

                        if (!_origDoStockGCalcs.HasValue)
                        {
                            _origDoStockGCalcs = ProtoCrewMember.doStockGCalcs;
                        }
                        ProtoCrewMember.doStockGCalcs = false;

                        bool killed = false;
                        for (int i = pC; i-- > 0;)
                        {
                            ProtoCrewMember pcm = part.protoModuleCrew[i];

                            double highGPenalty = vessel.geeForce > 3 ? vessel.geeForce : 1;
                            pcm.gExperienced += (0.5d + rnd.NextDouble()) * gDamageAdder * highGPenalty;

                            double gMult = ProtoCrewMember.GToleranceMult(pcm) * HighLogic.CurrentGame.Parameters.CustomParams <GameParameters.AdvancedParams>().KerbalGToleranceMult;
                            _anyCrewAboveWarnThreshold = pcm.gExperienced > PhysicsGlobals.KerbalGThresholdWarn * gMult;

                            double locThreshold = PhysicsGlobals.KerbalGThresholdLOC * gMult;
                            if (!pcm.outDueToG && pcm.gExperienced > locThreshold)
                            {
                                // Just passed out
                                ScreenMessages.PostScreenMessage($"<color=red>{pcm.name} has lost consciousness due to hypoxia!</color>", 5.5f, ScreenMessageStyle.UPPER_CENTER);
                            }

                            // There's at least one cycle of delay after passing out before the death chance rolls start
                            if (pcm.outDueToG && rnd.NextDouble() < crewDeathChance)
                            {
                                killed = true;
                                ScreenMessages.PostScreenMessage($"{vessel.vesselName}: Crewmember {pcm.name} has died from exposure to near-vacuum.", 30.0f, ScreenMessageStyle.UPPER_CENTER, XKCDColors.Red);
                                FlightLogger.fetch.LogEvent($"[{KSPUtil.PrintTime(vessel.missionTime, 3, false)}] {pcm.name} died from exposure to near-vacuum.");
                                part.RemoveCrewmember(pcm);
                                pcm.Die();
                            }
                        }

                        if (killed && CameraManager.Instance.currentCameraMode == CameraManager.CameraMode.IVA)
                        {
                            CameraManager.Instance.SetCameraFlight();
                        }
                    }
                    else
                    {
                        if (_origDoStockGCalcs.HasValue)
                        {
                            ProtoCrewMember.doStockGCalcs = _origDoStockGCalcs.Value;
                            _origDoStockGCalcs            = null;
                        }
                    }
                }
            }
        }
        private void MaintainContainment()
        {
            if (antimatter == null)
            {
                return;
            }

            float mult = 1;

            current_antimatter = antimatter.amount;
            explosion_size     = Math.Sqrt(current_antimatter) * 5.0;

            if (chargestatus > 0 && (current_antimatter > 0.00001 * antimatter.maxAmount))
            {
                chargestatus -= 1.0f * TimeWarp.fixedDeltaTime;
            }

            if (chargestatus >= GameConstants.MAX_ANTIMATTER_TANK_STORED_CHARGE)
            {
                mult = 0.5f;
            }

            if (!should_charge && current_antimatter <= 0.00001 * antimatter.maxAmount)
            {
                return;
            }

            var powerRequest = mult * 2.0 * chargeNeeded / 1000.0 * TimeWarp.fixedDeltaTime;

            double charge_to_add = CheatOptions.InfiniteElectricity
                ? powerRequest
                : consumeFNResource(powerRequest, FNResourceManager.FNRESOURCE_MEGAJOULES) * 1000.0f / chargeNeeded;

            chargestatus += charge_to_add;

            if (charge_to_add < 2f * TimeWarp.fixedDeltaTime)
            {
                float more_charge_to_add = ORSHelper.fixedRequestResource(part, FNResourceManager.STOCK_RESOURCE_ELECTRICCHARGE, mult * 2 * chargeNeeded * TimeWarp.fixedDeltaTime) / chargeNeeded;
                charge_to_add += more_charge_to_add;
                chargestatus  += more_charge_to_add;
            }

            if (charge_to_add >= 1f * TimeWarp.fixedDeltaTime)
            {
                charging = true;
            }
            else
            {
                charging = false;
                if (TimeWarp.CurrentRateIndex > 3 && (current_antimatter > 0.00001 * antimatter.maxAmount))
                {
                    TimeWarp.SetRate(3, true);
                    ScreenMessages.PostScreenMessage("Cannot Time Warp faster than 50x while Antimatter Tank is Unpowered", 1.0f, ScreenMessageStyle.UPPER_CENTER);
                }
            }
            //print (chargestatus);
            if (chargestatus <= 0)
            {
                chargestatus = 0;
                if (current_antimatter > 0.00001 * antimatter.maxAmount)
                {
                    explode_counter++;
                    if (explode_counter > 5)
                    {
                        doExplode();
                    }
                }
            }
            else
            {
                explode_counter = 0;
            }

            if (chargestatus > GameConstants.MAX_ANTIMATTER_TANK_STORED_CHARGE)
            {
                chargestatus = GameConstants.MAX_ANTIMATTER_TANK_STORED_CHARGE;
            }
        }
/*        public void LateUpdate()
 *      {
 *          if (!FlightDriver.Pause && FlightGlobals.fetch && FlightGlobals.Vessels != null)
 *          {
 *              foreach (Vessel v in FlightGlobals.Vessels)
 *              {
 *                  if (!v.loaded)
 *                      continue;
 *
 * //                    int tick = 0;
 * //                    float scalingFactor = 1;
 *                  //This scales up the inertia tensor over a few frames rather than trying to initialize with massive inertia tensors
 * //                    if (vesselOffRailsTick.TryGetValue(v, out tick))
 * //                    {
 * //                        scalingFactor = 1 - physicsEasingCurve.Evaluate(tick);
 * //                    }
 *
 *                  //ScreenMessages.PostScreenMessage("Scaling Factor: " + scalingFactor, TimeWarp.deltaTime, ScreenMessageStyle.UPPER_LEFT);
 *
 *                  foreach (Part p in v.Parts)
 *                  {
 *                      //if (p.Modules.Contains("LaunchClamp"))
 *                      //    continue;
 *                      // This relies on KSP resetting the tensors to a constant in Update
 *                      if (p.started && p.State != PartStates.DEAD && p.rb)
 *                      {
 *                          float mass = p.rb.mass;// *scalingFactor;
 *
 *                          if (mass > 1f)
 *                              p.rb.inertiaTensor *= mass;
 *                      }
 *                  }
 *              }
 *          }
 *      }*/

        public void FixedUpdate()
        {
            if (FlightGlobals.ready && FlightGlobals.Vessels != null)
            {
                for (int i = 0; i < updatedVessels.Count; ++i)
                {
                    Vessel v = updatedVessels[i];
                    if (v == null || !vesselOffRailsTick.ContainsKey(v))
                    {
                        continue;
                    }

                    int tick = vesselOffRailsTick[v];
                    if (tick > 0)
                    {
                        float physicsScalingFactor = physicsEasingCurve.Evaluate(tick);
                        if (tick >= numTicksForEasing)
                        {
                            List <Joint> jointList = new List <Joint>();
                            foreach (Part p in v.Parts)
                            {
                                p.crashTolerance = p.crashTolerance * 10000f;
                                if (p.attachJoint)
                                {
                                    p.attachJoint.SetUnbreakable(true);
                                }

                                Joint[] partJoints = p.GetComponents <Joint>();

/*                                foreach (Joint j in partJoints)
 *                              {
 * //                                    j.breakForce *= 1000000000000000000;
 * //                                    j.breakTorque *= 1000000000000000000;
 *                                  jointList.Add(j);
 *                                  Debug.Log("Part: " + p.partInfo.title + " BreakForce = " + j.breakForce + " BreakTorque = " + j.breakTorque);
 *                              }*/
                                if (p.Modules.Contains <LaunchClamp>())
                                {
                                    foreach (Joint j in partJoints)
                                    {
                                        if (j.connectedBody == null)
                                        {
                                            jointList.Remove(j);
                                            GameObject.Destroy(j);
                                            KJRJointUtils.ConnectLaunchClampToGround(p);
                                            break;
                                        }
                                    }
                                }
                            }
                            //vesselJointStrengthened.Add(v, jointList);
                        }
                        bool easing = false;
                        if (v.situation == Vessel.Situations.PRELAUNCH || v.situation == Vessel.Situations.LANDED || v.situation == Vessel.Situations.SPLASHED)
                        {
                            easing = true;
                        }
                        else
                        {
                            foreach (Part p in v.Parts)
                            {
                                if (p.Modules.Contains <LaunchClamp>())
                                {
                                    easing = true;
                                    break;
                                }
                            }
                        }
                        if (easing)
                        {
                            Vector3d vesselPos          = v.GetWorldPos3D();
                            Vector3d vesselVel          = v.obt_velocity;
                            Vector3d vesselAcceleration = FlightGlobals.getGeeForceAtPosition(vesselPos) + FlightGlobals.getCentrifugalAcc(vesselPos, FlightGlobals.currentMainBody) + FlightGlobals.getCoriolisAcc(vesselVel, FlightGlobals.currentMainBody);
                            vesselAcceleration *= physicsScalingFactor;
                            foreach (Part p in v.Parts)
                            {
                                if (p.rb)
                                {
                                    p.rb.AddForce(-vesselAcceleration * p.rb.mass);
                                }
                            }
                        }
                        if (v == FlightGlobals.ActiveVessel)
                        {
                            if (InputLockManager.GetControlLock("KJRLoadLock") != ControlTypes.ALL_SHIP_CONTROLS)
                            {
                                InputLockManager.SetControlLock(ControlTypes.ALL_SHIP_CONTROLS, "KJRLoadLock");
                            }
                            ScreenMessages.PostScreenMessage("KJR stabilizing physics load...", TimeWarp.fixedDeltaTime, ScreenMessageStyle.UPPER_RIGHT);
                        }
                        else
                        if (InputLockManager.GetControlLock("KJRLoadLock") == ControlTypes.ALL_SHIP_CONTROLS)
                        {
                            InputLockManager.RemoveControlLock("KJRLoadLock");
                        }

                        tick--;
                        vesselOffRailsTick[v] = tick;
                    }
                    else if (tick == 0)
                    {
                        foreach (Part p in v.Parts)
                        {
                            p.crashTolerance = p.crashTolerance / 10000f;
                            if (p.attachJoint)
                            {
                                p.attachJoint.SetUnbreakable(false);
                            }
                        }

                        vesselOffRailsTick.Remove(v);
                        if (InputLockManager.GetControlLock("KJRLoadLock") == ControlTypes.ALL_SHIP_CONTROLS)
                        {
                            InputLockManager.RemoveControlLock("KJRLoadLock");
                        }
                    }
                    else
                    {
                        foreach (Part p in v.Parts)
                        {
                            p.crashTolerance = p.crashTolerance / 10000f;
                            if (p.attachJoint)
                            {
                                p.attachJoint.SetUnbreakable(false);
                            }
                        }

                        vesselOffRailsTick.Remove(v);
                        if (InputLockManager.GetControlLock("KJRLoadLock") == ControlTypes.ALL_SHIP_CONTROLS)
                        {
                            InputLockManager.RemoveControlLock("KJRLoadLock");
                        }
                    }
                }
            }
        }
Exemplo n.º 12
0
 private void ScreenMsg(string msg)
 {
     ScreenMessages.PostScreenMessage(new ScreenMessage(msg, 4, ScreenMessageStyle.UPPER_LEFT));
 }
Exemplo n.º 13
0
        public void SetupToolBarButtons()
        {
            if (!ToolbarManager.ToolbarAvailable)
            {
                return;
            }

            SetupMainToolbarButton();

            foreach (DisplayModule module in core.GetDisplayModules(DisplayOrder.instance).Where(m => !m.hidden))
            {
                Button button;
                if (!toolbarButtons.ContainsKey(module))
                {
                    Debug.Log("Create button for module " + module.GetName());

                    String name = GetCleanName(module.GetName());

                    String TexturePath       = "MechJeb2/Icons/" + name;
                    String TexturePathActive = TexturePath + "_active";

                    button        = new Button();
                    button.button = ToolbarManager.Instance.add("MechJeb2", name);

                    if (GameDatabase.Instance.GetTexture(TexturePath, false) == null)
                    {
                        button.texturePath = Qmark;
                        print("No icon for " + name);
                    }
                    else
                    {
                        button.texturePath = TexturePath;
                    }

                    if (GameDatabase.Instance.GetTexture(TexturePathActive, false) == null)
                    {
                        button.texturePathActive = TexturePath;
                        //print("No icon for " + name + "_active");
                    }
                    else
                    {
                        button.texturePathActive = TexturePathActive;
                    }

                    toolbarButtons[module] = button;

                    button.button.ToolTip  = "MechJeb " + module.GetName();
                    button.button.OnClick += (b) =>
                    {
                        DisplayModule mod = FlightGlobals.ActiveVessel.GetMasterMechJeb().GetDisplayModules(DisplayOrder.instance).FirstOrDefault(m => m == module);
                        if (mod != null)
                        {
                            mod.enabled = !mod.enabled;
                        }
                    };
                }
                else
                {
                    button = toolbarButtons[module];
                }

                button.button.Visible     = module.showInCurrentScene;
                button.button.TexturePath = module.isActive() ? button.texturePathActive : button.texturePath;
            }

            // create toolbar buttons for features
            if (featureButtons.Count == 0)
            {
                var maneuverPlannerModule = core.GetComputerModule <MechJebModuleManeuverPlanner>();
                if (!HighLogic.LoadedSceneIsEditor && maneuverPlannerModule != null && !maneuverPlannerModule.hidden)
                {
                    CreateFeatureButton(maneuverPlannerModule, "Exec_Node", "MechJeb Execute Next Node", (b) =>
                    {
                        if (vessel.patchedConicSolver.maneuverNodes.Count > 0 && core.node != null)
                        {
                            if (core.node.enabled)
                            {
                                core.node.Abort();
                            }
                            else
                            {
                                if (vessel.patchedConicSolver.maneuverNodes[0].DeltaV.magnitude > 0.0001)
                                {
                                    core.node.ExecuteOneNode(maneuverPlannerModule);
                                }
                                else
                                {
                                    ScreenMessages.PostScreenMessage("Maneuver burn vector not set", 3f);
                                }
                            }
                        }
                        else
                        {
                            ScreenMessages.PostScreenMessage("No maneuver nodes", 2f);
                        }
                    }, () => vessel.patchedConicSolver.maneuverNodes.Count > 0 && core.node != null && core.node.enabled);

                    CreateFeatureButton(maneuverPlannerModule, "Autostage_Once", "MechJeb Autostage Once", (b) =>
                    {
                        var w = core.GetComputerModule <MechJebModuleThrustWindow>();

                        if (core.staging.enabled && core.staging.autostagingOnce)
                        {
                            if (core.staging.users.Contains(w))
                            {
                                core.staging.users.Remove(w);
                                w.autostageSavedState = false;
                            }
                        }
                        else
                        {
                            core.staging.AutostageOnce(w);
                        }
                    }, () => core.staging.enabled && core.staging.autostagingOnce);

                    CreateFeatureButton(maneuverPlannerModule, "Auto_Warp", "MechJeb Auto-warp", (b) =>
                    {
                        core.node.autowarp = !core.node.autowarp;
                    }, () => core.node.autowarp);
                }
            }
        }
Exemplo n.º 14
0
        private void DrawPrintProgress()
        {
            // Currently build item
            if (_processedItem != null)
            {
                if (_processedItem.Icon == null)
                {
                    _processedItem.EnableIcon(64);
                }
                GUI.Box(new Rect(190, 620, 50, 50), _processedItem.Icon.texture);
            }
            else
            {
                GUI.Box(new Rect(190, 620, 50, 50), "");
            }

            // Progressbar
            GUI.Box(new Rect(250, 620, 280, 50), "");
            if (progress >= 1)
            {
                var color = GUI.color;
                GUI.color = new Color(0, 1, 0, 1);
                GUI.Box(new Rect(250, 620, 280 * progress / 100, 50), "");
                GUI.color = color;
            }
            string progressText = string.Format("Progress: {0:n1}%, T- ", progress) + KSPUtil.PrintTime(_processedBlueprint.GetBuildTime(adjustedProductivity), 5, false);

            GUI.Label(new Rect(250, 620, 280, 50), " " + progressText);

            //Pause/resume production
            Texture2D buttonTexture = _pauseTexture;

            if (manufacturingPaused || _processedItem == null)
            {
                buttonTexture = _playTexture;
            }
            if (GUI.Button(new Rect(530, 620, 50, 50), buttonTexture) && _processedItem != null)
            {
                manufacturingPaused = !manufacturingPaused;
            }

            //Cancel production
            if (GUI.Button(new Rect(580, 620, 50, 50), _binTexture))
            {
                if (_confirmDelete)
                {
                    _processedItem.DisableIcon();
                    _processedItem      = null;
                    _processedBlueprint = null;
                    progress            = 0;
                    manufacturingPaused = false;
                    Status = "Online";

                    if (Animate && _heatAnimation != null && _workAnimation != null)
                    {
                        StartCoroutine(StopAnimations());
                    }
                    _confirmDelete = false;
                }

                else
                {
                    _confirmDelete = true;
                    ScreenMessages.PostScreenMessage("Click the cancel button again to confirm cancelling current production", 5.0f, ScreenMessageStyle.UPPER_CENTER);
                }
            }
        }
Exemplo n.º 15
0
        IEnumerator CommandPosition(IBDAIControl wingman, PilotCommands command)
        {
            if (focusIndexes.Count == 0 && !commandSelf)
            {
                yield break;
            }

            DisplayScreenMessage("Select target coordinates.\nRight-click to cancel.");

            if (command == PilotCommands.FlyTo)
            {
                waitingForFlytoPos = true;
            }
            else if (command == PilotCommands.Attack)
            {
                waitingForAttackPos = true;
            }

            yield return(null);

            bool waitingForPos = true;

            drawMouseDiamond = true;
            while (waitingForPos)
            {
                if (Input.GetMouseButtonDown(1))
                {
                    break;
                }
                if (Input.GetMouseButtonDown(0))
                {
                    Vector3 mousePos = new Vector3(Input.mousePosition.x / Screen.width,
                                                   Input.mousePosition.y / Screen.height, 0);
                    Plane surfPlane = new Plane(vessel.upAxis,
                                                vessel.transform.position - (vessel.altitude * vessel.upAxis));
                    Ray   ray = FlightCamera.fetch.mainCamera.ViewportPointToRay(mousePos);
                    float dist;
                    if (surfPlane.Raycast(ray, out dist))
                    {
                        Vector3  worldPoint = ray.GetPoint(dist);
                        Vector3d gps        = VectorUtils.WorldPositionToGeoCoords(worldPoint, vessel.mainBody);

                        if (command == PilotCommands.FlyTo)
                        {
                            wingman.CommandFlyTo(gps);
                        }
                        else if (command == PilotCommands.Attack)
                        {
                            wingman.CommandAttack(gps);
                        }

                        StartCoroutine(CommandPositionGUIRoutine(wingman, new GPSTargetInfo(gps, command.ToString())));
                    }

                    break;
                }
                yield return(null);
            }

            waitingForAttackPos = false;
            waitingForFlytoPos  = false;
            drawMouseDiamond    = false;
            ScreenMessages.RemoveMessage(screenMessage);
        }
Exemplo n.º 16
0
        internal void processUpgrade()
        {
            int oldLevel = getMember <int>("level");

            KCTDebug.Log($"Upgrading from level {oldLevel}");

            string facilityID = GetFacilityID();

            string gate = GetTechGate(facilityID, oldLevel + 1);

            Debug.Log("[KCTT] Gate for " + facilityID + "? " + gate);
            if (!string.IsNullOrEmpty(gate))
            {
                if (ResearchAndDevelopment.GetTechnologyState(gate) != RDTech.State.Available)
                {
                    PopupDialog.SpawnPopupDialog(new MultiOptionDialog("kctUpgradePadConfirm",
                                                                       "Can't upgrade this facility. Requires " + KerbalConstructionTimeData.techNameToTitle[gate] + ".",
                                                                       "Lack Tech to Upgrade",
                                                                       HighLogic.UISkin,
                                                                       new DialogGUIButton("Ok", stub)),
                                                 false,
                                                 HighLogic.UISkin);

                    return;
                }
            }

            KCT_UpgradingBuilding upgrading = new KCT_UpgradingBuilding(facilityID, oldLevel + 1, oldLevel, facilityID.Split('/').Last());

            upgrading.isLaunchpad = facilityID.ToLower().Contains("launchpad");
            if (upgrading.isLaunchpad)
            {
                upgrading.launchpadID = KCT_GameStates.ActiveKSC.ActiveLaunchPadID;
                if (upgrading.launchpadID > 0)
                {
                    upgrading.commonName += KCT_GameStates.ActiveKSC.ActiveLPInstance.name;
                }
            }

            if (!upgrading.AlreadyInProgress())
            {
                float cost = getMember <float>("upgradeCost");

                if (Funding.CanAfford(cost))
                {
                    Funding.Instance.AddFunds(-cost, TransactionReasons.Structures);
                    KCT_GameStates.ActiveKSC.KSCTech.Add(upgrading);
                    upgrading.SetBP(cost);
                    upgrading.cost = cost;

                    ScreenMessages.PostScreenMessage("Facility upgrade requested!", 4.0f, ScreenMessageStyle.UPPER_CENTER);
                    KCTDebug.Log($"Facility {facilityID} upgrade requested to lvl {oldLevel + 1} for {cost} funds, resulting in a BP of {upgrading.BP}");
                }
                else
                {
                    KCTDebug.Log("Couldn't afford to upgrade.");
                    ScreenMessages.PostScreenMessage("Not enough funds to upgrade facility!", 4.0f, ScreenMessageStyle.UPPER_CENTER);
                }
            }
            else if (oldLevel + 1 != upgrading.currentLevel)
            {
                ScreenMessages.PostScreenMessage("Facility is already being upgraded!", 4.0f, ScreenMessageStyle.UPPER_CENTER);
                KCTDebug.Log($"Facility {facilityID} tried to upgrade to lvl {oldLevel + 1} but already in list!");
            }
        }
        public override void OnStart(PartModule.StartState state)
        {
            Actions["ToggleToggleResourceAction"].guiName = Events["ToggleResource"].guiName = String.Format("Toggle Resource");

            if (state == StartState.Editor)
            {
                return;
            }

            this.part.force_activate();

            // verify if body has atmosphere at all
            if (!vessel.mainBody.atmosphere)
            {
                return;
            }

            // verify scoop was enabled
            if (!scoopIsEnabled)
            {
                return;
            }

            // verify a timestamp is available
            if (last_active_time == 0)
            {
                return;
            }

            // verify any power was avaialble in previous save
            if (last_power_percentage < 0.01)
            {
                return;
            }

            // verify altitude is not too high
            if (vessel.altitude > (PluginHelper.getMaxAtmosphericAltitude(vessel.mainBody) * PluginHelper.MaxAtmosphericAltitudeMult))
            {
                ScreenMessages.PostScreenMessage("Vessel is too high for resource accumulation", 10, ScreenMessageStyle.LOWER_CENTER);
                return;
            }

            // verify altitude is not too low
            if (vessel.altitude < (PluginHelper.getMaxAtmosphericAltitude(vessel.mainBody)))
            {
                ScreenMessages.PostScreenMessage("Vessel is too low for resource accumulation", 10, ScreenMessageStyle.LOWER_CENTER);
                return;
            }

            // verify eccentricity
            if (vessel.orbit.eccentricity > 0.1)
            {
                string message = "Eccentricity of " + vessel.orbit.eccentricity.ToString("0.0000") + " is too High for resource accumulations";
                ScreenMessages.PostScreenMessage(message, 10.0f, ScreenMessageStyle.LOWER_CENTER);
                return;
            }

            // verify that an electric or Thermal engine is available with high enough ISP
            var highIspEngine = part.vessel.parts.Find(p =>
                                                       p.FindModulesImplementing <ElectricEngineControllerFX>().Any(e => e.baseISP > 4200) ||
                                                       p.FindModulesImplementing <ThermalNozzleController>().Any(e => e.AttachedReactor.CoreTemperature > 40000));

            if (highIspEngine == null)
            {
                ScreenMessages.PostScreenMessage("No engine available, with high enough Isp and propelant switch ability to compensate for atmospheric drag", 10, ScreenMessageStyle.LOWER_CENTER);
                return;
            }

            // calcualte time past since last frame
            double time_diff = (Planetarium.GetUniversalTime() - last_active_time) * 55;

            // scoop athmosphere for entire durration
            ScoopAthmosphere(time_diff, true);
        }
 public override void PrintMissingResources()
 {
     ScreenMessages.PostScreenMessage(Localizer.Format("#LOC_KSPIE_WaterElectroliser_Postmsg") + " " + _pureWater.name, 3.0f, ScreenMessageStyle.UPPER_CENTER);//Missing
 }
        private void ScoopAthmosphere(double deltaTimeInSeconds, bool offlineCollecting)
        {
            string ors_atmospheric_resource_name = AtmosphericResourceHandler.getAtmosphericResourceName(vessel.mainBody.flightGlobalsIndex, currentresource);
            string resourceDisplayName           = AtmosphericResourceHandler.getAtmosphericResourceDisplayName(vessel.mainBody.flightGlobalsIndex, currentresource);

            if (ors_atmospheric_resource_name == null)
            {
                resflowf      = 0;
                recievedPower = "error";
                densityFractionOfUpperAthmosphere = "error";
                return;
            }

            // map ors resource to kspi resource

            if (PluginHelper.OrsResourceMappings == null || !PluginHelper.OrsResourceMappings.TryGetValue(ors_atmospheric_resource_name, out resourceStoragename))
            {
                resourceStoragename = ors_atmospheric_resource_name;
            }
            else if (!PartResourceLibrary.Instance.resourceDefinitions.Contains(resourceStoragename))
            {
                resourceStoragename = ors_atmospheric_resource_name;
            }

            //double resourcedensity = PartResourceLibrary.Instance.GetDefinition(PluginHelper.atomspheric_resources_tocollect[currentresource]).density;
            var definition = PartResourceLibrary.Instance.GetDefinition(resourceStoragename);

            if (definition == null)
            {
                return;
            }

            double resourcedensity = definition.density;

            double maxAltitudeAtmosphere = PluginHelper.getMaxAtmosphericAltitude(vessel.mainBody);

            double upperAtmospherFraction = Math.Max(0, (vessel.altitude - maxAltitudeAtmosphere) / Math.Max(0.000001, maxAltitudeAtmosphere * PluginHelper.MaxAtmosphericAltitudeMult - maxAltitudeAtmosphere));
            double upperatmosphereDensity = 1 - upperAtmospherFraction;

            double airDensity = part.vessel.atmDensity + (PluginHelper.MinAtmosphericAirDensity * upperatmosphereDensity);

            atmosphericDensity = airDensity.ToString("0.00000000");

            var hydrogenTax = 0.4 * Math.Sin(upperAtmospherFraction * Math.PI * 0.5);
            var heliumTax   = 0.2 * Math.Sin(upperAtmospherFraction * Math.PI);

            double rescourceFraction = (1.0 - hydrogenTax - heliumTax) * AtmosphericResourceHandler.getAtmosphericResourceContent(vessel.mainBody.flightGlobalsIndex, currentresource);

            // increase density hydrogen
            if (resourceDisplayName == "Hydrogen")
            {
                rescourceFraction += hydrogenTax;
            }
            else if (resourceDisplayName == "Helium")
            {
                rescourceFraction += heliumTax;
            }

            densityFractionOfUpperAthmosphere = (upperatmosphereDensity * 100).ToString("0.000") + "%";
            rescourcePercentage = rescourceFraction * 100;
            if (rescourceFraction <= 0 || vessel.altitude > (PluginHelper.getMaxAtmosphericAltitude(vessel.mainBody) * PluginHelper.MaxAtmosphericAltitudeMult))
            {
                resflowf      = 0;
                recievedPower = "off";
                densityFractionOfUpperAthmosphere = "too high";
                rescourcePercentage = 0;
                return;
            }

            double airspeed            = part.vessel.srf_velocity.magnitude + 40;
            double air                 = airspeed * (airDensity / 1000) * scoopair / resourcedensity;
            double scoopedAtm          = air * rescourceFraction;
            double powerrequirementsMW = (scoopair / 0.15) * 6 * PluginHelper.PowerConsumptionMultiplier * powerReqMult;

            if (scoopedAtm > 0 && part.GetResourceSpareCapacity(resourceStoragename) > 0)
            {
                var powerRequest = powerrequirementsMW * TimeWarp.fixedDeltaTime;

                // calculate available power
                double powerreceivedMW = CheatOptions.InfiniteElectricity
                    ? powerRequest
                    : Math.Max(consumeFNResource(powerRequest, ResourceManager.FNRESOURCE_MEGAJOULES), 0);

                double normalisedRevievedPowerMW = powerreceivedMW / TimeWarp.fixedDeltaTime;

                // if power requirement sufficiently low, retreive power from KW source
                if (powerrequirementsMW < 2 && normalisedRevievedPowerMW <= powerrequirementsMW)
                {
                    var requiredKW = (powerrequirementsMW - normalisedRevievedPowerMW) * 1000;
                    var recievedKW = part.RequestResource(ResourceManager.STOCK_RESOURCE_ELECTRICCHARGE, requiredKW * TimeWarp.fixedDeltaTime);
                    powerreceivedMW += (recievedKW / 1000);
                }

                last_power_percentage = offlineCollecting ? last_power_percentage : powerreceivedMW / powerrequirementsMW / TimeWarp.fixedDeltaTime;
            }
            else
            {
                last_power_percentage = 0;
                powerrequirementsMW   = 0;
            }

            recievedPower = powerrequirementsMW < 2
                ? (last_power_percentage * powerrequirementsMW * 1000).ToString("0.0") + " KW / " + (powerrequirementsMW * 1000).ToString("0.0") + " KW"
                : (last_power_percentage * powerrequirementsMW).ToString("0.0") + " MW / " + powerrequirementsMW.ToString("0.0") + " MW";

            double resourceChange = scoopedAtm * last_power_percentage * deltaTimeInSeconds;

            if (offlineCollecting)
            {
                string numberformat = resourceChange > 100 ? "0" : "0.00";
                ScreenMessages.PostScreenMessage("Atmospheric Scoop collected " + resourceChange.ToString(numberformat) + " " + resourceStoragename, 10.0f, ScreenMessageStyle.LOWER_CENTER);
            }

            resflowf = part.RequestResource(resourceStoragename, -resourceChange);
            resflowf = -resflowf / TimeWarp.fixedDeltaTime;
            UpdateResourceFlow();
        }
Exemplo n.º 20
0
        public override void OnFixedUpdateResourceSuppliable(double fixedDeltaTime)
        {
            temperatureStr = part.temperature.ToString("F0") + "K / " + part.maxTemp.ToString("F0") + "K";
            MinIsp         = BaseFloatCurve.Evaluate((float)altitude);

            resourceBuffers.UpdateVariable(ResourceSettings.Config.WasteHeatInMegawatt, part.mass);
            resourceBuffers.UpdateBuffers();

            if (curEngineT == null || !curEngineT.isEnabled)
            {
                return;
            }

            if (curEngineT.requestedThrottle > 0)
            {
                if (radHazard && rad_safety_features)
                {
                    ShutDown(Localizer.Format("#LOC_KSPIE_FusionECU2_PostMsg2"));//"Engines throttled down as they presently pose a radiation hazard"
                }
            }

            KillKerbalsWithRadiation(fusionRatio);

            hasIspThrottling = HasIspThrottling();

            ShowIspThrottle = hasIspThrottling;

            availablePower = Math.Max(GetResourceAvailability(ResourceSettings.Config.ElectricPowerInMegawatt), GetAvailablePrioritizedStableSupply(ResourceSettings.Config.ElectricPowerInMegawatt));

            currentMaximumPowerProduction  = GetCurrentMaximumPowerProduction();
            currentMaximumPowerRequirement = GetCurrentMaximumPowerRequirement();

            requiredPowerPerSecond = curEngineT.currentThrottle * currentMaximumPowerRequirement;

            if (curEngineT.currentThrottle > 0)
            {
                requestedPowerPerSecond = Math.Min(requiredPowerPerSecond, availablePower);

                recievedPowerPerSecond = requestedPowerPerSecond <= 0 ? 0
                    : CheatOptions.InfiniteElectricity
                        ? requiredPowerPerSecond
                        : ConsumeFnResourcePerSecond(requestedPowerPerSecond, ResourceSettings.Config.ElectricPowerInMegawatt);

                fusionRatio = requiredPowerPerSecond > 0 ? Math.Min(1, recievedPowerPerSecond / requiredPowerPerSecond) : 1;

                var inefficiency = 1 - LaserEfficiency;

                laserWasteheat         = recievedPowerPerSecond * inefficiency;
                producedPowerPerSecond = fusionRatio * currentMaximumPowerProduction;

                if (!CheatOptions.InfiniteElectricity && currentMaximumPowerProduction > 0)
                {
                    SupplyFnResourcePerSecondWithMax(producedPowerPerSecond, currentMaximumPowerProduction, ResourceSettings.Config.ElectricPowerInMegawatt);
                }

                // Lasers produce Wasteheat
                if (!CheatOptions.IgnoreMaxTemperature && laserWasteheat > 0)
                {
                    SupplyFnResourcePerSecondWithMax(laserWasteheat, currentMaximumPowerRequirement * inefficiency, ResourceSettings.Config.WasteHeatInMegawatt);
                }

                // The Absorbed wasteheat from Fusion
                rateMultplier        = hasIspThrottling ? Math.Pow(SelectedIsp / MinIsp, 2) : 1;
                neutronbsorbionBonus = hasIspThrottling ? 1 - NeutronAbsorptionFractionAtMinIsp * (1 - ((SelectedIsp - MinIsp) / (MaxIsp - MinIsp))) : 0.5;
                absorbedWasteheat    = FusionWasteHeat * fusionRatio * curEngineT.currentThrottle * neutronbsorbionBonus;
                SupplyFnResourcePerSecond(absorbedWasteheat, ResourceSettings.Config.WasteHeatInMegawatt);

                SetRatios();

                currentIsp = hasIspThrottling ? SelectedIsp : MinIsp;
                UpdateAtmosphereCurve(currentIsp);
                maximumThrust = hasIspThrottling ? MaximumThrust : FullTrustMaximum;

                // Update FuelFlow
                maxFuelFlow = fusionRatio * maximumThrust / currentIsp / PhysicsGlobals.GravitationalAcceleration;

                if ((maxAtmosphereDensity >= 0 && vessel.atmDensity > maxAtmosphereDensity) ||
                    (_currentActiveConfiguration.maxAtmosphereDensity >= 0 && vessel.atmDensity > _currentActiveConfiguration.maxAtmosphereDensity))
                {
                    ScreenMessages.PostScreenMessage(Localizer.Format("#LOC_KSPIE_FusionECU2_PostMsg1"), 1.0f, ScreenMessageStyle.UPPER_CENTER);
                    curEngineT.maxFuelFlow = 1e-10f;
                    curEngineT.maxThrust   = Mathf.Max((float)maximumThrust, 0.0001f);
                    HideExhaust();
                }
                else if (MinIsp < _currentActiveConfiguration.minIsp)
                {
                    ScreenMessages.PostScreenMessage(Localizer.Format("#LOC_KSPIE_FusionECU2_PostMsg3"), 1.0f, ScreenMessageStyle.UPPER_CENTER);
                    curEngineT.maxFuelFlow = 1e-10f;
                    curEngineT.maxThrust   = Mathf.Max((float)maximumThrust, 0.0001f);
                    HideExhaust();
                }
                else
                {
                    curEngineT.maxFuelFlow = Mathf.Max((float)maxFuelFlow, 1e-10f);
                    curEngineT.maxThrust   = Mathf.Max((float)maximumThrust, 0.0001f);
                }

                if (!curEngineT.getFlameoutState && fusionRatio < 0.9 && recievedPowerPerSecond > 0)
                {
                    curEngineT.status = Localizer.Format("#LOC_KSPIE_FusionECU2_statu1");//"Insufficient Electricity"
                }
            }
            else
            {
                absorbedWasteheat       = 0;
                laserWasteheat          = 0;
                requestedPowerPerSecond = 0;
                recievedPowerPerSecond  = 0;

                fusionRatio = requiredPowerPerSecond > 0 ? Math.Min(1, availablePower / requiredPowerPerSecond) : 1;

                currentIsp    = hasIspThrottling ? SelectedIsp : MinIsp;
                maximumThrust = hasIspThrottling ? MaximumThrust : FullTrustMaximum;

                UpdateAtmosphereCurve(currentIsp);

                rateMultplier = hasIspThrottling ? Math.Pow(SelectedIsp / MinIsp, 2) : 1;

                maxFuelFlow = fusionRatio * maximumThrust / currentIsp / PhysicsGlobals.GravitationalAcceleration;

                if ((maxAtmosphereDensity >= 0 && vessel.atmDensity > maxAtmosphereDensity) ||
                    (_currentActiveConfiguration.maxAtmosphereDensity >= 0 && vessel.atmDensity > _currentActiveConfiguration.maxAtmosphereDensity))
                {
                    curEngineT.maxFuelFlow = 1e-10f;
                    curEngineT.maxThrust   = Mathf.Max((float)maximumThrust, 0.0001f);
                    HideExhaust();
                }
                else if (MinIsp < _currentActiveConfiguration.minIsp)
                {
                    curEngineT.maxFuelFlow = 1e-10f;
                    curEngineT.maxThrust   = Mathf.Max((float)maximumThrust, 0.0001f);
                    HideExhaust();
                }
                else
                {
                    curEngineT.maxFuelFlow = Mathf.Max((float)maxFuelFlow, 1e-10f);
                    curEngineT.maxThrust   = Mathf.Max((float)maximumThrust, 0.0001f);
                }

                SetRatios();
            }

            coldBathTemp          = FNRadiator.GetAverageRadiatorTemperatureForVessel(vessel);
            maxTempatureRadiators = FNRadiator.GetAverageMaximumRadiatorTemperatureForVessel(vessel);
            radiatorPerformance   = Math.Max(1 - (coldBathTemp / maxTempatureRadiators), 0.000001);
            partEmissiveConstant  = part.emissiveConstant;
        }
Exemplo n.º 21
0
        private void HandleChatEvents()
        {
            //Handle leave event
            if (!leaveEventHandled)
            {
                if (!string.IsNullOrEmpty(selectedChannel) && selectedChannel != consoleIdentifier)
                {
                    using (MessageWriter mw = new MessageWriter())
                    {
                        mw.Write <int>((int)ChatMessageType.LEAVE);
                        mw.Write <string>(dmpSettings.playerName);
                        mw.Write <string>(selectedChannel);
                        networkWorker.SendChatMessage(mw.GetMessageBytes());
                    }

                    if (joinedChannels.Contains(selectedChannel))
                    {
                        joinedChannels.Remove(selectedChannel);
                    }

                    selectedChannel   = null;
                    selectedPMChannel = null;
                }
                if (!string.IsNullOrEmpty(selectedPMChannel))
                {
                    if (joinedPMChannels.Contains(selectedPMChannel))
                    {
                        joinedPMChannels.Remove(selectedPMChannel);
                    }

                    selectedChannel   = null;
                    selectedPMChannel = null;
                }

                leaveEventHandled = true;
            }
            //Handle send event
            if (!sendEventHandled)
            {
                if (sendText != "")
                {
                    HandleChatInput(sendText);
                }
                sendText         = "";
                sendEventHandled = true;
            }
            //Handle join messages
            while (newJoinMessages.Count > 0)
            {
                JoinLeaveMessage jlm = newJoinMessages.Dequeue();
                if (!playerChannels.ContainsKey(jlm.fromPlayer))
                {
                    playerChannels.Add(jlm.fromPlayer, new List <string>());
                }
                if (!playerChannels[jlm.fromPlayer].Contains(jlm.channel))
                {
                    playerChannels[jlm.fromPlayer].Add(jlm.channel);
                }
            }
            //Handle leave messages
            while (newLeaveMessages.Count > 0)
            {
                JoinLeaveMessage jlm = newLeaveMessages.Dequeue();
                if (playerChannels.ContainsKey(jlm.fromPlayer))
                {
                    if (playerChannels[jlm.fromPlayer].Contains(jlm.channel))
                    {
                        playerChannels[jlm.fromPlayer].Remove(jlm.channel);
                    }
                    if (playerChannels[jlm.fromPlayer].Count == 0)
                    {
                        playerChannels.Remove(jlm.fromPlayer);
                    }
                }
            }
            //Handle channel messages
            while (newChannelMessages.Count > 0)
            {
                ChannelEntry ce = newChannelMessages.Dequeue();
                if (!channelMessages.ContainsKey(ce.channel))
                {
                    channelMessages.Add(ce.channel, new List <string>());
                }

                // Write message to screen if chat window is disabled
                if (!display)
                {
                    chatButtonHighlighted = ce.fromPlayer != consoleIdentifier;

                    if (!string.IsNullOrEmpty(ce.channel))
                    {
                        ScreenMessages.PostScreenMessage(ce.fromPlayer + " -> #" + ce.channel + ": " + ce.message, 5f, ScreenMessageStyle.UPPER_LEFT);
                    }
                    else
                    {
                        ScreenMessages.PostScreenMessage(ce.fromPlayer + " -> #Global : " + ce.message, 5f, ScreenMessageStyle.UPPER_LEFT);
                    }
                }

                //Highlight if the channel isn't selected.
                if (!string.IsNullOrEmpty(selectedChannel) && string.IsNullOrEmpty(ce.channel) && ce.fromPlayer != consoleIdentifier)
                {
                    if (!highlightChannel.Contains(ce.channel))
                    {
                        highlightChannel.Add(ce.channel);
                    }
                }

                if (!string.IsNullOrEmpty(ce.channel) && ce.channel != selectedChannel)
                {
                    if (!highlightChannel.Contains(ce.channel))
                    {
                        highlightChannel.Add(ce.channel);
                    }
                }

                //Move the bar to the bottom on a new message
                if (string.IsNullOrEmpty(selectedChannel) && string.IsNullOrEmpty(selectedPMChannel) && string.IsNullOrEmpty(ce.channel))
                {
                    chatScrollPos.y = float.PositiveInfinity;
                    selectTextBox   = chatLocked;
                }

                if (!string.IsNullOrEmpty(selectedChannel) && string.IsNullOrEmpty(selectedPMChannel) && ce.channel == selectedChannel)
                {
                    chatScrollPos.y = float.PositiveInfinity;
                    selectTextBox   = chatLocked;
                }

                channelMessages[ce.channel].Add(ce.fromPlayer + ": " + ce.message);
            }
            //Handle private messages
            while (newPrivateMessages.Count > 0)
            {
                PrivateEntry pe = newPrivateMessages.Dequeue();
                if (pe.fromPlayer != dmpSettings.playerName)
                {
                    if (!privateMessages.ContainsKey(pe.fromPlayer))
                    {
                        privateMessages.Add(pe.fromPlayer, new List <string>());
                    }

                    //Highlight if the player isn't selected
                    if (!joinedPMChannels.Contains(pe.fromPlayer))
                    {
                        joinedPMChannels.Add(pe.fromPlayer);
                    }

                    if (selectedPMChannel != pe.fromPlayer)
                    {
                        if (!highlightPM.Contains(pe.fromPlayer))
                        {
                            highlightPM.Add(pe.fromPlayer);
                        }
                    }
                }

                if (!privateMessages.ContainsKey(pe.toPlayer))
                {
                    privateMessages.Add(pe.toPlayer, new List <string>());
                }

                //Move the bar to the bottom on a new message
                if (!string.IsNullOrEmpty(selectedPMChannel) && string.IsNullOrEmpty(selectedChannel) && (pe.fromPlayer == selectedPMChannel || pe.fromPlayer == dmpSettings.playerName))
                {
                    chatScrollPos.y = float.PositiveInfinity;
                    selectTextBox   = chatLocked;
                }

                if (pe.fromPlayer != dmpSettings.playerName)
                {
                    privateMessages[pe.fromPlayer].Add(pe.fromPlayer + ": " + pe.message);

                    if (!display)
                    {
                        chatButtonHighlighted = true;
                        ScreenMessages.PostScreenMessage(pe.fromPlayer + " -> @" + pe.toPlayer + ": " + pe.message, 5f, ScreenMessageStyle.UPPER_LEFT);
                    }
                }
                else
                {
                    privateMessages[pe.toPlayer].Add(pe.fromPlayer + ": " + pe.message);
                }
            }
            //Handle console messages
            while (newConsoleMessages.Count > 0)
            {
                ConsoleEntry ce = newConsoleMessages.Dequeue();
                //Highlight if the channel isn't selected.
                if (selectedChannel != consoleIdentifier)
                {
                    if (!highlightChannel.Contains(consoleIdentifier))
                    {
                        highlightChannel.Add(consoleIdentifier);
                    }
                }

                //Move the bar to the bottom on a new message
                if (!string.IsNullOrEmpty(selectedChannel) && string.IsNullOrEmpty(selectedPMChannel) && consoleIdentifier == selectedChannel)
                {
                    chatScrollPos.y = float.PositiveInfinity;
                    selectTextBox   = chatLocked;
                }

                consoleMessages.Add(ce.message);
            }
            while (disconnectingPlayers.Count > 0)
            {
                string disconnectingPlayer = disconnectingPlayers.Dequeue();
                if (playerChannels.ContainsKey(disconnectingPlayer))
                {
                    playerChannels.Remove(disconnectingPlayer);
                }
                if (joinedPMChannels.Contains(disconnectingPlayer))
                {
                    joinedPMChannels.Remove(disconnectingPlayer);
                }
                if (highlightPM.Contains(disconnectingPlayer))
                {
                    highlightPM.Remove(disconnectingPlayer);
                }
                if (privateMessages.ContainsKey(disconnectingPlayer))
                {
                    privateMessages.Remove(disconnectingPlayer);
                }
            }
        }
Exemplo n.º 22
0
 public void StopContainment()
 {
     containmentField = false;
     containmentSound.Stop();
     ScreenMessages.PostScreenMessage("Containment field is off, EM will decay!", 7.0f);
 }
Exemplo n.º 23
0
        private void ApplyAvionicsSettings()
        {
            if (!float.TryParse(_sControllableMass, out float newControlMass) || newControlMass < 0)
            {
                ScreenMessages.PostScreenMessage("Invalid controllable mass value");
                _sControllableMass = $"{controllableMass:0.###}";
                return;
            }
            if (!float.TryParse(_sExtraVolume, out float extraVolumeLiters) || extraVolumeLiters < 0)
            {
                ScreenMessages.PostScreenMessage("Invalid Additional volume value");
                _sExtraVolume = "0";
                return;
            }
            if (!float.TryParse(_sECAmount, out float ecAmount) || ecAmount <= 0)
            {
                ScreenMessages.PostScreenMessage("EC amount needs to be larger than 0");
                _sECAmount = $"{_ecTank.maxAmount:F0}";
                return;
            }

            controllableMass = newControlMass;
            if (_seekVolumeMethod != null && _seekVolumeMethod.GetParameters().Length == 2)
            {
                // Store and sum together the volume of all resources other than EC on this part
                double otherFuelVolume = 0;
                var    otherTanks      = new List <KeyValuePair <FuelTank, double> >();
                foreach (FuelTank t in _tankList)
                {
                    if (t == _ecTank || t.maxAmount == 0)
                    {
                        continue;
                    }
                    otherTanks.Add(new KeyValuePair <FuelTank, double>(t, t.maxAmount));
                    otherFuelVolume += t.maxAmount / t.utilization;
                }

                SetProcPartVolumeLimit();
                ApplyCorrectProcTankVolume(extraVolumeLiters + (float)otherFuelVolume, ecAmount);

                // Restore all the pre-resize amounts in tanks
                foreach (KeyValuePair <FuelTank, double> kvp in otherTanks)
                {
                    FuelTank t = kvp.Key;
                    t.amount = t.maxAmount = kvp.Value;
                }
            }
            else
            {
                // ROTank probe cores do not support SeekVolume()
                _showROTankSizeWarning = ClampControllableMass();
                _shouldResetUIHeight   = true;
                MonoUtilities.RefreshContextWindows(part);
            }

            Log($"Applying RF tank amount values to {ecAmount}, currently has {_ecTank.amount}/{_ecTank.maxAmount}, volume {_rfPM.AvailableVolume}");
            _ecTank.maxAmount = ecAmount;
            _ecTank.amount    = ecAmount;
            _rfPM.PartResourcesChanged();
            _rfPM.CalculateMass();
            RefreshDisplays();
        }
Exemplo n.º 24
0
        /// <summary>
        /// Update rover.
        /// </summary>
        /// <param name="currentTime">Current time.</param>
        public void Update(double currentTime)
        {
            if (vessel.isActiveVessel)
            {
                status = "current";
                return;
            }

            if (!bvActive || vessel.loaded)
            {
                status = "idle";
                return;
            }

            Vector3d vesselPos = vessel.mainBody.position - vessel.GetWorldPos3D();
            Vector3d toKerbol  = vessel.mainBody.position - FlightGlobals.Bodies[0].position;
            double   angle     = Vector3d.Angle(vesselPos, toKerbol);

            // Speed penalties at twighlight and at night
            if (angle > 90 && isManned)
            {
                speedMultiplier = 0.25;
            }
            else if (angle > 85 && isManned)
            {
                speedMultiplier = 0.5;
            }
            else if (angle > 80 && isManned)
            {
                speedMultiplier = 0.75;
            }
            else
            {
                speedMultiplier = 1.0;
            }

            // No moving at night, or when there's not enougth solar light for solar powered rovers
            if (angle > 90 && solarPowered)
            {
                status   = "awaiting sunlight";
                lastTime = currentTime;
                BVModule.SetValue("lastTime", currentTime.ToString());
                vessel.protoVessel = new ProtoVessel(vesselConfigNode, HighLogic.CurrentGame);
                return;
            }

            double deltaT = currentTime - lastTime;

            double deltaS  = AverageSpeed * deltaT;
            double bearing = GeoUtils.InitialBearing(
                vessel.latitude,
                vessel.longitude,
                targetLatitude,
                targetLongitude
                );

            distanceTravelled += deltaS;
            if (distanceTravelled >= distanceToTarget)
            {
//				vessel.latitude = targetLatitude;
//				vessel.longitude = targetLongitude;
                if (!MoveSafe(targetLatitude, targetLongitude))
                {
                    distanceTravelled -= deltaS;
                }
                else
                {
                    distanceTravelled = distanceToTarget;

                    bvActive = false;
                    BVModule.SetValue("isActive", "False");
                    BVModule.SetValue("distanceTravelled", distanceToTarget.ToString());
                    BVModule.SetValue("pathEncoded", "");

//					BVModule.GetNode ("EVENTS").GetNode ("Activate").SetValue ("active", "True");
//					BVModule.GetNode ("EVENTS").GetNode ("Deactivate").SetValue ("active", "False");

                    if (BonVoyage.Instance.AutoDewarp)
                    {
                        if (TimeWarp.CurrentRate > 3)
                        {
                            TimeWarp.SetRate(3, true);
                        }
                        if (TimeWarp.CurrentRate > 0)
                        {
                            TimeWarp.SetRate(0, false);
                        }
                        ScreenMessages.PostScreenMessage(vessel.vesselName + " has arrived to destination at " + vessel.mainBody.name);
                    }
                    HoneyImHome();
                }
                status = "idle";
            }
            else
            {
                int    step      = Convert.ToInt32(Math.Floor(distanceTravelled / PathFinder.StepSize));
                double remainder = distanceTravelled % PathFinder.StepSize;

                if (step < path.Count - 1)
                {
                    bearing = GeoUtils.InitialBearing(
                        path[step].latitude,
                        path[step].longitude,
                        path[step + 1].latitude,
                        path[step + 1].longitude
                        );
                }
                else
                {
                    bearing = GeoUtils.InitialBearing(
                        path[step].latitude,
                        path[step].longitude,
                        targetLatitude,
                        targetLongitude
                        );
                }

                double[] newCoordinates = GeoUtils.GetLatitudeLongitude(
                    path[step].latitude,
                    path[step].longitude,
                    bearing,
                    remainder,
                    vessel.mainBody.Radius
                    );

//				vessel.latitude = newCoordinates[0];
//				vessel.longitude = newCoordinates[1];
                if (!MoveSafe(newCoordinates [0], newCoordinates [1]))
                {
                    distanceTravelled -= deltaS;
                    status             = "idle";
                }
                else
                {
                    status = "roving";
                }
            }
//			vessel.altitude = GeoUtils.TerrainHeightAt(vessel.latitude, vessel.longitude, vessel.mainBody);
            Save(currentTime);
        }
Exemplo n.º 25
0
            /// <summary>
            /// [HACK] Spawn a new body from the PSystem-Prefab
            /// </summary>
            public static void Instantiate(PSystemBody template, string name)
            {
                // Fix Templates
                if (template == null)
                {
                    ScreenMessages.PostScreenMessage("You need a valid Template!", 3f, ScreenMessageStyle.UPPER_CENTER);
                    return;
                }

                // Spawn Message
                ScreenMessages.PostScreenMessage("Created new Planet " + name + ", based on " + template.name + "!", 5f, ScreenMessageStyle.UPPER_CENTER);
                ScreenMessages.PostScreenMessage("This tool is meant to be used by modders, it can break mods!", 5f, ScreenMessageStyle.UPPER_CENTER);

                // Clone the Template
                GameObject  bodyObject = UnityEngine.Object.Instantiate(template.gameObject);
                PSystemBody body       = bodyObject.GetComponent <PSystemBody>();

                // Alter it's name and flight-Number
                body.name = name;
                body.celestialBody.bodyName           = name;
                body.celestialBody.transform.name     = name;
                body.celestialBody.bodyTransform.name = name;
                body.scaledVersion.name = name;
                if (body.pqsVersion != null)
                {
                    body.pqsVersion.name            = name;
                    body.pqsVersion.gameObject.name = name;
                    body.pqsVersion.transform.name  = name;
                    foreach (PQS p in body.pqsVersion.GetComponentsInChildren(typeof(PQS), true))
                    {
                        p.name = p.name.Replace(template.celestialBody.bodyName, name);
                    }
                }
                body.flightGlobalsIndex = PSystemManager.Instance.localBodies.Last().flightGlobalsIndex + 1;

                // Change it's Orbit
                body.orbitDriver.orbit                = Orbit.CreateRandomOrbitAround(PSystemManager.Instance.localBodies.First(), 4000000000, 60000000000);
                body.orbitDriver.referenceBody        = PSystemManager.Instance.localBodies.First();
                body.orbitDriver.orbit.referenceBody  = body.orbitDriver.referenceBody;
                body.orbitRenderer.lowerCamVsSmaRatio = template.orbitRenderer.lowerCamVsSmaRatio;
                body.orbitRenderer.upperCamVsSmaRatio = template.orbitRenderer.upperCamVsSmaRatio;

                // Clear it's childs
                body.children = new List <PSystemBody>();

                // Add it to the System-Prefab
                body.transform.parent = PSystemManager.Instance.systemPrefab.transform;
                PSystemManager.Instance.systemPrefab.rootBody.children.Add(body);

                // Hack^6 - Hack the PSystemManager to spawn this thing
                MethodInfo spawnBody = typeof(PSystemManager).GetMethod("SpawnBody", BindingFlags.NonPublic | BindingFlags.Instance);

                spawnBody.Invoke(PSystemManager.Instance, new object[] { PSystemManager.Instance.localBodies.First(), body });
                CelestialBody cBody = PSystemManager.Instance.localBodies.Last();

                // Add the body to FlightGlobals.Bodies
                FlightGlobals.fetch.bodies.Add(cBody);

                // Start the CelestialBody
                typeof(CelestialBody).GetMethod("Start", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(cBody, null);

                // Start the OrbitDriver
                if (cBody.orbitDriver != null)
                {
                    typeof(OrbitDriver).GetMethod("Start", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(cBody.orbitDriver, null);
                }

                // Fix and start the OrbitRenderer
                if (Resources.FindObjectsOfTypeAll <OrbitRenderer>().Count(r => r.name == cBody.name) == 1)
                {
                    OrbitRenderer renderer = Resources.FindObjectsOfTypeAll <OrbitRenderer>().First(r => r.name == cBody.name);
                    renderer.driver        = cBody.orbitDriver;
                    renderer.celestialBody = cBody;
                    typeof(OrbitRenderer).GetMethod("Start", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(renderer, null);
                }

                // Force the start of the PQS-Spheres
                foreach (PQS p in cBody.GetComponentsInChildren <PQS>(true))
                {
                    p.ForceStart();
                }

                // Fix the ScaledVersion
                if (cBody.scaledBody.GetComponents <ScaledSpaceFader>().Length == 1)
                {
                    cBody.scaledBody.GetComponent <ScaledSpaceFader>().celestialBody = cBody;
                }
                if (cBody.scaledBody.GetComponents <AtmosphereFromGround>().Length == 1)
                {
                    cBody.scaledBody.GetComponent <AtmosphereFromGround>().planet = cBody;
                }
            }
Exemplo n.º 26
0
        // Окно(главное) "Basic Window"
        void DoWindow0(int windowID)
        {
            GUILayout.BeginVertical(GUILayout.ExpandHeight(true));

            GUILayout.BeginHorizontal();

            GUILayout.FlexibleSpace();

            if (GUILayout.Button("Save"))
            {
                save_cfg();
                ScreenMessages.PostScreenMessage("Info saved", .5f, ScreenMessageStyle.LOWER_CENTER);
            }

            if (GUILayout.Button("Load"))
            {
                load_cfg();
                ScreenMessages.PostScreenMessage("Info loaded", .5f, ScreenMessageStyle.LOWER_CENTER);
            }

            if (GUILayout.Button((_isPause) ? "Continue": "Pause"))
            {
                ScreenMessages.PostScreenMessage((_isPause) ? "Info continued" : "Info paused",
                                                 .5f, ScreenMessageStyle.LOWER_CENTER);

                _isPause = (_isPause) ? false : true;
            }

            if (GUILayout.Button("Export texture"))
            {
                Export();
                ScreenMessages.PostScreenMessage("Export texture begin", .5f, ScreenMessageStyle.LOWER_CENTER);
            }

            GUILayout.FlexibleSpace();

            GUILayout.EndHorizontal();

            GUILayout.Space(10);

            if (!_isPause)
            {
                vi.SetInfo(FlightGlobals.ActiveVessel);
            }

            int la = (int)GUI.skin.label.alignment;

            GUI.skin.label.alignment = TextAnchor.MiddleRight;

            using (var hs = new GUILayout.HorizontalScope("Name vessel"))
            {
                GUILayout.Label("Name vessel:", GUILayout.Width(200));
                GUILayout.TextArea(vi.name, GUILayout.Width(200));
            }

            using (var hs = new GUILayout.HorizontalScope("Altitude"))
            {
                GUILayout.Label("Altitude:", GUILayout.Width(200));
                GUILayout.TextArea(string.Format("{0,-10:f2}", vi.Altitude), GUILayout.Width(200));
            }

            using (var hs = new GUILayout.HorizontalScope("Gee force"))
            {
                GUILayout.Label("Gee force:", GUILayout.Width(200));
                GUILayout.TextArea(string.Format("{0,-10:f2}", vi.gforce), GUILayout.Width(200));
            }

            using (var hs = new GUILayout.HorizontalScope("Surface speed"))
            {
                GUILayout.Label("Surface speed:", GUILayout.Width(200));
                GUILayout.TextArea(string.Format("{0,-10:f2}", vi.surf_speed), GUILayout.Width(200));
            }

            using (var hs = new GUILayout.HorizontalScope("Vertical speed"))
            {
                GUILayout.Label("Vertical speed:", GUILayout.Width(200));
                GUILayout.TextArea(string.Format("{0,-10:f2}", vi.vert_speed), GUILayout.Width(200));
            }

            GUI.skin.label.alignment = (TextAnchor)la;

            GUILayout.EndVertical();

            GUI.DragWindow(new Rect(0, 0, 10000, 20));
        }
Exemplo n.º 27
0
            /// <summary>
            /// Generate the scaled space Textures using PQS in a Coroutine
            /// </summary>
            public static IEnumerator GeneratePQSMaps(CelestialBody body, Boolean transparentMaps, ExportMode mode)
            {
                // Get time
                DateTime now = DateTime.Now;

                // Get PQS
                PQS pqs = body.pqsController;

                pqs.isBuildingMaps = true;
                pqs.isFakeBuild    = true;

                // Get the mods
                Action <PQS.VertexBuildData> modOnVertexBuildHeight = (Action <PQS.VertexBuildData>)Delegate.CreateDelegate(
                    typeof(Action <PQS.VertexBuildData>),
                    pqs,
                    typeof(PQS).GetMethod("Mod_OnVertexBuildHeight", BindingFlags.Instance | BindingFlags.NonPublic));
                Action <PQS.VertexBuildData> modOnVertexBuild = (Action <PQS.VertexBuildData>)Delegate.CreateDelegate(
                    typeof(Action <PQS.VertexBuildData>),
                    pqs,
                    typeof(PQS).GetMethod("Mod_OnVertexBuild", BindingFlags.Instance | BindingFlags.NonPublic));

                PQSMod[] mods = pqs.GetComponentsInChildren <PQSMod>().Where(m => m.sphere == pqs && m.modEnabled).ToArray();

                // Create the Textures
                Texture2D colorMap  = new Texture2D(pqs.mapFilesize, pqs.mapFilesize / 2, TextureFormat.ARGB32, true);
                Texture2D heightMap = new Texture2D(pqs.mapFilesize, pqs.mapFilesize / 2, TextureFormat.RGB24, true);

                // Arrays
                Color[] colorMapValues  = new Color[pqs.mapFilesize * (pqs.mapFilesize / 2)];
                Color[] heightMapValues = new Color[pqs.mapFilesize * (pqs.mapFilesize / 2)];

                // Stuff
                ScreenMessage message = ScreenMessages.PostScreenMessage("Generating Planet-Maps", Single.MaxValue, ScreenMessageStyle.UPPER_CENTER);

                // Wait a some time
                yield return(null);

                // Loop through the pixels
                for (int y = 0; y < (pqs.mapFilesize / 2); y++)
                {
                    for (int x = 0; x < pqs.mapFilesize; x++)
                    {
                        // Update Message
                        Double percent = ((double)((y * pqs.mapFilesize) + x) / ((pqs.mapFilesize / 2) * pqs.mapFilesize)) * 100;
                        while (CanvasUpdateRegistry.IsRebuildingLayout())
                        {
                            Thread.Sleep(10);
                        }
                        message.textInstance.text.text = "Generating Planet-Maps: " + percent.ToString("0.00") + "%";

                        // Create a VertexBuildData
                        PQS.VertexBuildData data = new PQS.VertexBuildData
                        {
                            directionFromCenter = (QuaternionD.AngleAxis((360d / pqs.mapFilesize) * x, Vector3d.up) * QuaternionD.AngleAxis(90d - (180d / (pqs.mapFilesize / 2)) * y, Vector3d.right)) * Vector3d.forward,
                            vertHeight          = pqs.radius
                        };

                        // Build from the Mods
                        double height = Double.MinValue;
                        if (mode != ExportMode.COLOR)
                        {
                            modOnVertexBuildHeight(data);

                            // Adjust the height
                            height = (data.vertHeight - pqs.radius) * (1d / pqs.mapMaxHeight);
                            if (height < 0)
                            {
                                height = 0;
                            }
                            else if (height > 1)
                            {
                                height = 1;
                            }

                            // Set the Pixels
                            heightMapValues[(y * pqs.mapFilesize) + x] = new Color((Single)height, (Single)height, (Single)height);
                        }
                        if (mode == ExportMode.COLOR || mode == ExportMode.ALL)
                        {
                            modOnVertexBuild(data);

                            // Adjust the Color
                            Color color = data.vertColor;
                            if (!pqs.mapOcean)
                            {
                                color.a = 1f;
                            }
                            else if (height > pqs.mapOceanHeight)
                            {
                                color.a = transparentMaps ? 0f : 1f;
                            }
                            else if (mode == ExportMode.COLOR)
                            {
                                color.a = 1f;
                            }
                            else
                            {
                                color = pqs.mapOceanColor.A(1f);
                            }

                            // Set the Pixels
                            colorMapValues[(y * pqs.mapFilesize) + x] = color;
                        }
                    }
                    yield return(null);
                }

                // Apply the maps
                if (mode == ExportMode.COLOR || mode == ExportMode.ALL)
                {
                    colorMap.SetPixels(colorMapValues);
                    colorMap.Apply();
                }
                if (mode != ExportMode.COLOR)
                {
                    heightMap.SetPixels(heightMapValues);
                }
                yield return(null);

                // Close the Renderer
                pqs.isBuildingMaps = false;
                pqs.isFakeBuild    = false;

                // Serialize them to disk
                string path = KSPUtil.ApplicationRootPath + "/GameData/KittopiaTech/Textures/" + body.name + "/";

                Directory.CreateDirectory(path);
                if (mode == ExportMode.COLOR || mode == ExportMode.ALL)
                {
                    File.WriteAllBytes(path + body.name + "_Color.png", colorMap.EncodeToPNG());

                    // Apply them to the ScaledVersion
                    body.scaledBody.GetComponent <MeshRenderer>().material.SetTexture("_MainTex", colorMap);
                }
                if (mode != ExportMode.COLOR)
                {
                    File.WriteAllBytes(path + body.name + "_Height.png", heightMap.EncodeToPNG());
                }
                if (mode == ExportMode.HEIGHTNORMAL || mode == ExportMode.ALL)
                {
                    // Bump to Normal Map
                    Texture2D normalMap = Utility.BumpToNormalMap(heightMap, UIController.NormalStrength);
                    File.WriteAllBytes(path + body.name + "_Normal.png", normalMap.EncodeToPNG());

                    // Apply them to the ScaledVersion
                    body.scaledBody.GetComponent <MeshRenderer>().material.SetTexture("_BumpMap", normalMap);
                }
                yield return(null);

                // Declare that we're done
                ScreenMessages.RemoveMessage(message);
                ScreenMessages.PostScreenMessage("Operation completed in: " + (DateTime.Now - now).TotalMilliseconds + " ms", 2f, ScreenMessageStyle.UPPER_CENTER);
            }
Exemplo n.º 28
0
        private static void DrawBuildPlansWindow(int id)
        {
            int butW = 20;

            GUILayout.BeginVertical();
            if (HighLogic.LoadedSceneIsEditor)
            {
                if (EditorLogic.fetch.ship != null && EditorLogic.fetch.ship.Parts != null && EditorLogic.fetch.ship.Parts.Count > 0)
                {
                    if (EditorLogic.fetch.ship.shipName == "Untitled Space Craft" || EditorLogic.fetch.ship.shipName == "")
                    {
                        if (GUILayout.Button("Cannot Add a Plan Without a Valid Name", GUILayout.Height(2 * 22)))
                        {
                            if (EditorLogic.fetch.ship.shipName == "Untitled Space Craft")
                            {
                                var message = new ScreenMessage("[KCT] Vessel must have a name other than 'Untitled Space Craft'.", 4f, ScreenMessageStyle.UPPER_CENTER);
                                ScreenMessages.PostScreenMessage(message);
                            }
                            else
                            {
                                var message = new ScreenMessage("[KCT] Vessel must have a name", 4f, ScreenMessageStyle.UPPER_CENTER);
                                ScreenMessages.PostScreenMessage(message);
                            }
                        }
                    }
                    else
                    {
                        GUILayout.BeginHorizontal();
                        if (GUILayout.Button("Add To Building Plans", GUILayout.Height(2 * 22)))
                        {
                            AddVesselToPlansList();
                        }
                        GUILayout.EndHorizontal();
                        GUILayout.BeginHorizontal();
                        if (GUILayout.Button("Build", GUILayout.Height(2 * 22)))
                        {
                            Utilities.AddVesselToBuildList();
                            Utilities.RecalculateEditorBuildTime(EditorLogic.fetch.ship);
                        }
                        GUILayout.EndHorizontal();
                    }
                }
                else
                {
                    GUILayout.Button("No vessel available", GUILayout.Height(2 * 22));
                }
            }
            GUILayout.Space(10);
            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            GUILayout.Label("Available Building Plans");
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();
            GUILayout.BeginHorizontal();

            bool isVABSelectedNew = GUILayout.Toggle(_isVABSelectedInPlans, "VAB", GUI.skin.button);
            bool isSPHSelectedNew = GUILayout.Toggle(_isSPHSelectedInPlans, "SPH", GUI.skin.button);

            if (isVABSelectedNew != _isVABSelectedInPlans)
            {
                _isVABSelectedInPlans = isVABSelectedNew;
                _isSPHSelectedInPlans = false;
                SelectList("VAB");
            }
            else if (isSPHSelectedNew != _isSPHSelectedInPlans)
            {
                _isSPHSelectedInPlans = isSPHSelectedNew;
                _isVABSelectedInPlans = false;
                SelectList("SPH");
            }

            GUILayout.EndHorizontal();
            {
                if (isVABSelectedNew)
                {
                    _plansList = KCTGameStates.ActiveKSC.VABPlans;
                }
                else if (isSPHSelectedNew)
                {
                    _plansList = KCTGameStates.ActiveKSC.SPHPlans;
                }
                if (_isVABSelectedInPlans || _isSPHSelectedInPlans)
                {
                    GUILayout.BeginHorizontal();
                    GUILayout.Label("Name:");
                    GUILayout.EndHorizontal();
                    _scrollPos = GUILayout.BeginScrollView(_scrollPos, GUILayout.Height(250));

                    if (_plansList == null || _plansList.Count == 0)
                    {
                        GUILayout.Label("No vessels in plans.");
                    }
                    for (int i = 0; i < _plansList.Count; i++)
                    {
                        BuildListVessel b = _plansList.Values[i];
                        if (!b.AllPartsValid)
                        {
                            continue;
                        }
                        GUILayout.BeginHorizontal();
                        {
                            if (GUILayout.Button("X", _redButton, GUILayout.Width(butW)))
                            {
                                _planToDelete = i;
                                InputLockManager.SetControlLock(ControlTypes.EDITOR_SOFT_LOCK, "KCTPopupLock");
                                _selectedVesselId = b.Id;
                                DialogGUIBase[] options = new DialogGUIBase[2];
                                options[0] = new DialogGUIButton("Yes", RemoveVesselFromPlans);
                                options[1] = new DialogGUIButton("No", RemoveInputLocks);
                                MultiOptionDialog diag = new MultiOptionDialog("scrapVesselPopup", "Are you sure you want to remove this vessel from the plans?", "Delete plan", null, options: options);
                                PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), diag, false, HighLogic.UISkin);
                            }

                            if (GUILayout.Button(b.ShipName))
                            {
                                Utilities.AddVesselToBuildList(b.CreateCopy(true));
                            }
                        }

                        GUILayout.EndHorizontal();
                    }
                    GUILayout.EndScrollView();
                }
                GUILayout.FlexibleSpace();
                if (GUILayout.Button("Close"))
                {
                    GUIStates.ShowBuildPlansWindow = false;
                }
            }

            GUILayout.EndVertical();
            GUI.DragWindow();
        }
Exemplo n.º 29
0
        // Called by Unity once to initialize the class, just before Update is called.
        public void Start( )
        {
            _logger.Trace("Start");

            if (_addonInitialized == true)
            {
                // For some reason the addon can be instantiated several times by the KSP addon loader (generally when going to/from the VAB),
                // even though we set onlyOnce to true in the KSPAddon attribute.
                HammerMusicMute( );                 // Ensure we enforce music volume anyway
                return;
            }
            _addonInitialized = true;
            _active           = false;



            // Config
            Config = new Config( );
            Config.Load( );



            // Music Muting
            if (Config.MusicStartsMuted)
            {
                Muted = true;
                ScreenMessages.PostScreenMessage("[x] Science! - Music Mute");
            }

            GameEvents.onGameSceneSwitchRequested.Add(this.onGameSceneSwitchRequested);
            GameEvents.onLevelWasLoaded.Add(this.onLevelWasLoaded);



//			_logger.Trace( "Making DMagic Factory" );
            DMagic = new DMagicFactory( );
//			_logger.Trace( "Made DMagic Factory" );



//			_logger.Trace( "Making ScienceContext" );
            Science = new ScienceContext(this);
//			_logger.Trace( "Made ScienceContext" );



            // Start event handlers
            ScienceEventHandler = new xScienceEventHandler(this);



            // Settings window
            _settingsWindow = new SettingsWindow(this);
            Config.UseBlizzysToolbarChanged   += Settings_UseBlizzysToolbarChanged;
            Config.RighClickMutesMusicChanged += Settings_RighClickMutesMusicChanged;



            // Help window
            _helpWindow = new HelpWindow(this);



            // Status window
            _alertNoise                 = gameObject.AddComponent <Noise>( );
            _statusWindow               = new StatusWindow(this);
            _statusWindow.NoiseEvent   += OnPlayNoise;
            _statusWindow.WindowClosed += OnStatusWindowClosed;
            _statusWindow.OnCloseEvent += OnStatusWindowClosed;
            _statusWindow.OnOpenEvent  += OnStatusWindowOpened;



            // Checklist window
            _checklistWindow = new ScienceWindow(this, _settingsWindow, _helpWindow);
            _checklistWindow.OnCloseEvent += OnChecklistWindowClosed;
            _checklistWindow.OnOpenEvent  += OnChecklistWindowOpened;



            // ShipState Window
            _shipStateWindow = new ShipStateWindow(this);



            // Save and load checklist window config when the game scene is changed
            // We are only visible in some scenes
            GameEvents.onGameSceneSwitchRequested.Add(new EventData <GameEvents.FromToAction <GameScenes, GameScenes> > .OnEvent(this.OnGameSceneSwitch));



            // Callbacks for buttons - we init when the "Launcher" toolbar is ready
            GameEvents.onGUIApplicationLauncherReady.Add(Load);
            GameEvents.onGUIApplicationLauncherDestroyed.Add(Unload);

            // Callbacks for F2
            GameEvents.onHideUI.Add(OnHideUI);
            GameEvents.onShowUI.Add(OnShowUI);


            DontDestroyOnLoad(this);


            _logger.Trace("Done Start");
        }
        // the main collecting function
        private void CollectRegolith(double deltaTimeInSeconds, bool offlineCollecting)
        {
            //Debug.Log("Inside Collect function.");
            //dConcentrationRegolith = CalculateRegolithConcentration(FlightGlobals.currentMainBody.position, localStar.transform.position, vessel.altitude);
            dConcentrationRegolith = GetFinalConcentration();

            string strRegolithResourceName = InterstellarResourcesConfiguration.Instance.Regolith;
            double dPowerRequirementsMW    = PluginHelper.PowerConsumptionMultiplier * mwRequirements; // change the mwRequirements number in part config to change the power consumption

            // gets density of the regolith resource
            dRegolithDensity = (double)(decimal)PartResourceLibrary.Instance.GetDefinition(strRegolithResourceName).density;

            var partsThatContainRegolith = part.GetConnectedResources(strRegolithResourceName);

            dRegolithSpareCapacity = partsThatContainRegolith.Sum(r => r.maxAmount - r.amount);

            if (offlineCollecting)
            {
                dConcentrationRegolith = dLastRegolithConcentration; // if resolving offline collection, pass the saved value, because OnStart doesn't resolve the above function CalculateRegolithConcentration correctly
            }



            if (dConcentrationRegolith > 0 && (dRegolithSpareCapacity > 0))
            {
                // calculate available power
                double dPowerReceivedMW           = Math.Max(consumeFNResource(dPowerRequirementsMW * TimeWarp.fixedDeltaTime, ResourceManager.FNRESOURCE_MEGAJOULES, TimeWarp.fixedDeltaTime), 0);
                double dNormalisedRevievedPowerMW = dPowerReceivedMW / TimeWarp.fixedDeltaTime;

                // if power requirement sufficiently low, retreive power from KW source
                if (dPowerRequirementsMW < 2 && dNormalisedRevievedPowerMW <= dPowerRequirementsMW)
                {
                    double dRequiredKW = (dPowerRequirementsMW - dNormalisedRevievedPowerMW) * 1000;
                    double dReceivedKW = part.RequestResource(ResourceManager.STOCK_RESOURCE_ELECTRICCHARGE, dRequiredKW * TimeWarp.fixedDeltaTime);
                    dPowerReceivedMW += (dReceivedKW / 1000);
                }

                dLastPowerPercentage = offlineCollecting ? dLastPowerPercentage : (float)(dPowerReceivedMW / dPowerRequirementsMW / TimeWarp.fixedDeltaTime);

                // show in GUI
                strCollectingStatus = "Collecting regolith";
            }

            else
            {
                dLastPowerPercentage = 0;
                dPowerRequirementsMW = 0;
            }

            // set the GUI string to state the number of KWs received if the MW requirements were lower than 2, otherwise in MW
            strReceivedPower = dPowerRequirementsMW < 2
                ? (dLastPowerPercentage * dPowerRequirementsMW * 1000).ToString("0.0") + " KW / " + (dPowerRequirementsMW * 1000).ToString("0.0") + " KW"
                : (dLastPowerPercentage * dPowerRequirementsMW).ToString("0.0") + " MW / " + dPowerRequirementsMW.ToString("0.0") + " MW";

            /** The first important bit.
             * This determines how much solar wind will be collected. Can be tweaked in part configs by changing the collector's effectiveness.
             * */

            resourceProduction = dConcentrationRegolith * drillSize * dRegolithDensity * effectiveness * dLastPowerPercentage;

            double dResourceChange = resourceProduction * deltaTimeInSeconds;

            // if the vessel has been out of focus, print out the collected amount for the player
            if (offlineCollecting)
            {
                string strNumberFormat = dResourceChange > 100 ? "0" : "0.00";
                // let the player know that offline collecting worked
                ScreenMessages.PostScreenMessage("The Regolith Drill collected " + dResourceChange.ToString(strNumberFormat) + " units of " + strRegolithResourceName, 10.0f, ScreenMessageStyle.LOWER_CENTER);
            }

            // this is the second important bit - do the actual change of the resource amount in the vessel
            dResourceFlow = part.RequestResource(strRegolithResourceName, -dResourceChange);

            dResourceFlow = -dResourceFlow / TimeWarp.fixedDeltaTime;

            /* This takes care of wasteheat production (but takes into account if waste heat mechanics weren't disabled).
             * It's affected by two properties of the drill part - its power requirements and waste heat production percentage.
             * More power hungry drills will produce more heat. More effective drills will produce less heat. More effective power hungry drills should produce
             * less heat than less effective power hungry drills. This should allow us to bring some variety into parts, if we want to.
             */

            if (!CheatOptions.IgnoreMaxTemperature)                                                         // is this player not using no-heat cheat mode?
            {
                dTotalWasteHeatProduction = dPowerRequirementsMW * wasteHeatModifier;                       // calculate amount of heat to be produced
                supplyFNResourcePerSecond(dTotalWasteHeatProduction, ResourceManager.FNRESOURCE_WASTEHEAT); // push the heat onto them
            }
        }
Exemplo n.º 31
0
        private void Start()
        {
            FlightCamera[] cams = FlightCamera.FindObjectsOfType(typeof(FlightCamera)) as FlightCamera[];
            cam = cams[0];

            warpText = FindObjectOfType<ScreenMessages>();
            warpTextColor = warpText.textStyles[1].normal.textColor;

            //EVENTS
            GameEvents.onFlightReady.Add(this.onFlightReady);
            GameEvents.onGameSceneLoadRequested.Add(this.onGameSceneLoadRequested);
            GameEvents.onGamePause.Add(this.onGamePause);
            GameEvents.onGameUnpause.Add(this.onGameUnpause);
            GameEvents.onHideUI.Add(this.onHideUI);
            GameEvents.onShowUI.Add(this.onShowUI);
            GameEvents.onLevelWasLoaded.Add(this.onLevelWasLoaded);
            GameEvents.onTimeWarpRateChanged.Add(this.onTimeWarpRateChanged);
            GameEvents.onPartDestroyed.Add(this.onPartDestroyed);
            GameEvents.onVesselDestroy.Add(this.onVesselDestroy);
            GameEvents.onVesselGoOffRails.Add(this.onVesselGoOffRails);
        }