public ProtoAntenna(Vessel v, ProtoPartSnapshot p, ProtoPartModuleSnapshot ppms)
        {
            ConfigNode n = new ConfigNode();
            ppms.Save(n);
            Name = p.partInfo.title;
            try {
                mTarget = new Guid(n.GetValue("RTAntennaTarget"));
                DishRange = Single.Parse(n.GetValue("RTDishRange"));
                DishFactor = Double.Parse(n.GetValue("RTDishFactor"));
                OmniRange = Single.Parse(n.GetValue("RTOmniRange"));
            }
            catch (ArgumentException) {
                mTarget = Guid.Empty;
                DishRange = 0.0f;
                DishFactor = 1.0f;
                OmniRange = 0.0f;
                RTUtil.Log("ProtoAntenna parsing error. Default values assumed.");
            }

            mProtoPart = p;
            mProtoModule = ppms;
            Vessel = v;
            RTUtil.Log("ProtoAntenna: DishRange: {0}, OmniRange: {1}, Name: {2}, DishTarget: {3})",
                DishRange, OmniRange, Vessel.vesselName, DishTarget);
        }
示例#2
0
        public SatSettingNode(ProtoPartModuleSnapshot s, Vessel v, ProtoPartSnapshot sn)
        {
            this.protoPartModule = s;
            this.vessel = v;
            this.snapshot = sn;
            isLoaded = false;

            ConfigNode n = new ConfigNode();
            protoPartModule.Save(n);

            if (n.HasValue("pointedAt"))
                this.pointedAt = new Target(n.GetValue("pointedAt"));
            else
                this.pointedAt = new Target();

            if (n.HasValue("dishRange"))
                this.dishRange = float.Parse(n.GetValue("dishRange"));
            else
                this.dishRange = 0;

            if (n.HasValue("antennaName"))
                this.antennaName = n.GetValue("antennaName");

            for (int i = 0; i < RTGlobals.targets.Count; i++)
            {
                if (pointedAt.Equals(RTGlobals.targets[i])) { selectedTarget = i; break; }
            }
        }
        public ProtoSignalProcessor(ProtoPartModuleSnapshot ppms, Vessel v)
        {
            Vessel = v;
            Powered = ppms.GetBool("IsRTPowered");

            // get the crew count from the vessel
            var crewcount = v.GetVesselCrew().Count;

            // when the crew count is equal to 0 then look into the protoVessel
            if (crewcount == 0 && v.protoVessel.GetVesselCrew() != null)
                crewcount = v.protoVessel.GetVesselCrew().Count;

            RTLog.Notify("ProtoSignalProcessor crew count of {0} is {1}", v.vesselName, crewcount);

            int ppmsMinCrew;
            //try to get the RTCommandMinCrew value in the ProtoPartModuleSnapshot
            if (ppms.GetInt("RTCommandMinCrew", out ppmsMinCrew))
            {
                IsCommandStation = Powered && v.HasCommandStation() && crewcount >= ppmsMinCrew;
                RTLog.Notify("ProtoSignalProcessor(Powered: {0}, HasCommandStation: {1}, Crew: {2}/{3})",
                    Powered, v.HasCommandStation(), crewcount, ppmsMinCrew);
            }
            else
            {
                // there was no RTCommandMinCrew member in the ProtoPartModuleSnapshot
                IsCommandStation = false;

                RTLog.Notify("ProtoSignalProcessor(Powered: {0}, HasCommandStation: {1}, Crew: {2})",
                    Powered, v.HasCommandStation(), crewcount);
            }
        }
 public ProtoSignalProcessor(ProtoPartModuleSnapshot ppms, Vessel v)
 {
     mVessel = v;
     Powered = ppms.GetBool("IsRTPowered");
     IsCommandStation = Powered && v.HasCommandStation() && v.GetVesselCrew().Count >= 6;
     RTLog.Notify("ProtoSignalProcessor(Powered: {0}, HasCommandStation: {1}, Crew: {2})", Powered, v.HasCommandStation(), v.GetVesselCrew().Count);
 }
示例#5
0
        public ProtoAntenna(Vessel v, ProtoPartSnapshot p, ProtoPartModuleSnapshot ppms)
        {
            ConfigNode n = new ConfigNode();
            ppms.Save(n);
            Name = p.partInfo.title;
            Consumption = 0;
            Guid = v.id;
            mProtoPart = p;
            mProtoModule = ppms;
            try
            {
                mDishTarget = new Guid(n.GetValue("RTAntennaTarget"));
            }
            catch (ArgumentException)
            {
                mDishTarget = Guid.Empty;
            }
            double temp_double;
            float temp_float;
            bool temp_bool;
            Dish = Single.TryParse(n.GetValue("RTDishRange"), out temp_float) ? temp_float : 0.0f;
            CosAngle = Double.TryParse(n.GetValue("RTDishCosAngle"), out temp_double) ? temp_double : 0.0;
            Omni = Single.TryParse(n.GetValue("RTOmniRange"), out temp_float) ? temp_float : 0.0f;
            Powered = Boolean.TryParse(n.GetValue("IsRTPowered"), out temp_bool) ? temp_bool : false;
            Activated = Boolean.TryParse(n.GetValue("IsRTActive"), out temp_bool) ? temp_bool : false;

            RTLog.Notify(ToString());
        }
        public ProtoSignalProcessor(ProtoPartModuleSnapshot ppms, Vessel v)
        {
            mVessel = v;
            Powered = ppms.GetBool("IsRTPowered");

            // get the crew count from the vessel
            int crewcount = v.GetVesselCrew().Count;
            // when the crewcount is eq 0 than look into the protoVessel
            if (crewcount == 0 && v.protoVessel.GetVesselCrew() != null)
                crewcount = v.protoVessel.GetVesselCrew().Count;

            RTLog.Notify("ProtoSignalProcessor crew count of {0} is {1}", v.vesselName, crewcount);

            try {
                IsCommandStation = Powered && v.HasCommandStation() && crewcount >= ppms.GetInt("RTCommandMinCrew");
                RTLog.Notify("ProtoSignalProcessor(Powered: {0}, HasCommandStation: {1}, Crew: {2}/{3})",
                    Powered, v.HasCommandStation(), crewcount, ppms.GetInt("RTCommandMinCrew"));
            } catch (ArgumentException argexeception) {
                // I'm assuming this would get thrown by ppms.GetInt()... do the other functions have an exception spec?
                IsCommandStation = false;
                RTLog.Notify("ProtoSignalProcessor(Powered: {0}, HasCommandStation: {1}, Crew: {2})",
                    Powered, v.HasCommandStation(), crewcount);
                RTLog.Notify("ProtoSignalProcessor ", argexeception);
            }
        }
 public ProtoSignalProcessor(ProtoPartModuleSnapshot ppms, Vessel v)
 {
     Vessel = v;
     Powered = ppms.GetBool("IsRTPowered");
     CommandStation = Powered && v.HasCommandStation() && v.GetVesselCrew().Count >= 6;
     RTUtil.Log("ProtoSignalProcessor: Powered: {0}, CommandStation: {1}, Crew: {2}",
         Powered, v.HasCommandStation(), v.GetVesselCrew().Count);
 }
 private ConfigNode findExperimentModulInPC(ProtoPartModuleSnapshot kasModule, AvailablePart experiment)
 {
     ConfigNode partConf = kasModule.moduleValues;
     foreach (ConfigNode contentPart in partConf.GetNodes(CONTENT_PART))
     {
         NE_Helper.log("ContentPart: " + contentPart.GetValue("name"));
         if (contentPart.GetValue("name") == experiment.name)
         {
             foreach (ConfigNode module in contentPart.GetNodes("MODULE"))
             {
                 if (module.GetValue("name") == experimentModulname[experiment.name])
                     return module;
             }
         }
     }
     return null;
 }
示例#9
0
        public static bool HasResourceGenerationData(
            PartModule m,
            ProtoPartModuleSnapshot s,
            Dictionary<String, List<ResourceModuleHandler>> resourceData,
            HashSet<String> interestingResources
        )
        {
            ModuleCommand c = (ModuleCommand)m;

            // TODO: Check for deactivated command modules

            foreach (ModuleResource mr in c.inputResources)
            {
                if (interestingResources.Contains(mr.name)) { return true; }
            }

            return false;
        }
示例#10
0
        public static bool HasResourceGenerationData(
            PartModule m,
            ProtoPartModuleSnapshot s,
            Dictionary<String, List<ResourceModuleHandler>> resourceData,
            HashSet<String> interestingResources
        )
        {
            bool active = false;
            Boolean.TryParse(s.moduleValues.GetValue("generatorIsActive"), out active);
            if (active)
            {
                ModuleGenerator g = (ModuleGenerator)m;
                if (g.inputList.Count <= 0)
                {
                    foreach (ModuleResource gr in g.outputList)
                    {
                        if (interestingResources.Contains(gr.name)) { return true; }
                    }
                }
            }

            return false;
        }
