public override void OnSave(ConfigNode gameNode)
        {
            try
            {
                //Other variables
                gameNode.AddValue("DisplayModeTracking", CNCCommNetUI.CustomModeTrackingStation);
                gameNode.AddValue("DisplayModeFlight", CNCCommNetUI.CustomModeFlightMap);
                gameNode.AddValue("HideGroundStations", this.hideGroundStations);

                //Constellations
                if (gameNode.HasNode("Constellations"))
                {
                    gameNode.RemoveNode("Constellations");
                }

                ConfigNode constellationNode = new ConfigNode("Constellations");
                for (int i = 0; i < constellations.Count; i++)
                {
                    ConfigNode newConstellationNode = new ConfigNode("Constellation");
                    newConstellationNode = ConfigNode.CreateConfigFromObject(constellations[i], newConstellationNode);
                    constellationNode.AddNode(newConstellationNode);
                }

                if (constellations.Count <= 0)
                {
                    CNCLog.Error("No user-defined constellations to save!");
                }
                else
                {
                    gameNode.AddNode(constellationNode);
                }

                //Ground stations
                if (gameNode.HasNode("GroundStations"))
                {
                    gameNode.RemoveNode("GroundStations");
                }

                ConfigNode stationNode = new ConfigNode("GroundStations");
                for (int i = 0; i < groundStations.Count; i++)
                {
                    ConfigNode newGroundStationNode = new ConfigNode("GroundStation");
                    newGroundStationNode = ConfigNode.CreateConfigFromObject(groundStations[i], newGroundStationNode);
                    stationNode.AddNode(newGroundStationNode);
                }

                if (groundStations.Count <= 0)
                {
                    CNCLog.Error("No ground stations to save!");
                }
                else
                {
                    gameNode.AddNode(stationNode);
                }

                CNCLog.Verbose("Scenario content to be saved:\n{0}", gameNode);
            }
            catch (Exception e)
            {
                CNCLog.Error("Error when saving CNCCommNetScenario: {0}", e.Message);
            }
        }
        protected override void Start()
        {
            CNCCommNetScenario.Instance = this;
            this.commVessels            = new List <CNCCommNetVessel>();
            this.dirtyCommNetVesselList = true;

            CNCLog.Verbose("CommNet Scenario loading ...");

            //Replace the CommNet user interface
            CommNetUI ui = FindObjectOfType <CommNetUI>();              // the order of the three lines is important

            CustomCommNetUI = gameObject.AddComponent <CNCCommNetUI>(); // gameObject.AddComponent<>() is "new" keyword for Monohebaviour class
            UnityEngine.Object.Destroy(ui);

            //Replace the CommNet network
            CommNetNetwork net = FindObjectOfType <CommNetNetwork>();

            CustomCommNetNetwork = gameObject.AddComponent <CNCCommNetNetwork>();
            UnityEngine.Object.Destroy(net);
            //CommNetNetwork.Instance.GetType().GetMethod("set_Instance").Invoke(CustomCommNetNetwork, null); // reflection to bypass Instance's protected set // don't seem to work

            //Replace the TelemetryUpdate
            TelemetryUpdate     tel      = TelemetryUpdate.Instance;                 //only appear in flight
            CommNetUIModeButton cnmodeUI = FindObjectOfType <CommNetUIModeButton>(); //only appear in tracking station; initialised separately by TelemetryUpdate in flight

            if (tel != null && HighLogic.LoadedSceneIsFlight)
            {
                TelemetryUpdateData tempData = new TelemetryUpdateData(tel);
                UnityEngine.Object.DestroyImmediate(tel); //seem like UE won't initialise CNCTelemetryUpdate instance in presence of TelemetryUpdate instance
                CustomCommNetTelemetry = gameObject.AddComponent <CNCTelemetryUpdate>();
                CustomCommNetTelemetry.copyOf(tempData);
            }
            else if (cnmodeUI != null && HighLogic.LoadedScene == GameScenes.TRACKSTATION)
            {
                CustomCommNetModeButton = cnmodeUI.gameObject.AddComponent <CNCCommNetUIModeButton>();
                CustomCommNetModeButton.copyOf(cnmodeUI);
                UnityEngine.Object.DestroyImmediate(cnmodeUI);
            }

            //Replace the CommNet ground stations
            groundStations.Clear();
            CommNetHome[] homes = FindObjectsOfType <CommNetHome>();
            for (int i = 0; i < homes.Length; i++)
            {
                CNCCommNetHome customHome = homes[i].gameObject.AddComponent(typeof(CNCCommNetHome)) as CNCCommNetHome;
                customHome.copyOf(homes[i]);
                UnityEngine.Object.Destroy(homes[i]);
                groundStations.Add(customHome);
            }
            groundStations.Sort();

            //Apply the ground-station changes from persistent.sfs
            for (int i = 0; i < persistentGroundStations.Count; i++)
            {
                if (groundStations.Exists(x => x.ID.Equals(persistentGroundStations[i].ID)))
                {
                    groundStations.Find(x => x.ID.Equals(persistentGroundStations[i].ID)).applySavedChanges(persistentGroundStations[i]);
                }
            }
            persistentGroundStations.Clear();//dont need anymore

            //Replace the CommNet celestial bodies
            CommNetBody[] bodies = FindObjectsOfType <CommNetBody>();
            for (int i = 0; i < bodies.Length; i++)
            {
                CNCCommNetBody customBody = bodies[i].gameObject.AddComponent(typeof(CNCCommNetBody)) as CNCCommNetBody;
                customBody.copyOf(bodies[i]);
                UnityEngine.Object.Destroy(bodies[i]);
            }

            CNCLog.Verbose("CommNet Scenario loading done!");
        }
        /// <summary>
        /// Check if given vessel has CNConstellationModule and its attributes required, and if not, "upgrade" the vessel data
        /// </summary>
        public void validateAndUpgrade(Vessel thisVessel)
        {
            if (thisVessel == null)
            {
                return;
            }
            if (thisVessel.loaded) // it seems KSP will automatically add/upgrade the active vessel (unconfirmed)
            {
                return;
            }

            CNCLog.Debug("Unloaded CommNet vessel '{0}' is validated and upgraded", thisVessel.GetName());

            if (thisVessel.protoVessel != null)
            {
                List <ProtoPartSnapshot> parts = thisVessel.protoVessel.protoPartSnapshots;
                for (int i = 0; i < parts.Count; i++)
                {
                    if (parts[i].FindModule("ModuleCommand") != null) // check command parts only
                    {
                        ProtoPartModuleSnapshot cncModule;
                        if ((cncModule = parts[i].FindModule("CNConstellationModule")) == null)                      //check if CNConstellationModule is there
                        {
                            CNConstellationModule realcncModule = gameObject.AddComponent <CNConstellationModule>(); // don't use new keyword. PartModule is Monobehavior
                            parts[i].modules.Add(new ProtoPartModuleSnapshot(realcncModule));

                            CNCLog.Verbose("CNConstellationModule is added to CommNet Vessel '{0}'", thisVessel.GetName());
                        }
                        else //check if all attributes are or should not be there
                        {
                            if (cncModule.moduleValues.HasValue("radioFrequency")) //obsolete
                            {
                                cncModule.moduleValues.RemoveValue("radioFrequency");
                            }

                            if (cncModule.moduleValues.HasValue("communicationMembershipFlag")) //obsolete
                            {
                                cncModule.moduleValues.RemoveValue("communicationMembershipFlag");
                            }
                        }
                    }

                    if (parts[i].FindModule("ModuleDataTransmitter") != null) // check antennas, probe cores and manned cockpits
                    {
                        ProtoPartModuleSnapshot cncModule;
                        if ((cncModule = parts[i].FindModule("CNConstellationAntennaModule")) == null)                             //check if CNConstellationAntennaModule is there
                        {
                            CNConstellationAntennaModule realcncModule = gameObject.AddComponent <CNConstellationAntennaModule>(); // don't use new keyword. PartModule is Monobehavior
                            parts[i].modules.Add(new ProtoPartModuleSnapshot(realcncModule));

                            CNCLog.Verbose("CNConstellationAntennaModule is added to CommNet Vessel '{0}'", thisVessel.GetName());
                        }
                        else //check if all attributes are or should not be there
                        {
                            if (!cncModule.moduleValues.HasValue("CosAngle"))
                            {
                                cncModule.moduleValues.AddValue("CosAngle", -1.0);
                            }
                        }
                    }
                } // end of part loop
            }
        }
        public override void OnLoad(ConfigNode gameNode)
        {
            try
            {
                CNCLog.Verbose("Scenario content to be read:\n{0}", gameNode);

                //Other variables
                for (int i = 0; i < gameNode.values.Count; i++)
                {
                    ConfigNode.Value value = gameNode.values[i];
                    string           name  = value.name;
                    switch (name)
                    {
                    case "DisplayModeTracking":
                        CNCCommNetUI.CustomModeTrackingStation = (CNCCommNetUI.CustomDisplayMode)((int)Enum.Parse(typeof(CNCCommNetUI.CustomDisplayMode), value.value));
                        break;

                    case "DisplayModeFlight":
                        CNCCommNetUI.CustomModeFlightMap = (CNCCommNetUI.CustomDisplayMode)((int)Enum.Parse(typeof(CNCCommNetUI.CustomDisplayMode), value.value));
                        break;

                    case "HideGroundStations":
                        this.hideGroundStations = Boolean.Parse(value.value);
                        break;
                    }
                }

                //Constellations
                if (gameNode.HasNode("Constellations"))
                {
                    ConfigNode   constellationNode  = gameNode.GetNode("Constellations");
                    ConfigNode[] constellationNodes = constellationNode.GetNodes();

                    if (constellationNodes.Length < 1) // missing constellation list
                    {
                        CNCLog.Error("The 'Constellations' node is malformed! Reverted to the default constellation list.");
                        constellations = CNCSettings.Instance.Constellations;
                    }
                    else
                    {
                        constellations.Clear();
                        for (int i = 0; i < constellationNodes.Length; i++)
                        {
                            Constellation newConstellation = new Constellation();
                            ConfigNode.LoadObjectFromConfig(newConstellation, constellationNodes[i]);
                            constellations.Add(newConstellation);
                        }
                    }
                }
                else
                {
                    CNCLog.Verbose("The 'Constellations' node is not found. The default constellation list is loaded.");
                    constellations = CNCSettings.Instance.Constellations;
                }

                constellations.Sort();

                //Ground stations
                if (gameNode.HasNode("GroundStations"))
                {
                    ConfigNode   stationNode  = gameNode.GetNode("GroundStations");
                    ConfigNode[] stationNodes = stationNode.GetNodes();

                    if (stationNodes.Length < 1) // missing ground-station list
                    {
                        CNCLog.Error("The 'GroundStations' node is malformed! Reverted to the default list of ground stations.");
                        //do nothing since KSP provides this default list
                    }
                    else
                    {
                        persistentGroundStations.Clear();
                        for (int i = 0; i < stationNodes.Length; i++)
                        {
                            CNCCommNetHome dummyGroundStation = new CNCCommNetHome();
                            ConfigNode.LoadObjectFromConfig(dummyGroundStation, stationNodes[i]);
                            if (!stationNodes[i].HasNode("Frequencies")) // empty list is not saved as empty node in persistent.sfs
                            {
                                dummyGroundStation.deleteFrequencies();  // clear the default frequency list
                            }
                            persistentGroundStations.Add(dummyGroundStation);
                        }
                    }
                }
                else
                {
                    CNCLog.Verbose("The 'GroundStations' node is not found. The default list of ground stations is loaded from KSP's data.");
                    //do nothing since KSP provides this default list
                }
            }
            catch (Exception e)
            {
                CNCLog.Error("Error when loading CNCCommNetScenario: {0}", e.Message);
            }
        }
        /// <summary>
        /// Read the part data of an unloaded/loaded vessel and store in data structures
        /// </summary>
        protected List <CNCAntennaPartInfo> readAntennaData()
        {
            List <CNCAntennaPartInfo> antennas = new List <CNCAntennaPartInfo>();
            int numParts = (!this.vessel.loaded) ? this.vessel.protoVessel.protoPartSnapshots.Count : this.vessel.Parts.Count;

            //inspect each part
            for (int partIndex = 0; partIndex < numParts; partIndex++)
            {
                Part thisPart;
                ProtoPartSnapshot partSnapshot = null;

                if (this.Vessel.loaded)
                {
                    thisPart = this.vessel.Parts[partIndex];
                }
                else
                {
                    partSnapshot = this.vessel.protoVessel.protoPartSnapshots[partIndex];
                    thisPart     = partSnapshot.partInfo.partPrefab;
                }

                bool populatedAntennaInfo = false;
                CNCAntennaPartInfo      newAntennaPartInfo = new CNCAntennaPartInfo();;
                ProtoPartModuleSnapshot partModuleSnapshot = null;

                //inspect each module of the part
                for (int moduleIndex = 0; moduleIndex < thisPart.Modules.Count; moduleIndex++)
                {
                    PartModule thisPartModule = thisPart.Modules[moduleIndex];

                    if (thisPartModule is CNConstellationAntennaModule) // is it CNConstellationAntennaModule?
                    {
                        if (!this.Vessel.loaded)
                        {
                            partModuleSnapshot = partSnapshot.FindModule(thisPartModule, moduleIndex);

                            newAntennaPartInfo.frequency = short.Parse(partModuleSnapshot.moduleValues.GetValue("Frequency"));
                            string oname = partModuleSnapshot.moduleValues.GetValue("OptionalName");
                            newAntennaPartInfo.name     = (oname.Length == 0) ? partSnapshot.partInfo.title : oname;
                            newAntennaPartInfo.inUse    = bool.Parse(partModuleSnapshot.moduleValues.GetValue("InUse"));
                            newAntennaPartInfo.CosAngle = double.Parse(partModuleSnapshot.moduleValues.GetValue("CosAngle"));
                        }
                        else
                        {
                            CNConstellationAntennaModule antennaMod = (CNConstellationAntennaModule)thisPartModule;
                            newAntennaPartInfo.frequency = antennaMod.Frequency;
                            newAntennaPartInfo.name      = antennaMod.Name;
                            newAntennaPartInfo.inUse     = antennaMod.InUse;
                        }

                        populatedAntennaInfo = true;
                    }
                    else if (thisPartModule is ICommAntenna) // is it ModuleDataTransmitter?
                    {
                        ICommAntenna thisAntenna = thisPartModule as ICommAntenna;

                        if (!this.Vessel.loaded)
                        {
                            partModuleSnapshot = partSnapshot.FindModule(thisPartModule, moduleIndex);
                        }

                        newAntennaPartInfo.antennaPower              = (!this.vessel.loaded) ? thisAntenna.CommPowerUnloaded(partModuleSnapshot) : thisAntenna.CommPower;
                        newAntennaPartInfo.antennaCombinable         = thisAntenna.CommCombinable;
                        newAntennaPartInfo.antennaCombinableExponent = thisAntenna.CommCombinableExponent;
                        newAntennaPartInfo.antennaType           = thisAntenna.CommType;
                        newAntennaPartInfo.partReference         = thisPart; //unique ID for part is not available
                        newAntennaPartInfo.partSnapshotReference = partSnapshot;
                        newAntennaPartInfo.canComm = (!this.vessel.loaded) ? thisAntenna.CanCommUnloaded(partModuleSnapshot) : thisAntenna.CanComm();

                        populatedAntennaInfo = true;
                    }
                }

                if (populatedAntennaInfo) // valid info?
                {
                    antennas.Add(newAntennaPartInfo);
                    CNCLog.Debug("CommNet Vessel '{0}' has antenna '{1}' of {2} and {3} power (w/o range modifier)", this.Vessel.GetName(), newAntennaPartInfo.name, newAntennaPartInfo.frequency, newAntennaPartInfo.antennaPower);
                }
            }

            return(antennas);
        }