示例#11
0
        public static void ProtoBreak(Vessel v, ProtoPartSnapshot p, ProtoPartModuleSnapshot m)
        {
            // get reliability module prefab
            string      type        = Lib.Proto.GetString(m, "type", string.Empty);
            Reliability reliability = p.partPrefab.FindModulesImplementing <Reliability>().Find(k => k.type == type);

            if (reliability == null)
            {
                return;
            }

            // if manned, or if safemode didn't trigger
            if (Cache.VesselInfo(v).crew_capacity > 0 || Lib.RandomDouble() > Settings.SafeModeChance)
            {
                // flag as broken
                Lib.Proto.Set(m, "broken", true);

                // determine if this is a critical failure
                bool critical = Lib.RandomDouble() < Settings.CriticalChance;
                Lib.Proto.Set(m, "critical", critical);

                // for each associated module
                foreach (var proto_module in p.modules.FindAll(k => k.moduleName == reliability.type))
                {
                    // disable the module
                    Lib.Proto.Set(proto_module, "isEnabled", false);
                }

                // type-specific hacks
                switch (reliability.type)
                {
                case "ProcessController":
                    foreach (ProcessController pc in p.partPrefab.FindModulesImplementing <ProcessController>())
                    {
                        ProtoPartResourceSnapshot res = p.resources.Find(k => k.resourceName == pc.resource);
                        if (res != null)
                        {
                            res.flowState = false;
                        }
                    }
                    break;
                }

                // show message
                Broken_msg(v, reliability.title, critical);
            }
            // safe mode
            else
            {
                // reset age
                Lib.Proto.Set(m, "last", 0.0);
                Lib.Proto.Set(m, "next", 0.0);

                // notify user
                Safemode_msg(v, reliability.title);
            }

            // in any case, incentive redundancy
            if (Settings.IncentiveRedundancy)
            {
                Incentive_redundancy(v, reliability.redundancy);
            }
        }
示例#12
0
 public static bool IsCommandStation(this ProtoPartModuleSnapshot ppms)
 {
     return(ppms.GetBool("IsRTCommandStation"));
 }
        static bool Prefix(ref ProtoVessel pv, ref bool quick)
        {
            if (pv == null)
            {
                return(true);
            }

            // get a hard drive. any hard drive will do, no need to find a specific one.
            ProtoPartModuleSnapshot protoHardDrive = null;

            foreach (var p in pv.protoPartSnapshots)
            {
                foreach (var pm in Lib.FindModules(p, "HardDrive"))
                {
                    protoHardDrive = pm;
                    break;
                }
                if (protoHardDrive != null)
                {
                    break;
                }
            }

            if (protoHardDrive == null)
            {
                return(true);                // no drive on the vessel - nothing to do.
            }
            double scienceToCredit = 0.0;

            List <DialogGUIBase> labels = new List <DialogGUIBase>();

            foreach (Drive drive in Drive.GetDrives(pv, true))
            {
                foreach (File file in drive.files.Values)
                {
                    double subjectValue = file.subjectData.ScienceValue(file.size);
                    file.subjectData.RemoveScienceCollectedInFlight(subjectValue);

                    if (file.useStockCrediting)
                    {
                        file.ConvertToStockData().Save(protoHardDrive.moduleValues.AddNode("ScienceData"));

                        if (!file.subjectData.ExistsInRnD)
                        {
                            file.subjectData.CreateSubjectInRnD();
                        }

                        file.subjectData.SetAsPersistent();
                        file.subjectData.UpdateSubjectCompletion(subjectValue);
                    }
                    else
                    {
                        scienceToCredit += file.subjectData.RetrieveScience(subjectValue, false, pv);

                        labels.Add(new DialogGUILabel(Lib.BuildString(
                                                          Lib.Color("+ " + subjectValue.ToString("F1"), Lib.Kolor.Science),
                                                          " (",
                                                          Lib.Color(file.subjectData.ScienceRetrievedInKSC.ToString("F1"), Lib.Kolor.Science, true),
                                                          " / ",
                                                          Lib.Color(file.subjectData.ScienceMaxValue.ToString("F1"), Lib.Kolor.Science, true),
                                                          ") : ",
                                                          file.subjectData.FullTitle
                                                          )));
                    }
                }

                foreach (Sample sample in drive.samples.Values)
                {
                    double subjectValue = sample.subjectData.ScienceValue(sample.size);
                    sample.subjectData.RemoveScienceCollectedInFlight(subjectValue);

                    if (sample.useStockCrediting)
                    {
                        sample.ConvertToStockData().Save(protoHardDrive.moduleValues.AddNode("ScienceData"));

                        if (!sample.subjectData.ExistsInRnD)
                        {
                            sample.subjectData.CreateSubjectInRnD();
                        }

                        sample.subjectData.SetAsPersistent();
                        sample.subjectData.UpdateSubjectCompletion(subjectValue);
                    }
                    else
                    {
                        scienceToCredit += sample.subjectData.RetrieveScience(subjectValue, false, pv);

                        labels.Add(new DialogGUILabel(Lib.BuildString(
                                                          Lib.Color("+ " + subjectValue.ToString("F1"), Lib.Kolor.Science),
                                                          " (",
                                                          Lib.Color(sample.subjectData.ScienceRetrievedInKSC.ToString("F1"), Lib.Kolor.Science, true),
                                                          " / ",
                                                          Lib.Color(sample.subjectData.ScienceMaxValue.ToString("F1"), Lib.Kolor.Science, true),
                                                          ") : ",
                                                          sample.subjectData.FullTitle
                                                          )));
                    }
                }
            }

            protoHardDrive.moduleName = "ModuleScienceContainer";

            if (scienceToCredit > 0.0)
            {
                // ideally we should hack the stock dialog to add the little science widgets to it but I'm lazy
                // plus it looks like crap anyway
                PopupDialog.SpawnPopupDialog
                (
                    new MultiOptionDialog
                    (
                        "scienceResults", "", pv.vesselName + " " + Local.VesselRecovery_title, HighLogic.UISkin, new Rect(0.3f, 0.5f, 350f, 100f),                      //" recovery"
                        new DialogGUIVerticalLayout
                        (
                            new DialogGUIBox(Local.VesselRecovery_info + " : " + Lib.Color(scienceToCredit.ToString("F1") + " " + Local.VesselRecovery_CREDITS, Lib.Kolor.Science, true), 340f, 30f),                            //"SCIENCE RECOVERED"" CREDITS"
                            new DialogGUIScrollList
                            (
                                new Vector2(340f, 250f), false, true,
                                new DialogGUIVerticalLayout(labels.ToArray())
                            ),
                            new DialogGUIButton(Local.VesselRecovery_OKbutton, null, 340f, 30f, true, HighLogic.UISkin.button)                            //"OK"
                        )
                    ),
                    false, HighLogic.UISkin
                );
            }

            return(true);            // continue to the original code
        }