Example #6
0
 /// <summary>
 /// Action to remove the particular frequency from the station's list
 /// </summary>
 private void deleteFreqClick(short frequency)
 {
     this.freqListShown.Remove(frequency);
     CNCLog.Debug("Removed g-station freq: {0}", frequency);
     refreshList(this.freqListShown);
 }
        /// <summary>
        /// Action to update the attributes of the antenna
        /// </summary>
        private void updateAction()
        {
            try
            {
                try
                {
                    bool   changesCommitted = false;
                    short  inputFreq        = short.Parse(frequencyInput.uiItem.GetComponent <TMP_InputField>().text);
                    string inputName        = nameInput.uiItem.GetComponent <TMP_InputField>().text.Trim();

                    //Check name
                    if (inputName.Length <= 0)
                    {
                        throw new Exception(Localizer.Format("#CNC_CheckName_Empty"));//"Name cannot be empty"
                    }

                    //Check frequency
                    if (inputFreq < 0)
                    {
                        throw new Exception(Localizer.Format("#CNC_CheckFrequency_negative"));//"Frequency cannot be negative"
                    }
                    else if (!GameUtils.NonLinqAny(CNCCommNetScenario.Instance.constellations, inputFreq))
                    {
                        throw new Exception(Localizer.Format("#CNC_CheckFrequency_Exist"));//"Please choose an existing constellation"
                    }
                    else if (!Constellation.isFrequencyValid(inputFreq))
                    {
                        throw new Exception(Localizer.Format("#CNC_CheckFrequency_Valid", short.MaxValue));//"Frequency must be between 0 and " +
                    }

                    //ALL OK
                    if (this.antennaModule.Frequency != inputFreq) // different frequency
                    {
                        this.antennaModule.Frequency = inputFreq;
                        ScreenMessage msg = new ScreenMessage(Localizer.Format("#CNC_ScreenMsg_FreqUpdate", inputFreq), CNCSettings.ScreenMessageDuration, ScreenMessageStyle.UPPER_CENTER);//string.Format("Frequency is updated to {0}", )
                        ScreenMessages.PostScreenMessage(msg);
                        changesCommitted = true;
                    }

                    if (!this.antennaModule.Name.Equals(inputName)) // different name
                    {
                        this.antennaModule.Name = inputName;
                        ScreenMessage msg = new ScreenMessage(Localizer.Format("#CNC_ScreenMsg_NameUpdate", this.antennaModule.Name), CNCSettings.ScreenMessageDuration, ScreenMessageStyle.UPPER_CENTER);//string.Format("Antenna is renamed to '{0}'", )
                        ScreenMessages.PostScreenMessage(msg);
                        changesCommitted = true;
                    }

                    CNCLog.Debug("Updated antenna: {0}, {1}", inputName, inputFreq);

                    if (changesCommitted)
                    {
                        if (this.hostVessel != null)
                        {
                            CNCCommNetVessel cncVessel = (CNCCommNetVessel)this.hostVessel.Connection;
                            cncVessel.OnAntennaChange();
                        }

                        this.dismiss();
                    }
                }
                catch (FormatException e)
                {
                    throw new FormatException(Localizer.Format("#CNC_CheckFrequency_Format"));//"Frequency must be numeric only"
                }
                catch (OverflowException e)
                {
                    throw new OverflowException(Localizer.Format("#CNC_CheckFrequency_Overflow", short.MaxValue));//string.Format("Frequency must be equal to or less than {0}", )
                }
            }
            catch (Exception e)
            {
                ScreenMessage msg = new ScreenMessage("<color=red>" + e.Message + "</color>", CNCSettings.ScreenMessageDuration, ScreenMessageStyle.UPPER_CENTER);
                ScreenMessages.PostScreenMessage(msg);
            }
        }
        protected override void Start()
        {
            CNCCommNetScenario.Instance = this;
            this.commVessels            = new List <CNCCommNetVessel>();
            this.dirtyCommNetVesselList = true;

            CNCLog.Verbose("CommNet Scenario loading ...");

            //Issue #13: Commnet behaves like vanilla when joining a DMP server for the second time.
            //if stock CommNet logic somehow runs (such as the order of CNCCommNetScenario and CommNetScenario in persisten.sfs)
            if (CommNetScenario.Instance != null)
            {
                UnityEngine.Object.DestroyImmediate(CommNetScenario.Instance);
                CNCCommNetScenario.Instance = this;
            }

            //Replace the CommNet user interface
            CommNetUI ui = FindObjectOfType <CommNetUI>();              // the order of the three lines is important

            CustomCommNetUI = gameObject.AddComponent <CNCCommNetUI>(); // gameObject.AddComponent<>() is "new" keyword for Monohebaviour class
            UnityEngine.Object.Destroy(ui);

            //Replace the CommNet network
            CommNetNetwork net = FindObjectOfType <CommNetNetwork>();

            CustomCommNetNetwork = gameObject.AddComponent <CNCCommNetNetwork>();
            UnityEngine.Object.Destroy(net);

            //Replace the TelemetryUpdate
            TelemetryUpdate     tel      = TelemetryUpdate.Instance;                 //only appear in flight
            CommNetUIModeButton cnmodeUI = FindObjectOfType <CommNetUIModeButton>(); //only appear in tracking station; initialised separately by TelemetryUpdate in flight

            if (tel != null && HighLogic.LoadedSceneIsFlight)
            {
                TelemetryUpdateData tempData = new TelemetryUpdateData(tel);
                UnityEngine.Object.DestroyImmediate(tel); //seem like UE won't initialise CNCTelemetryUpdate instance in presence of TelemetryUpdate instance
                CustomCommNetTelemetry = gameObject.AddComponent <CNCTelemetryUpdate>();
                CustomCommNetTelemetry.copyOf(tempData);
            }
            else if (cnmodeUI != null && HighLogic.LoadedScene == GameScenes.TRACKSTATION)
            {
                CustomCommNetModeButton = cnmodeUI.gameObject.AddComponent <CNCCommNetUIModeButton>();
                CustomCommNetModeButton.copyOf(cnmodeUI);
                UnityEngine.Object.DestroyImmediate(cnmodeUI);
            }

            //Replace the CommNet ground stations
            groundStations.Clear();
            CommNetHome[] homes = FindObjectsOfType <CommNetHome>();
            for (int i = 0; i < homes.Length; i++)
            {
                CNCCommNetHome customHome = homes[i].gameObject.AddComponent(typeof(CNCCommNetHome)) as CNCCommNetHome;
                customHome.copyOf(homes[i]);
                UnityEngine.Object.Destroy(homes[i]);
                groundStations.Add(customHome);
            }
            groundStations.Sort();

            //Apply the ground-station changes from persistent.sfs
            for (int i = 0; i < persistentGroundStations.Count; i++)
            {
                if (!groundStations.Exists(x => x.ID.Equals(persistentGroundStations[i].ID)))        //need to create ground stations
                {
                    var stockStation = groundStations.Find(x => x.ID.Equals("Kerbin: Baikerbanur")); //not recommended to use KSC as it has additional properties like SurfaceObject (camera)
                    //var additionalHome = ksc.gameObject.AddComponent<RemoteTechCommNetHome>(); //fail
                    //var additionalHome = ksc.gameObject.AddComponent(typeof(RemoteTechCommNetHome)) as RemoteTechCommNetHome; //fail
                    //var additionalHome = gameObject.AddComponent<RemoteTechCommNetHome>(); //working but transform reference reused
                    var additionalStation = UnityEngine.Object.Instantiate <CNCCommNetHome>(stockStation); //working
                    additionalStation.ID    = additionalStation.nodeName = additionalStation.displaynodeName = persistentGroundStations[i].ID;
                    additionalStation.isKSC = false;
                    groundStations.Add(additionalStation);

                    CNCLog.Verbose("Custom CommNet Home '{0}' added", persistentGroundStations[i].ID);
                }

                groundStations.Find(x => x.ID.Equals(persistentGroundStations[i].ID)).applySavedChanges(persistentGroundStations[i]);
            }
            persistentGroundStations.Clear();//dont need anymore

            //Replace the CommNet celestial bodies
            CommNetBody[] bodies = FindObjectsOfType <CommNetBody>();
            for (int i = 0; i < bodies.Length; i++)
            {
                CNCCommNetBody customBody = bodies[i].gameObject.AddComponent(typeof(CNCCommNetBody)) as CNCCommNetBody;
                customBody.copyOf(bodies[i]);
                UnityEngine.Object.Destroy(bodies[i]);
            }

            //Imitate stock CommNetScenario.Instance in order to run certain stock functionalities
            //Comment: Vessel.GetControlLevel() has the check on CommNetScenario.Instance != null before calling vessel.connection.GetControlLevel()
            PropertyInfo property = typeof(CommNetScenario).GetProperty("Instance");

            property.DeclaringType.GetProperty("Instance");
            property.SetValue(CommNetScenario.Instance, this, BindingFlags.NonPublic | BindingFlags.Instance, null, null, null);

            //Imitate stock CommNetNetwork.Instance
            if (CustomCommNetNetwork != null)
            {
                PropertyInfo property2 = typeof(CommNetNetwork).GetProperty("Instance");
                property2.DeclaringType.GetProperty("Instance");
                property2.SetValue(CommNetNetwork.Instance, CustomCommNetNetwork, BindingFlags.NonPublic | BindingFlags.Instance, null, null, null);
            }

            CNCLog.Verbose("CommNet Scenario loading done!");
        }