示例#14
0
        public static void BackgroundUpdate(Vessel v, ProtoPartModuleSnapshot m, Experiment experiment, Resource_info ec, double elapsed_s)
        {
            var    exp                 = ResearchAndDevelopment.GetExperiment(experiment.experiment_id);
            bool   didPrepare          = Lib.Proto.GetBool(m, "didPrepare", false);
            bool   shrouded            = Lib.Proto.GetBool(m, "shrouded", false);
            string last_subject_id     = Lib.Proto.GetString(m, "last_subject_id", "");
            double remainingSampleMass = Lib.Proto.GetDouble(m, "remainingSampleMass", 0);
            bool   broken              = Lib.Proto.GetBool(m, "broken", false);

            string subject_id;
            string issue = TestForIssues(v, exp, ec, experiment, broken,
                                         remainingSampleMass, didPrepare, shrouded, last_subject_id, out subject_id);

            Lib.Proto.Set(m, "issue", issue);

            double dataSampled = Lib.Proto.GetDouble(m, "dataSampled");

            if (last_subject_id != subject_id)
            {
                dataSampled = 0;
            }

            // if experiment is active
            if (!Lib.Proto.GetBool(m, "recording"))
            {
                return;
            }

            // if there are no issues
            if (issue.Length == 0 && dataSampled < exp.scienceCap * exp.dataScale)
            {
                Lib.Proto.Set(m, "last_subject_id", subject_id);

                // record in drive
                double chunkSize = experiment.data_rate * elapsed_s;
                var    info      = Science.Experiment(subject_id);
                double massDelta = experiment.sample_mass * chunkSize / info.max_amount;

                bool isSample = experiment.sample_mass < float.Epsilon;
                var  drive    = isSample
                                                   ? DB.Vessel(v).BestDrive(chunkSize, 0)
                                                   : DB.Vessel(v).BestDrive(0, Lib.SampleSizeToSlots(chunkSize));

                // on high time warp this chunk size could be too big, but we could store a sizable amount if we processed less
                double maxCapacity = isSample ? drive.FileCapacityAvailable() : drive.SampleCapacityAvailable(subject_id);
                if (maxCapacity < chunkSize)
                {
                    double factor = maxCapacity / chunkSize;
                    chunkSize *= factor;
                    massDelta *= factor;
                    elapsed_s *= factor;
                }

                bool stored = false;
                if (experiment.sample_mass < float.Epsilon)
                {
                    stored = drive.Record_file(subject_id, chunkSize, true, true);
                }
                else
                {
                    stored = drive.Record_sample(subject_id, chunkSize, massDelta);
                }

                if (stored)
                {
                    // consume ec
                    ec.Consume(experiment.ec_rate * elapsed_s);
                    dataSampled += chunkSize;
                    dataSampled  = Math.Min(dataSampled, exp.scienceCap * exp.dataScale);

                    if (!experiment.sample_collecting)
                    {
                        remainingSampleMass -= massDelta;
                        remainingSampleMass  = Math.Max(remainingSampleMass, 0);
                        Lib.Proto.Set(m, "remainingSampleMass", remainingSampleMass);
                    }

                    Lib.Proto.Set(m, "dataSampled", dataSampled);
                }
                else
                {
                    issue = "insufficient storage";
                    Lib.Proto.Set(m, "issue", issue);
                }
            }
        }
        private bool labWithCrew(Vessel v)
        {
            if (v == null || v.protoVessel == null)
            {
                return(false);
            }

            if (v.loaded)
            {
                List <ModuleScienceLab> labs = v.FindPartModulesImplementing <ModuleScienceLab>();

                for (int i = labs.Count - 1; i >= 0; i--)
                {
                    ModuleScienceLab lab = labs[i];

                    if (lab == null)
                    {
                        continue;
                    }

                    if (lab.part.protoModuleCrew.Count >= lab.crewsRequired)
                    {
                        return(true);
                    }
                }
            }
            else
            {
                for (int i = v.protoVessel.protoPartSnapshots.Count - 1; i >= 0; i--)
                {
                    ProtoPartSnapshot part = v.protoVessel.protoPartSnapshots[i];

                    if (part == null)
                    {
                        continue;
                    }

                    for (int j = part.modules.Count - 1; j >= 0; j--)
                    {
                        ProtoPartModuleSnapshot mod = part.modules[j];

                        if (mod == null)
                        {
                            continue;
                        }

                        if (mod.moduleName != "ModuleScienceLab")
                        {
                            continue;
                        }

                        int crew = (int)getCrewRequired(part);

                        if (part.protoModuleCrew.Count >= crew)
                        {
                            return(true);
                        }
                    }
                }
            }

            return(false);
        }
示例#16
0
		public ProtoEmitterDevice(ProtoPartModuleSnapshot emitter, uint part_id)
		{
			this.emitter = emitter;
			this.part_id = part_id;
		}
示例#17
0
        public static double GetChuteArea(List <ProtoPartSnapshot> protoParts)
        {
            double RCParameter    = 0;
            bool   realChuteInUse = false;

            try
            {
                foreach (ProtoPartSnapshot p in protoParts)
                {
                    if (p.modules.Exists(ppms => ppms.moduleName == "RealChuteModule"))
                    {
                        if (!realChuteInUse)
                        {
                            RCParameter = 0;
                        }
                        //First off, get the PPMS since we'll need that
                        ProtoPartModuleSnapshot realChute = p.modules.First(mod => mod.moduleName == "RealChuteModule");
                        //Assuming that's not somehow null, then we continue
                        if (realChute != null) //Some of this was adopted from DebRefund, as Vendan's method of handling multiple parachutes is better than what I had.
                        {
                            //We make a list of ConfigNodes containing the parachutes (usually 1, but now there can be any number of them)
                            //We get that from the PPMS
                            ConfigNode rcNode = new ConfigNode();
                            realChute.Save(rcNode);

                            //It's existence means that RealChute is installed and in use on the craft (you could have it installed and use stock chutes, so we only check if it's on the craft)
                            realChuteInUse = true;

                            RCParameter += ProcessRealchute(rcNode);
                        }
                    }
                    else if (p.modules.Exists(ppms => ppms.moduleName == "RealChuteFAR"))  //RealChute Lite for FAR
                    {
                        if (!realChuteInUse)
                        {
                            RCParameter = 0;
                        }

                        ProtoPartModuleSnapshot realChute = p.modules.First(mod => mod.moduleName == "RealChuteFAR");
                        float diameter = 0.0F; //realChute.moduleValues.GetValue("deployedDiameter")

                        if (realChute.moduleRef != null)
                        {
                            try
                            {
                                diameter = realChute.moduleRef.Fields.GetValue <float>("deployedDiameter");
                                Debug.Log($"[SR] Diameter is {diameter}.");
                            }
                            catch (Exception e)
                            {
                                Debug.LogError("[SR] Exception while finding deployedDiameter for RealChuteFAR module on moduleRef.");
                                Debug.LogException(e);
                            }
                        }
                        else
                        {
                            Debug.Log("[SR] moduleRef is null, attempting workaround to find diameter.");
                            object dDefault = p.partInfo.partPrefab.Modules["RealChuteFAR"]?.Fields?.GetValue("deployedDiameter"); //requires C# 6
                            if (dDefault != null)
                            {
                                diameter = Convert.ToSingle(dDefault);
                                Debug.Log($"[SR] Workaround gave a diameter of {diameter}.");
                            }
                            else
                            {
                                Debug.Log("[SR] Couldn't get default value, setting to 0 and calling it a day.");
                                diameter = 0.0F;
                            }
                        }
                        float dragC = 1.0f; //float.Parse(realChute.moduleValues.GetValue("staticCd"));
                        RCParameter += (dragC * Mathf.Pow(diameter, 2) * Math.PI / 4.0);

                        realChuteInUse = true;
                    }
                    else if (!realChuteInUse && p.modules.Exists(ppms => ppms.moduleName == "ModuleParachute"))
                    {
                        //Credit to m4v and RCSBuildAid: https://github.com/m4v/RCSBuildAid/blob/master/Plugin/CoDMarker.cs
                        Part         part      = p.partRef ?? p.partPrefab; //the part reference, or the part prefab
                        DragCubeList dragCubes = part.DragCubes;
                        dragCubes.SetCubeWeight("DEPLOYED", 1);
                        dragCubes.SetCubeWeight("SEMIDEPLOYED", 0);
                        dragCubes.SetCubeWeight("PACKED", 0);
                        dragCubes.SetOcclusionMultiplier(0);
                        Quaternion rotation = Quaternion.LookRotation(Vector3d.up);
                        try
                        {
                            rotation = Quaternion.LookRotation(part.partTransform?.InverseTransformDirection(Vector3d.up) ?? Vector3d.up);
                        }
                        catch (Exception)
                        {
                            //Debug.LogException(e);
                        }
                        dragCubes.SetDragVectorRotation(rotation);
                    }
                    if (!realChuteInUse)
                    {
                        Part         part      = p.partRef ?? p.partPrefab; //the part reference, or the part prefab
                        DragCubeList dragCubes = part.DragCubes;
                        dragCubes.ForceUpdate(false, true);
                        dragCubes.SetDragWeights();
                        dragCubes.SetPartOcclusion();

                        Vector3 dir = Vector3d.up;
                        dragCubes.SetDrag(dir, 0.03f); //mach 0.03, or about 10m/s

                        double dragCoeff = dragCubes.AreaDrag * PhysicsGlobals.DragCubeMultiplier;

                        RCParameter += (dragCoeff * PhysicsGlobals.DragMultiplier);
                    }
                }
            }
            catch (Exception e)
            {
                Debug.LogError("[SR] Error occured while trying to determine total chute area.");
                Debug.LogException(e);
            }
            return(RCParameter);
        }
示例#18
0
        static void ProcessAsteroidDrill(Vessel v, ProtoPartSnapshot p, ProtoPartModuleSnapshot m, ModuleAsteroidDrill asteroid_drill, vessel_resources resources, double elapsed_s)
        {
            // note: untested
            // note: ignore stock temperature mechanic of asteroid drills
            // note: ignore autoshutdown
            // note: 'undo' stock behaviour by forcing lastUpdateTime to now (to minimize overlapping calculations from this and stock post-facto simulation)

            // if active
            if (Lib.Proto.GetBool(m, "IsActivated"))
            {
                // get asteroid data
                ProtoPartModuleSnapshot asteroid_info     = null;
                ProtoPartModuleSnapshot asteroid_resource = null;
                foreach (ProtoPartSnapshot pp in v.protoVessel.protoPartSnapshots)
                {
                    if (asteroid_info == null)
                    {
                        asteroid_info = pp.modules.Find(k => k.moduleName == "ModuleAsteroidInfo");
                    }
                    if (asteroid_resource == null)
                    {
                        asteroid_resource = pp.modules.Find(k => k.moduleName == "ModuleAsteroidResource");
                    }
                }

                // if there is actually an asteroid attached to this active asteroid drill (it should)
                if (asteroid_info != null && asteroid_resource != null)
                {
                    // get some data
                    double mass_threshold = Lib.Proto.GetDouble(asteroid_info, "massThresholdVal");
                    double mass           = Lib.Proto.GetDouble(asteroid_info, "currentMassVal");
                    double abundance      = Lib.Proto.GetDouble(asteroid_resource, "abundance");
                    string res_name       = Lib.Proto.GetString(asteroid_resource, "resourceName");
                    double res_density    = PartResourceLibrary.Instance.GetDefinition(res_name).density;

                    // if asteroid isn't depleted
                    if (mass > mass_threshold && abundance > double.Epsilon)
                    {
                        // deduce crew bonus
                        int exp_level = -1;
                        if (asteroid_drill.UseSpecialistBonus)
                        {
                            foreach (ProtoCrewMember c in Lib.CrewList(v))
                            {
                                if (c.experienceTrait.Effects.Find(k => k.Name == asteroid_drill.ExperienceEffect) != null)
                                {
                                    exp_level = Math.Max(exp_level, c.experienceLevel);
                                }
                            }
                        }
                        double exp_bonus = exp_level < 0
          ? asteroid_drill.EfficiencyBonus * asteroid_drill.SpecialistBonusBase
          : asteroid_drill.EfficiencyBonus * (asteroid_drill.SpecialistBonusBase + (asteroid_drill.SpecialistEfficiencyFactor * (exp_level + 1)));

                        // determine resource extracted
                        double res_amount = abundance * asteroid_drill.Efficiency * exp_bonus * elapsed_s;

                        // transform EC into mined resource
                        resource_recipe recipe = new resource_recipe();
                        recipe.Input("ElectricCharge", asteroid_drill.PowerConsumption * elapsed_s);
                        recipe.Output(res_name, res_amount, true);
                        resources.Transform(recipe);

                        // if there was ec
                        // note: comparing against amount in previous simulation step
                        if (resources.Info(v, "ElectricCharge").amount > double.Epsilon)
                        {
                            // consume asteroid mass
                            Lib.Proto.Set(asteroid_info, "currentMassVal", (mass - res_density * res_amount));
                        }
                    }
                }

                // undo stock behaviour by forcing last_update_time to now
                Lib.Proto.Set(m, "lastUpdateTime", Planetarium.GetUniversalTime());
            }
        }
示例#19
0
        static void ProcessHarvester(Vessel v, ProtoPartSnapshot p, ProtoPartModuleSnapshot m, ModuleResourceHarvester harvester, vessel_resources resources, double elapsed_s)
        {
            // note: ignore stock temperature mechanic of harvesters
            // note: ignore autoshutdown
            // note: ignore depletion (stock seem to do the same)
            // note: 'undo' stock behaviour by forcing lastUpdateTime to now (to minimize overlapping calculations from this and stock post-facto simulation)

            // if active
            if (Lib.Proto.GetBool(m, "IsActivated"))
            {
                // do nothing if full
                // note: comparing against previous amount
                if (resources.Info(v, harvester.ResourceName).level < harvester.FillAmount - double.Epsilon)
                {
                    // deduce crew bonus
                    int exp_level = -1;
                    if (harvester.UseSpecialistBonus)
                    {
                        foreach (ProtoCrewMember c in Lib.CrewList(v))
                        {
                            if (c.experienceTrait.Effects.Find(k => k.Name == harvester.ExperienceEffect) != null)
                            {
                                exp_level = Math.Max(exp_level, c.experienceLevel);
                            }
                        }
                    }
                    double exp_bonus = exp_level < 0
          ? harvester.EfficiencyBonus * harvester.SpecialistBonusBase
          : harvester.EfficiencyBonus * (harvester.SpecialistBonusBase + (harvester.SpecialistEfficiencyFactor * (exp_level + 1)));

                    // detect amount of ore in the ground
                    AbundanceRequest request = new AbundanceRequest
                    {
                        Altitude     = v.altitude,
                        BodyId       = v.mainBody.flightGlobalsIndex,
                        CheckForLock = false,
                        Latitude     = v.latitude,
                        Longitude    = v.longitude,
                        ResourceType = (HarvestTypes)harvester.HarvesterType,
                        ResourceName = harvester.ResourceName
                    };
                    double abundance = ResourceMap.Instance.GetAbundance(request);

                    // if there is actually something (should be if active when unloaded)
                    if (abundance > harvester.HarvestThreshold)
                    {
                        // create and commit recipe
                        resource_recipe recipe = new resource_recipe();
                        foreach (var ir in harvester.inputList)
                        {
                            recipe.Input(ir.ResourceName, ir.Ratio * elapsed_s);
                        }
                        recipe.Output(harvester.ResourceName, abundance * harvester.Efficiency * exp_bonus * elapsed_s, true);
                        resources.Transform(recipe);
                    }
                }

                // undo stock behaviour by forcing last_update_time to now
                Lib.Proto.Set(m, "lastUpdateTime", Planetarium.GetUniversalTime());
            }
        }
示例#20
0
        static void ProcessCryoTank(Vessel v, ProtoPartSnapshot p, ProtoPartModuleSnapshot m, PartModule cryotank, Vessel_resources resources, Resource_info ec, double elapsed_s)
        {
            // Note. Currently background simulation of Cryotanks has an irregularity in that boiloff of a fuel type in a tank removes resources from all tanks
            // but at least some simulation is better than none ;)

            // get list of fuels, do nothing if no fuels
            IList fuels = Lib.ReflectionValue <IList>(cryotank, "fuels");

            if (fuels == null)
            {
                return;
            }

            // is cooling available, note: comparing against amount in previous simulation step
            bool available = (Lib.Proto.GetBool(m, "CoolingEnabled") && ec.amount > double.Epsilon);

            // get cooling cost
            double cooling_cost = Lib.ReflectionValue <float>(cryotank, "CoolingCost");

            string fuel_name    = "";
            double amount       = 0.0;
            double total_cost   = 0.0;
            double boiloff_rate = 0.0;

            foreach (var item in fuels)
            {
                fuel_name = Lib.ReflectionValue <string>(item, "fuelName");
                // if fuel_name is null, don't do anything
                if (fuel_name == null)
                {
                    continue;
                }

                //get fuel resource
                Resource_info fuel = resources.Info(v, fuel_name);

                // if there is some fuel
                // note: comparing against amount in previous simulation step
                if (fuel.amount > double.Epsilon)
                {
                    // Try to find resource "fuel_name" in PartResources
                    ProtoPartResourceSnapshot proto_fuel = p.resources.Find(k => k.resourceName == fuel_name);

                    // If part doesn't have the fuel, don't do anything.
                    if (proto_fuel == null)
                    {
                        continue;
                    }

                    // get amount in the part
                    amount = proto_fuel.amount;

                    // if cooling is enabled and there is enough EC
                    if (available)
                    {
                        // calculate ec consumption
                        total_cost += cooling_cost * amount * 0.001;
                    }
                    // if cooling is disabled or there wasn't any EC
                    else
                    {
                        // get boiloff rate per-second
                        boiloff_rate = Lib.ReflectionValue <float>(item, "boiloffRate") / 360000.0f;

                        // let it boil off
                        fuel.Consume(amount * (1.0 - Math.Pow(1.0 - boiloff_rate, elapsed_s)));
                    }
                }
            }

            // apply EC consumption
            ec.Consume(total_cost * elapsed_s);
        }