Example #9
0
        /// <summary>
        /// Action to create or update the constellation
        /// </summary>
        private void actionClick()
        {
            try
            {
                try
                {
                    short  constellFreq = short.Parse(frequencyInput.uiItem.GetComponent <TMP_InputField>().text);
                    string constellName = nameInput.uiItem.GetComponent <TMP_InputField>().text;

                    //Check name
                    if (constellName.Length <= 0)
                    {
                        throw new Exception(Localizer.Format("#CNC_CheckName_Empty"));//"Name cannot be empty"
                    }

                    //Check frequency
                    if (constellFreq < 0)
                    {
                        throw new Exception(Localizer.Format("#CNC_CheckFrequency_negative"));//"Frequency cannot be negative"
                    }
                    else if (!Constellation.isFrequencyValid(constellFreq))
                    {
                        throw new Exception(Localizer.Format("#CNC_CheckFrequency_Valid", short.MaxValue));//"Frequency must be between 0 and " +
                    }
                    else if (this.existingConstellation != null)
                    {
                        if (this.existingConstellation.frequency == CNCSettings.Instance.PublicRadioFrequency) //public one
                        {
                            if (constellFreq != CNCSettings.Instance.PublicRadioFrequency)
                            {
                                throw new Exception(Localizer.Format("#CNC_CheckFrequency_Locked", CNCSettings.Instance.PublicRadioFrequency));//"Public frequency " +  + " is locked"
                            }
                        }

                        /*
                         * else if(constellFreq == CNCSettings.Instance.PublicRadioFrequency) // not public but new freq is public
                         * {
                         *  throw new Exception("New frequency cannot be " + CNCSettings.Instance.PublicRadioFrequency);
                         * }
                         */
                        else if (GameUtils.NonLinqAny(CNCCommNetScenario.Instance.constellations, constellFreq) && this.existingConstellation.frequency != constellFreq)
                        {
                            throw new Exception(Localizer.Format("#CNC_CheckFrequency_InUse"));//"Frequency is in use already"
                        }
                    }
                    else if (this.existingConstellation == null && GameUtils.NonLinqAny(CNCCommNetScenario.Instance.constellations, constellFreq))
                    {
                        throw new Exception(Localizer.Format("#CNC_CheckFrequency_InUse"));//"Frequency is in use already"
                    }

                    //ALL OK
                    if (this.existingConstellation == null && creationCallback != null)
                    {
                        Constellation newConstellation = new Constellation(constellFreq, constellName, this.constellColor);
                        CNCCommNetScenario.Instance.constellations.Add(newConstellation);
                        creationCallback(newConstellation);

                        string message = Localizer.Format("#CNC_ScreenMsg_ConstellationCreated", constellName, constellFreq);//string.Format("New constellation '{0}' of frequency {1} is created", )
                        ScreenMessages.PostScreenMessage(new ScreenMessage(message, CNCSettings.ScreenMessageDuration, ScreenMessageStyle.UPPER_CENTER));

                        CNCLog.Debug("New constellation: {0}, {1}", constellName, constellFreq);

                        this.dismiss();
                    }
                    else if (this.existingConstellation != null && updateCallback != null)
                    {
                        bool  changesCommitted = false;
                        short prevFreq         = this.existingConstellation.frequency;

                        if (this.existingConstellation.frequency != constellFreq) // new frequency
                        {
                            this.existingConstellation.frequency = constellFreq;

                            List <CNCCommNetVessel> affectedVessels = CNCCommNetScenario.Instance.getCommNetVessels().FindAll(x => x.getFrequencyList().Contains(prevFreq));
                            for (int i = 0; i < affectedVessels.Count; i++)
                            {
                                affectedVessels[i].replaceAllFrequencies(prevFreq, this.existingConstellation.frequency);
                                affectedVessels[i].OnAntennaChange();
                            }

                            List <CNCCommNetHome> affectedStations = CNCCommNetScenario.Instance.groundStations.FindAll(x => x.getFrequencyList().Contains(prevFreq));
                            for (int i = 0; i < affectedStations.Count; i++)
                            {
                                affectedStations[i].replaceFrequency(prevFreq, this.existingConstellation.frequency);
                            }

                            ScreenMessage msg = new ScreenMessage(Localizer.Format("#CNC_ScreenMsg_ConstellationFreqUpdate", constellFreq), CNCSettings.ScreenMessageDuration, ScreenMessageStyle.UPPER_CENTER);//string.Format("Constellation has the new frequency {0}", )
                            ScreenMessages.PostScreenMessage(msg);
                            changesCommitted = true;
                        }

                        if (!this.existingConstellation.name.Equals(constellName)) // different name
                        {
                            this.existingConstellation.name = constellName;
                            string message = Localizer.Format("#CNC_ScreenMsg_ConstellationNameUpdate", constellName);//string.Format("Constellation is renamed to '{0}'", )
                            ScreenMessages.PostScreenMessage(new ScreenMessage(message, CNCSettings.ScreenMessageDuration, ScreenMessageStyle.UPPER_CENTER));
                            changesCommitted = true;
                        }

                        if (!this.existingConstellation.color.Equals(this.constellColor)) // new color
                        {
                            this.existingConstellation.color = this.constellColor;
                            string message = Localizer.Format("#CNC_ScreenMsg_ConstellationColorUpdate", UIUtils.colorToHex(this.constellColor));//string.Format("Constellation color becomes '{0}'", )
                            ScreenMessages.PostScreenMessage(new ScreenMessage(message, CNCSettings.ScreenMessageDuration, ScreenMessageStyle.UPPER_CENTER));
                            changesCommitted = true;
                        }

                        CNCLog.Debug("Updated constellation: {0}, {1}", constellName, constellFreq);

                        if (changesCommitted)
                        {
                            updateCallback(this.existingConstellation, prevFreq);
                            this.dismiss();
                        }
                    }
                }
                catch (FormatException e)
                {
                    throw new FormatException(Localizer.Format("#CNC_CheckFrequency_Format"));//"Frequency must be numeric only"
                }
                catch (OverflowException e)
                {
                    throw new OverflowException(Localizer.Format("#CNC_CheckFrequency_Overflow", short.MaxValue));//string.Format("Frequency must be equal to or less than {0}", )
                }
            }
            catch (Exception e)
            {
                ScreenMessage msg = new ScreenMessage("<color=red>" + e.Message + "</color>", CNCSettings.ScreenMessageDuration, ScreenMessageStyle.UPPER_CENTER);
                ScreenMessages.PostScreenMessage(msg);
            }
        }