示例#21
0
        public AntennaInfoCommNet(Vessel v, bool powered, bool storm, bool transmitting)
        {
            int transmitterCount = 0;

            rate = 1;
            double ec_transmitter = 0;

            // if vessel is loaded
            if (v.loaded)
            {
                List <ModuleDataTransmitter> transmitters;

                if (!Cache.HasVesselObjectsCache(v, "commnet"))
                {
                    // find transmitters
                    transmitters = v.FindPartModulesImplementing <ModuleDataTransmitter>();
                    if (transmitters == null)
                    {
                        transmitters = new List <ModuleDataTransmitter>();
                    }
                    Cache.SetVesselObjectsCache(v, "commnet", transmitters);
                }
                else
                {
                    transmitters = Cache.VesselObjectsCache <List <ModuleDataTransmitter> >(v, "commnet");
                }

                foreach (ModuleDataTransmitter t in transmitters)
                {
                    // Disable all stock buttons
                    t.Events["TransmitIncompleteToggle"].active = false;
                    t.Events["StartTransmission"].active        = false;
                    t.Events["StopTransmission"].active         = false;
                    t.Actions["StartTransmissionAction"].active = false;

                    if (t.antennaType == AntennaType.INTERNAL)                     // do not include internal data rate, ec cost only
                    {
                        ec += t.DataResourceCost * t.DataRate;
                    }
                    else
                    {
                        // do we have an animation
                        ModuleDeployableAntenna animation        = t.part.FindModuleImplementing <ModuleDeployableAntenna>();
                        ModuleAnimateGeneric    animationGeneric = t.part.FindModuleImplementing <ModuleAnimateGeneric>();
                        if (animation != null)
                        {
                            // only include data rate and ec cost if transmitter is extended
                            if (animation.deployState == ModuleDeployablePart.DeployState.EXTENDED)
                            {
                                rate *= t.DataRate;
                                transmitterCount++;
                                var e = t.DataResourceCost * t.DataRate;
                                ec_transmitter += e;
                            }
                        }
                        else if (animationGeneric != null)
                        {
                            // only include data rate and ec cost if transmitter is extended
                            if (animationGeneric.animSpeed > 0)
                            {
                                rate *= t.DataRate;
                                transmitterCount++;
                                var e = t.DataResourceCost * t.DataRate;
                                ec_transmitter += e;
                            }
                        }
                        // no animation
                        else
                        {
                            rate *= t.DataRate;
                            transmitterCount++;
                            var e = t.DataResourceCost * t.DataRate;
                            ec_transmitter += e;
                        }
                    }
                }
            }
            // if vessel is not loaded
            else
            {
                List <KeyValuePair <ModuleDataTransmitter, ProtoPartSnapshot> > transmitters;
                if (!Cache.HasVesselObjectsCache(v, "commnet_bg"))
                {
                    transmitters = new List <KeyValuePair <ModuleDataTransmitter, ProtoPartSnapshot> >();
                    // find proto transmitters
                    foreach (ProtoPartSnapshot p in v.protoVessel.protoPartSnapshots)
                    {
                        // get part prefab (required for module properties)
                        Part part_prefab = PartLoader.getPartInfoByName(p.partName).partPrefab;

                        foreach (ModuleDataTransmitter t in part_prefab.FindModulesImplementing <ModuleDataTransmitter>())
                        {
                            transmitters.Add(new KeyValuePair <ModuleDataTransmitter, ProtoPartSnapshot>(t, p));
                        }
                    }

                    Cache.SetVesselObjectsCache(v, "commnet_bg", transmitters);
                }
                else
                {
                    // cache transmitters
                    transmitters = Cache.VesselObjectsCache <List <KeyValuePair <ModuleDataTransmitter, ProtoPartSnapshot> > >(v, "commnet_bg");
                }

                foreach (var pair in transmitters)
                {
                    ModuleDataTransmitter t = pair.Key;
                    ProtoPartSnapshot     p = pair.Value;

                    if (t.antennaType == AntennaType.INTERNAL)                     // do not include internal data rate, ec cost only
                    {
                        ec += t.DataResourceCost * t.DataRate;
                    }
                    else
                    {
                        // do we have an animation
                        ProtoPartModuleSnapshot m = p.FindModule("ModuleDeployableAntenna") ?? p.FindModule("ModuleAnimateGeneric");
                        if (m != null)
                        {
                            // only include data rate and ec cost if transmitter is extended
                            string deployState = Lib.Proto.GetString(m, "deployState");
                            float  animSpeed   = Lib.Proto.GetFloat(m, "animSpeed");
                            if (deployState == "EXTENDED" || animSpeed > 0)
                            {
                                rate *= t.DataRate;
                                transmitterCount++;
                                ec_transmitter += t.DataResourceCost * t.DataRate;
                            }
                        }
                        // no animation
                        else
                        {
                            rate *= t.DataRate;
                            transmitterCount++;
                            ec_transmitter += t.DataResourceCost * t.DataRate;
                        }
                    }
                }
            }

            if (transmitterCount > 1)
            {
                rate = Math.Pow(rate, 1.0 / transmitterCount);
            }
            else if (transmitterCount == 0)
            {
                rate = 0;
            }

            // when transmitting, transmitters need more EC for the signal amplifiers.
            // while not transmitting, transmitters only use 10-20% of that
            ec_transmitter *= transmitting ? Settings.TransmitterActiveEcFactor : Settings.TransmitterPassiveEcFactor;

            ec += ec_transmitter;

            Init(v, powered, storm);
        }
示例#22
0
        /*************************************************************************************************************************/
        public bool search_for_new_vessels(string save_file_name)
        {
            bool new_vessel_found = false, controllable = false;

            Log.PushStackInfo("FMRS_Core.search_for_new_vessels(string)", "entering search_for_new_vessels(string save_file_name) {0}", save_file_name);

            foreach (Vessel temp_vessel in FlightGlobals.Vessels)
            {
                controllable = false;

                //Check if the stage was claimed by another mod or by this mod
                string controllingMod = RecoveryControllerWrapper.ControllingMod(temp_vessel);

                bool FMRSIsControllingMod = false;
                if (controllingMod != null)
                {
                    Log.info("RecoveryControllerWrapper.ControllingMod for vessel: {0} : {1}", temp_vessel.name, controllingMod);

                    FMRSIsControllingMod = string.Equals(controllingMod, "FMRS", StringComparison.OrdinalIgnoreCase);
                }

                if (controllingMod == null ||
                    string.Equals(controllingMod, "auto", StringComparison.OrdinalIgnoreCase) ||
                    FMRSIsControllingMod)
                {
                    if (!Vessels.Contains(temp_vessel.id))
                    {
                        if (FMRSIsControllingMod ||
                            (
                                ((temp_vessel.isCommandable && temp_vessel.IsControllable) || (_SETTING_Control_Uncontrollable && controllingMod == null)) &&
                                temp_vessel.vesselType != VesselType.EVA &&
                                temp_vessel.vesselType != VesselType.Flag &&
                                temp_vessel.vesselType != VesselType.SpaceObject &&
                                temp_vessel.vesselType != VesselType.Unknown
                            )
                            )
                        {
                            controllable = true;
                        }
                        else
                        {
                            foreach (ProtoPartSnapshot proto_part in temp_vessel.protoVessel.protoPartSnapshots)
                            {
                                List <ProtoPartModuleSnapshot> proto_modules = proto_part.modules;
                                ProtoPartModuleSnapshot        module        = null;

                                if (proto_modules != null &&
                                    (_SETTING_Parachutes &&
                                     ((controllingMod != null && string.Equals(controllingMod, "FMRS", StringComparison.OrdinalIgnoreCase)) ||
                                      !_SETTING_Defer_Parachutes_to_StageRecovery ||
                                      !stageRecoveryInstalled)
                                    )
                                    )
                                {
                                    //
                                    module = proto_part.modules.Find(p => p.moduleName == "RealChuteModule" ||
                                                                     p.moduleName == "ModuleParachute" ||
                                                                     p.moduleName == "ModuleKrKerbalParachute" ||
                                                                     p.moduleName == "RealChuteFAR");
                                    if (module != null)
                                    {
                                        controllable = true;
                                    }
                                }

                                if (proto_part.protoCrewNames.Count > 0)
                                {
                                    controllable = true;
                                }
                            }
                        }
                        foreach (Part p in temp_vessel.Parts)
                        {
                            foreach (PartModule pm in p.Modules)
                            {
                                if (pm.moduleName == "FMRS_PM")
                                {
                                    if ((pm as FMRS_PM).parent_vessel != "00000000-0000-0000-0000-000000000000")
                                    {
                                        controllable = false;
                                        break;
                                    }
                                }
                            }
                            break;
                        }

                        if (controllable)
                        {
                            Log.dbg("{0} Found and will be added to the dicts", temp_vessel.vesselName);

                            Vessels_dropped.Add(temp_vessel.id, save_file_name);
                            Vessels_dropped_names.Add(temp_vessel.id, temp_vessel.vesselName);
                            Vessel_State.Add(temp_vessel.id, vesselstate.FLY);
                            foreach (Part p in temp_vessel.Parts)
                            {
                                foreach (PartModule pm in p.Modules)
                                {
                                    if (pm.moduleName == "FMRS_PM")
                                    {
                                        pm.StartCoroutine("setid");
                                    }
                                }
                            }

                            foreach (ProtoPartSnapshot part_snapshot in temp_vessel.protoVessel.protoPartSnapshots)
                            {
                                foreach (ProtoCrewMember member in part_snapshot.protoModuleCrew)
                                {
                                    if (!Kerbal_dropped.ContainsKey(member.name))
                                    {
                                        Kerbal_dropped.Add(member.name, temp_vessel.id);
                                    }
                                }
                            }
                            new_vessel_found = true;
                        }
                        Vessels.Add(temp_vessel.id);
                    }
                }
            }

            Log.PopStackInfo("leaving search_for_new_vessels(string save_file_name)");

            return(new_vessel_found);
        }
示例#23
0
 // Simulate resources production/consumption for unloaded vessel
 public static string BackgroundUpdate(Vessel v, ProtoPartSnapshot part_snapshot, ProtoPartModuleSnapshot module_snapshot, PartModule proto_part_module, Part proto_part, Dictionary <string, double> availableResources, List <KeyValuePair <string, double> > resourceChangeRequest, double elapsed_s)
 {
     if (Lib.Proto.GetBool(module_snapshot, "IsCooling"))
     {
         foreach (ModuleResource res in ((proto_part_module as SystemHeatRadiatorKerbalism).resHandler.inputResources))
         {
             resourceChangeRequest.Add(new KeyValuePair <string, double>(res.name, -res.rate));
         }
     }
     return(radiatorTitle);
 }
示例#24
0
        private IEnumerator loadSensors()
        {
            while (!FlightGlobals.ready)
            {
                yield return(null);
            }

            for (int i = FlightGlobals.Vessels.Count - 1; i >= 0; i--)
            {
                Vessel v = FlightGlobals.Vessels[i];

                if (v == null)
                {
                    continue;
                }

                if (v.mainBody != FlightGlobals.ActiveVessel.mainBody)
                {
                    continue;
                }

                if (v.loaded)
                {
                    for (int j = 0; j < v.Parts.Count; j++)
                    {
                        Part p = v.Parts[j];

                        if (p == null)
                        {
                            continue;
                        }

                        IDMSeismometer sensor = p.FindModuleImplementing <IDMSeismometer>();

                        if (sensor != null)
                        {
                            addLoadedSeismometer(p.flightID, sensor);
                        }
                    }
                }
                else
                {
                    ProtoVessel pv = v.protoVessel;

                    for (int j = 0; j < v.protoVessel.protoPartSnapshots.Count; j++)
                    {
                        ProtoPartSnapshot p = v.protoVessel.protoPartSnapshots[j];

                        if (p == null)
                        {
                            continue;
                        }

                        for (int k = 0; k < p.modules.Count; k++)
                        {
                            ProtoPartModuleSnapshot m = p.modules[k];

                            if (m == null)
                            {
                                continue;
                            }

                            if (m.moduleName == "DMSeismicSensor" || m.moduleName == "DMSeismicHammer")
                            {
                                addProtoSeismometer(p.flightID, p, m);
                            }
                        }
                    }
                }
            }
        }
示例#25
0
 /// <summary>
 /// For Kerbalism integration
 /// </summary>
 /// <returns></returns>
 public new static string BackgroundUpdate(Vessel v,
                                           ProtoPartSnapshot part_snapshot, ProtoPartModuleSnapshot module_snapshot,
                                           PartModule proto_part_module, Part proto_part,
                                           Dictionary <string, double> availableResources, List <KeyValuePair <string, double> > resourceChangeRequest,
                                           double elapsed_s) => ModuleAvionics.BackgroundUpdate(v, part_snapshot, module_snapshot, proto_part_module, proto_part, availableResources, resourceChangeRequest, elapsed_s);
示例#26
0
        static void ProcessScanner(Vessel v, ProtoPartSnapshot p, ProtoPartModuleSnapshot m, PartModule scanner, Part part_prefab, VesselData vd, resource_info ec, double elapsed_s)
        {
            // get ec consumption rate
            double power = SCANsat.EcConsumption(scanner);

            // if the scanner doesn't require power to operate, we aren't interested in simulating it
            if (power <= double.Epsilon)
            {
                return;
            }

            // get scanner state
            bool is_scanning = Lib.Proto.GetBool(m, "scanning");

            // if its scanning
            if (is_scanning)
            {
                // consume ec
                ec.Consume(power * elapsed_s);

                // if there isn't ec
                // - comparing against amount in previous simulation step
                if (ec.amount <= double.Epsilon)
                {
                    // unregister scanner
                    SCANsat.stopScanner(v, m, part_prefab);
                    is_scanning = false;

                    // remember disabled scanner
                    vd.scansat_id.Add(p.flightID);

                    // give the user some feedback
                    if (vd.cfg_ec)
                    {
                        Message.Post(Lib.BuildString("SCANsat sensor was disabled on <b>", v.vesselName, "</b>"));
                    }
                }
            }
            // if it was disabled in background
            else if (vd.scansat_id.Contains(p.flightID))
            {
                // if there is enough ec
                // note: comparing against amount in previous simulation step
                if (ec.level > 0.25) //< re-enable at 25% EC
                {
                    // re-enable the scanner
                    SCANsat.resumeScanner(v, m, part_prefab);
                    is_scanning = true;

                    // give the user some feedback
                    if (vd.cfg_ec)
                    {
                        Message.Post(Lib.BuildString("SCANsat sensor resumed operations on <b>", v.vesselName, "</b>"));
                    }
                }
            }

            // forget active scanners
            if (is_scanning)
            {
                vd.scansat_id.Remove(p.flightID);
            }
        }
示例#27
0
        public static void BackgroundUpdate(Vessel v, ProtoPartModuleSnapshot m, Greenhouse g,
                                            vessel_info vi, vessel_resources resources, double elapsed_s)
        {
            // get protomodule data
            bool   active = Lib.Proto.GetBool(m, "active");
            double growth = Lib.Proto.GetDouble(m, "growth");

            // if enabled and not ready for harvest
            if (active && growth < 0.99)
            {
                // get resource handler
                resource_info ec = resources.Info(v, "ElectricCharge");

                // calculate natural and artificial lighting
                double natural    = vi.solar_flux;
                double artificial = Math.Max(g.light_tolerance - natural, 0.0);

                // consume EC for the lamps, scaled by artificial light intensity
                if (artificial > double.Epsilon)
                {
                    ec.Consume(g.ec_rate * (artificial / g.light_tolerance) * elapsed_s);
                }

                // reset artificial lighting if there is no ec left
                // note: comparing against amount in previous simulation step
                if (ec.amount <= double.Epsilon)
                {
                    artificial = 0.0;
                }

                // execute recipe
                resource_recipe recipe = new resource_recipe();
                foreach (ModuleResource input in g.resHandler.inputResources)
                {
                    recipe.Input(input.name, input.rate * elapsed_s);
                }
                foreach (ModuleResource output in g.resHandler.outputResources)
                {
                    recipe.Output(output.name, output.rate * elapsed_s, true);
                }
                resources.Transform(recipe);

                // determine environment conditions
                bool lighting  = natural + artificial >= g.light_tolerance;
                bool pressure  = g.pressure_tolerance <= double.Epsilon || vi.pressure >= g.pressure_tolerance;
                bool radiation = g.radiation_tolerance <= double.Epsilon || vi.radiation * (1.0 - vi.shielding) < g.radiation_tolerance;

                // determine inputs conditions
                // note: comparing against amounts in previous simulation step
                bool   inputs      = true;
                string missing_res = string.Empty;
                foreach (ModuleResource input in g.resHandler.inputResources)
                {
                    if (resources.Info(v, input.name).amount <= double.Epsilon)
                    {
                        inputs      = false;
                        missing_res = input.name;
                        break;
                    }
                }

                // if growing
                if (lighting && pressure && radiation && inputs)
                {
                    // increase growth
                    growth += g.crop_rate * elapsed_s;
                    growth  = Math.Min(growth, 1.0);

                    // notify the user when crop can be harvested
                    if (growth >= 0.99)
                    {
                        Message.Post(Lib.BuildString("On <b>", v.vesselName, "</b> the crop is ready to be harvested"));
                        growth = 1.0;
                    }
                }

                // update time-to-harvest
                double tta = (1.0 - growth) / g.crop_rate;

                // update issues
                string issue =
                    !inputs?Lib.BuildString("missing ", missing_res)
                        : !lighting  ? "insufficient lighting"
      : !pressure  ? "insufficient pressure"
      : !radiation ? "excessive radiation"
      : string.Empty;

                // update protomodule data
                Lib.Proto.Set(m, "natural", natural);
                Lib.Proto.Set(m, "artificial", artificial);
                Lib.Proto.Set(m, "tta", tta);
                Lib.Proto.Set(m, "issue", issue);
                Lib.Proto.Set(m, "growth", growth);
            }
        }
示例#28
0
		public ProtoRingDevice(ProtoPartModuleSnapshot ring, uint part_id)
		{
			this.ring = ring;
			this.part_id = part_id;
		}
        private bool finishTransfer(Vessel v, ScienceData d, float boost)
        {
            if (v == null)
            {
                return(false);
            }

            if (d == null)
            {
                return(false);
            }

            if (v.loaded)
            {
                List <ModuleScienceContainer> containers = v.FindPartModulesImplementing <ModuleScienceContainer>();

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

                ModuleScienceContainer currentContainer = null;

                for (int j = containers.Count - 1; j >= 0; j--)
                {
                    ModuleScienceContainer container = containers[j];

                    if (container.capacity != 0 && container.GetData().Length >= container.capacity)
                    {
                        continue;
                    }

                    if (container.allowRepeatedSubjects)
                    {
                        currentContainer = container;
                        break;
                    }

                    if (container.HasData(d))
                    {
                        continue;
                    }

                    currentContainer = container;
                }

                if (currentContainer != null)
                {
                    d.triggered         = false;
                    d.dataAmount       *= (d.baseTransmitValue * (1 + boost));
                    d.transmitBonus     = 1;
                    d.baseTransmitValue = 1;
                    return(currentContainer.AddData(d));
                }
            }
            else
            {
                List <ProtoPartSnapshot> containers = getProtoContainers(v.protoVessel);

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

                ProtoPartModuleSnapshot currentContainer = null;

                uint host = 0;

                for (int j = containers.Count - 1; j >= 0; j--)
                {
                    ProtoPartSnapshot container = containers[j];

                    host = container.flightID;

                    ProtoPartModuleSnapshot tempContainer = null;

                    for (int k = container.modules.Count - 1; k >= 0; k--)
                    {
                        ProtoPartModuleSnapshot mod = container.modules[k];

                        if (mod.moduleName != "ModuleScienceContainer")
                        {
                            continue;
                        }

                        tempContainer = mod;

                        break;
                    }

                    if (tempContainer == null)
                    {
                        continue;
                    }

                    List <ScienceData> protoData = new List <ScienceData>();

                    ConfigNode[] science = tempContainer.moduleValues.GetNodes("ScienceData");

                    for (int l = science.Length - 1; l >= 0; l--)
                    {
                        ConfigNode node = science[l];

                        protoData.Add(new ScienceData(node));
                    }

                    Part prefab = container.partInfo.partPrefab;

                    ModuleScienceContainer prefabContainer = prefab.FindModuleImplementing <ModuleScienceContainer>();

                    if (prefabContainer != null)
                    {
                        if (prefabContainer.capacity != 0 && protoData.Count >= prefabContainer.capacity)
                        {
                            continue;
                        }

                        if (prefabContainer.allowRepeatedSubjects)
                        {
                            currentContainer = tempContainer;
                            break;
                        }

                        if (HasData(d.subjectID, protoData))
                        {
                            continue;
                        }

                        currentContainer = tempContainer;
                    }
                }

                if (currentContainer != null)
                {
                    d.triggered         = false;
                    d.dataAmount        = d.dataAmount * (d.baseTransmitValue * (boost + 1));
                    d.transmitBonus     = 1;
                    d.baseTransmitValue = 1;
                    d.container         = host;
                    d.Save(currentContainer.moduleValues.AddNode("ScienceData"));
                    return(true);
                }
            }

            return(false);
        }
 public static ModuleConfigurationFlags BackgroundModuleConfiguration(
     ProtoPartModuleSnapshot protoPartModuleSnapshot) => ModuleConfigurationFlags.LocalResources |
 ModuleConfigurationFlags.First |
 ModuleConfigurationFlags.SupplierOnly;
 public ProtoSignalProcessor(ProtoPartModuleSnapshot ppms, Vessel v)
 {
     Vessel = v;
     Powered = ppms.GetBool("IsPowered");
     CommandStation = Powered && v.HasCommandStation() && Vessel.GetVesselCrew().Count >= 6;
 }
示例#32
0
        public Antenna_Info(Vessel v)
        {
            List <AntennaPartInfo> adaptorsInfoList = new List <AntennaPartInfo>();

            int numParts = (!v.loaded) ? v.protoVessel.protoPartSnapshots.Count : v.Parts.Count;

            for (int partIndex = 0; partIndex < numParts; partIndex++)
            {
                Part part;
                ProtoPartSnapshot protoPart = null;

                if (v.loaded)
                {
                    part = v.Parts[partIndex];
                }
                else
                {
                    protoPart = v.protoVessel.protoPartSnapshots[partIndex];
                    part      = PartLoader.getPartInfoByName(protoPart.partName).partPrefab;
                }

                bool                    hasInfo         = false;
                AntennaPartInfo         antennaPartInfo = new AntennaPartInfo();
                ProtoPartModuleSnapshot protoPartModule = null;

                // Inspect each module of the part
                for (int moduleIndex = 0; moduleIndex < part.Modules.Count; moduleIndex++)
                {
                    NetworkAdaptor antennaMod = new NetworkAdaptor();
                    PartModule     pModule    = part.Modules[moduleIndex];
                    if (pModule is NetworkAdaptor)
                    {
                        if (v.loaded)
                        {
                            antennaMod = (NetworkAdaptor)pModule;
                            antennaPartInfo.frequency = antennaMod.frequency;
                            antennaPartInfo.ecCost    = antennaMod.ecCost;
                            antennaPartInfo.rate      = antennaMod.rate;
                            antennaPartInfo.name      = part.partInfo.title;
                        }
                        else
                        {
                            ProtoPartModuleSnapshot netAdaptor = FlightGlobals.FindProtoPartByID(protoPart.flightID).FindModule("NetworkAdaptor");
                            antennaPartInfo.frequency = Lib.Proto.GetShort(netAdaptor, "frequency");
                            antennaPartInfo.ecCost    = Lib.Proto.GetDouble(netAdaptor, "ecCost");
                            antennaPartInfo.rate      = Lib.Proto.GetDouble(netAdaptor, "rate");
                            antennaPartInfo.name      = protoPart.partInfo.title;
                        }

                        hasInfo = true;
                    }
                    else if (pModule is ICommAntenna)
                    {
                        ICommAntenna antenna = pModule as ICommAntenna;

                        // This method only works when v.Loaded, otherwise this brings a wrong deployState
                        ModuleDeployableAntenna anim = part.FindModuleImplementing <ModuleDeployableAntenna>();

                        // Assume extended if there is no animator
                        if (anim != null)
                        {
                            if (!v.loaded)
                            {
                                // This method works to !v.Loaded
                                ProtoPartModuleSnapshot deployState = FlightGlobals.FindProtoPartByID(protoPart.flightID).FindModule("ModuleDeployableAntenna");
                                antennaPartInfo.deployState = Lib.KCOMMNET.String_to_DeployState(Lib.Proto.GetString(deployState, "deployState"));
                            }
                            else
                            {
                                antennaPartInfo.deployState = anim.deployState;
                            }
                        }
                        else
                        {
                            antennaPartInfo.deployState = ModuleDeployablePart.DeployState.EXTENDED;
                        }

                        if (!v.loaded)
                        {
                            protoPartModule = protoPart.FindModule(pModule, moduleIndex);
                        }

                        antennaPartInfo.antennaPower              = (!v.loaded) ? antenna.CommPowerUnloaded(protoPartModule) : antenna.CommPower;
                        antennaPartInfo.antennaCombinable         = antenna.CommCombinable;
                        antennaPartInfo.antennaCombinableExponent = antenna.CommCombinableExponent;
                        antennaPartInfo.antennaType = antenna.CommType;
                        //antennaPartInfo.partReference = part;
                        //antennaPartInfo.partSnapshotReference = protoPart;
                        antennaPartInfo.canComm = (!v.loaded) ? antenna.CanCommUnloaded(protoPartModule) : antenna.CanComm();

                        hasInfo = true;
                    }
                }

                if (hasInfo)
                {
                    adaptorsInfoList.Add(antennaPartInfo);
                }
            }

            freqSortedList     = adaptorsInfoList.OrderBy(a => a.frequency).ToList(); // order by frequency
            adaptorsSortedList = adaptorsInfoList.OrderBy(a => a.name).ToList();      // order by device name

            AntennaCalc(freqSortedList);
        }
 public static string KITPartName(ProtoPartSnapshot protoPartSnapshot,
                                  ProtoPartModuleSnapshot protoPartModuleSnapshot) => _kitPartName;
示例#34
0
 public ProtoDrillDevice(ProtoPartModuleSnapshot drill, ModuleResourceHarvester prefab, uint part_id)
 {
   this.drill = drill;
   this.prefab = prefab;
   this.part_id = part_id;
 }
示例#35
0
        public void onProtoSave(GameEvents.FromToAction <ProtoPartModuleSnapshot, ConfigNode> FTA)
        {
            if (FTA.from.moduleName != "ModuleSEPScienceExperiment")
            {
                return;
            }

            ConfigNode node = FTA.to;

            //This is the case of a loaded vessel moving out of physics range
            if (node == null)
            {
                protoHost = FTA.from;

                int id = 0;

                protoHost.moduleValues.TryGetValue("flightID", ref id);

                if (id != flightID)
                {
                    return;
                }

                //SEP_Utilities.log("Saving Handler from loaded vessel", logLevels.error);

                protoHost.moduleValues.SetValue("experimentRunning", experimentRunning.ToString());
                protoHost.moduleValues.SetValue("calibration", calibration.ToString());
                protoHost.moduleValues.SetValue("completion", completion.ToString());
                protoHost.moduleValues.SetValue("submittedData", submittedData.ToString());
                protoHost.moduleValues.SetValue("lastBackgroundCheck", lastBackgroundCheck.ToString());
                protoHost.moduleValues.SetValue("controllerAutoTransmit", controllerAutoTransmit.ToString());
                OnSave(protoHost.moduleValues);
            }
            //This is the standard method used when saving
            else
            {
                if (currentGame != null && HighLogic.LoadedScene == GameScenes.SPACECENTER)
                {
                    if (lastBackgroundCheck > currentGame.UniversalTime)
                    {
                        return;
                    }
                }

                int id = 0;

                node.TryGetValue("flightID", ref id);

                if (id != flightID)
                {
                    return;
                }

                //if (vessel.mainBody.bodyName == "Kerbin")
                //{
                //	SEP_Utilities.log("Save - Experiment: {0} - Completion: {1:P0} - Science Data: {2} - Check Time: {3:N2} - UT: {4:N2} - Game UT: {5:N2}"
                //		, logLevels.log
                //		, experimentTitle
                //		, completion
                //		, storedData.Count > 0 ? storedData[0].title : "None"
                //		, lastBackgroundCheck
                //		, Planetarium.GetUniversalTime()
                //		, currentGame == null ? -1000 : currentGame.UniversalTime);
                //}

                //SEP_Utilities.log("Saving Handler from proto vessel", logLevels.error);

                node.SetValue("experimentRunning", experimentRunning.ToString());
                node.SetValue("calibration", calibration.ToString());
                node.SetValue("completion", completion.ToString());
                node.SetValue("submittedData", submittedData.ToString());
                node.SetValue("lastBackgroundCheck", lastBackgroundCheck.ToString());
                node.SetValue("controllerAutoTransmit", controllerAutoTransmit.ToString());
                OnSave(node);
            }
        }
示例#36
0
        public static void BackgroundUpdate(Vessel v, ProtoPartModuleSnapshot m, Experiment experiment, Resource_info ec, Vessel_resources resources, double elapsed_s)
        {
            bool   didPrepare          = Lib.Proto.GetBool(m, "didPrepare", false);
            bool   shrouded            = Lib.Proto.GetBool(m, "shrouded", false);
            string last_subject_id     = Lib.Proto.GetString(m, "last_subject_id", "");
            double remainingSampleMass = Lib.Proto.GetDouble(m, "remainingSampleMass", 0);
            bool   broken      = Lib.Proto.GetBool(m, "broken", false);
            bool   forcedRun   = Lib.Proto.GetBool(m, "forcedRun", false);
            bool   recording   = Lib.Proto.GetBool(m, "recording", false);
            uint   privateHdId = Lib.Proto.GetUInt(m, "privateHdId", 0);

            string issue = TestForIssues(v, ec, experiment, privateHdId, broken,
                                         remainingSampleMass, didPrepare, shrouded, last_subject_id);

            if (string.IsNullOrEmpty(issue))
            {
                issue = TestForResources(v, ParseResources(experiment.resources), elapsed_s, resources);
            }

            Lib.Proto.Set(m, "issue", issue);

            if (!string.IsNullOrEmpty(issue))
            {
                return;
            }

            var subject_id = Science.Generate_subject_id(experiment.experiment_id, v);

            Lib.Proto.Set(m, "last_subject_id", subject_id);

            double dataSampled = Lib.Proto.GetDouble(m, "dataSampled");

            if (last_subject_id != subject_id)
            {
                dataSampled = 0;
                Lib.Proto.Set(m, "forcedRun", false);
            }

            double scienceValue = Science.Value(last_subject_id);

            Lib.Proto.Set(m, "scienceValue", scienceValue);

            var state = GetState(scienceValue, issue, recording, forcedRun);

            if (state != State.RUNNING)
            {
                return;
            }
            if (dataSampled >= Science.Experiment(subject_id).max_amount)
            {
                return;
            }

            var stored = DoRecord(experiment, subject_id, v, ec, privateHdId,
                                  resources, ParseResources(experiment.resources),
                                  remainingSampleMass, dataSampled, out dataSampled, out remainingSampleMass);

            if (!stored)
            {
                Lib.Proto.Set(m, "issue", insufficient_storage);
            }

            Lib.Proto.Set(m, "dataSampled", dataSampled);
            Lib.Proto.Set(m, "remainingSampleMass", remainingSampleMass);
        }
示例#37
0
 public static bool IsSignalProcessor(this ProtoPartModuleSnapshot ppms)
 {
     return(ppms.GetBool("IsRTSignalProcessor"));
 }
示例#38
0
        public SolarPanel(ConfigNode node, InterestedVessel vessel, ProtoPartModuleSnapshot modulesnapshot, ProtoPartSnapshot partsnapshot)
        {
            if (node == null)
            {
                Debug.Log("[UnloadedResources]: SolarPanel - Call to constructor failed. node is null.");
                return;
            }
            if (vessel == null)
            {
                Debug.Log("[UnloadedResources]: SolarPanel - Call to constructor failed. vessel is null.");
                return;
            }
            if (modulesnapshot == null)
            {
                Debug.Log("[UnloadedResources]: SolarPanel - Call to constructor failed. modulesnapshot is null.");
                return;
            }
            if (partsnapshot == null)
            {
                Debug.Log("[UnloadedResources]: SolarPanel - Call to constructor failed. partsnapshot is null.");
                return;
            }
            this.vessel     = vessel;
            this.PartModule = modulesnapshot;

            if (node.HasValue("type"))
            {
                panelType = (ModuleDeployableSolarPanel.PanelType)System.Enum.Parse(typeof(ModuleDeployableSolarPanel.PanelType), node.GetValue("type"));
            }
            node.TryGetValue("chargeRate", ref chargeRate);
            node.TryGetValue("sunAOA", ref this.sunAOA);
            node.TryGetValue("flowRate", ref this.flowRate);
            node.TryGetValue("flowMult", ref this.flowMult);
            node.TryGetValue("efficiencyMult", ref this.efficiencyMult);
            if (node.HasValue("deployState"))
            {
                deployState = (ModuleDeployablePart.DeployState)System.Enum.Parse(typeof(ModuleDeployablePart.DeployState), node.GetValue("deployState"));
            }
            if (deployState != ModuleDeployablePart.DeployState.EXTENDED)
            {
                sunAOA   = 0f;
                flowRate = 0f;
            }
            Part part = PartLoader.getPartInfoByName(partsnapshot.partName).partPrefab;

            if (part == null)
            {
                Debug.Log("[UnloadedResources]: SolarPanel - Unable to Find Part: " + partsnapshot.partName);
                return;
            }
            for (int i = 0; i < part.Modules.Count; ++i)
            {
                if (part.Modules[i].moduleName == "ModuleDeployableSolarPanel" || part.Modules[i].moduleName == "KopernicusSolarPanel")
                {
                    ModuleDeployableSolarPanel panelModule = (ModuleDeployableSolarPanel)part.Modules[i];
                    solarNormal = panelModule.part.FindModelTransform(panelModule.secondaryTransformName).forward;
                    pivotAxis   = panelModule.part.FindModelTransform(panelModule.pivotName).up;
                    sunTracking = panelModule.isTracking && panelModule.trackingMode == ModuleDeployablePart.TrackingMode.SUN;
                    usesCurve   = panelModule.useCurve;
                    tempCurve   = panelModule.temperatureEfficCurve;
                    temperature = (float)partsnapshot.temperature;
                    powerCurve  = panelModule.powerCurve;
                    position    = partsnapshot.position;
                    orientation = partsnapshot.rotation;
                    break;
                }
            }
        }
示例#39
0
 public BackgroundModule(BackgroundFunctionInfo functionInfo, Vessel vessel, ProtoPartSnapshot protoPartSnapshot, ProtoPartModuleSnapshot protoPartModuleSnapshot, Part part, PartModule partModule)
 {
     FunctionInfo            = functionInfo;
     Vessel                  = vessel;
     ProtoPartSnapshot       = protoPartSnapshot;
     ProtoPartModuleSnapshot = protoPartModuleSnapshot;
     Part       = part;
     PartModule = partModule;
 }
示例#40
0
 public ProtoRingDevice(ProtoPartModuleSnapshot ring)
 {
   this.ring = ring;
 }
示例#41
0
    public static bool ModuleInAlias(ProtoPartModuleSnapshot Module, string alias) {
      for (int i = 0; i < ModuleAliases.Length; i++) {
        ConfigNode ModuleAlias = ModuleAliases [i];

        if (ModuleAlias.GetValue ("name") == alias) {
          
          ConfigNode[] Modules = ModuleAlias.GetNode("Modules").GetNodes ();

          for (int k = 0; k < Modules.Length; k++) {
            ConfigNode Mod = Modules [k];
            if (Mod.GetValue ("name") == Module.moduleValues.GetValue("name")) {
              return true;
            }
          }
        }
      }

      return false;
    }
示例#42
0
 public BackgroundSuppliableModule(BackgroundFunctionInfo functionInfo, Vessel vessel, ProtoPartSnapshot protoPartSnapshot, ProtoPartModuleSnapshot protoPartModuleSnapshot, Part part, PartModule partModule) : base(functionInfo, vessel, protoPartSnapshot, protoPartModuleSnapshot, part, partModule)
 {
 }