Beispiel #1
0
        public static void CreateSatellite(string satName, double orbitPeriod, double eccentricity, double inclination, double rightAscension, double meanAnomaly, double argOfPerigee)
        {
            AgStkObjectRoot root;
            AgUiApplication app;

            app = System.Runtime.InteropServices.Marshal.GetActiveObject("STK11.Application") as AGI.Ui.Application.AgUiApplication;
            root = (AgStkObjectRoot)app.Personality2;
    
            // new satellite
            IAgSatellite sat = root.CurrentScenario.Children.New(AgESTKObjectType.eSatellite, satName) as IAgSatellite;

            // set the propagator to J2
            sat.SetPropagatorType(AgEVePropagatorType.ePropagatorJ2Perturbation);

            // get the propagator
            IAgVePropagatorJ2Perturbation j2 = (IAgVePropagatorJ2Perturbation) sat.Propagator;


            //Define the satellite's orbit using classical (Keplerian) orbital elements
            IAgOrbitStateClassical classical = (IAgOrbitStateClassical) j2.InitialState.Representation.ConvertTo(AgEOrbitStateType.eOrbitStateClassical);

            //Use period and eccentricity to define the size and shape of the orbit
            classical.SizeShapeType = AgEClassicalSizeShape.eSizeShapePeriod;
            IAgClassicalSizeShapePeriod period = (IAgClassicalSizeShapePeriod)classical.SizeShape;
            period.Eccentricity = eccentricity;
            period.Period = orbitPeriod;

            //Use argument of perigee, inclination and RAAN to define the orientation of the orbit
            classical.Orientation.ArgOfPerigee = argOfPerigee;
            classical.Orientation.Inclination = inclination;
            classical.Orientation.AscNodeType = AgEOrientationAscNode.eAscNodeRAAN;
            IAgOrientationAscNodeRAAN raan = (IAgOrientationAscNodeRAAN)classical.Orientation.AscNode;
            raan.Value = rightAscension;

            //Use mean anomaly to specify the position of the satellite in orbit
            classical.LocationType = AgEClassicalLocation.eLocationMeanAnomaly;
            IAgClassicalLocationMeanAnomaly ma = (IAgClassicalLocationMeanAnomaly)classical.Location;
            ma.Value = meanAnomaly;

            //Assign the orbital elements to the satellite's propagator and propagate the orbit	
            j2.InitialState.Representation.Assign(classical);
            j2.Propagate();
        }
Beispiel #2
0
        //create satellite function
        private void CreateSatellite(string objID, string source, string fpath)
        {
            string sname = objID + "_" + source.Replace(' ', '_').Trim();

            if (!stkRoot.CurrentScenario.Children.Contains(AgESTKObjectType.eSatellite, sname))
            {
                //create new if non-existant
                stkRoot.CurrentScenario.Children.New(AgESTKObjectType.eSatellite, sname);
            }

            //handle to satellite
            IAgSatellite zsat = stkRoot.CurrentScenario.Children[sname] as IAgSatellite;

            zsat.SetPropagatorType(AgEVePropagatorType.ePropagatorSGP4);
            IAgVePropagatorSGP4 tleprop = zsat.Propagator as IAgVePropagatorSGP4;

            tleprop.Segments.RemoveAllSegs();//clear before adding new
            tleprop.CommonTasks.AddSegsFromFile(objID, fpath);
            tleprop.Propagate();
        }
Beispiel #3
0
        private void DisplaySelected_Click(object sender, EventArgs e)
        {
            if (listView1.FocusedItem != null && listView1.FocusedItem.Index != -1)
            {
                if (CommonData.HasManeuvers)
                {
                    IAgStkObject passiveSatObj = CreatorFunctions.GetCreateSatellite("PassiveCheck");
                    IAgSatellite passiveSat    = passiveSatObj as IAgSatellite;
                    passiveSat.VO.OrbitSystems.InertialByWindow.IsVisible = false;
                    passiveSat.VO.OrbitSystems.RemoveAll();
                    passiveSat.VO.OrbitSystems.Add("Satellite/" + CommonData.TargetName + " VVLH System");
                    passiveSat.SetPropagatorType(AgEVePropagatorType.ePropagatorAstrogator);
                    IAgVADriverMCS passiveDriver = passiveSat.Propagator as IAgVADriverMCS;

                    IAgVAMCSInitialState          intState = passiveDriver.MainSequence[0] as IAgVAMCSInitialState;
                    IAgVAMCSPropagate             prop     = passiveDriver.MainSequence[1] as IAgVAMCSPropagate;
                    IAgVAStoppingConditionElement sc1      = prop.StoppingConditions[0];
                    IAgVAStoppingCondition        sc       = sc1.Properties as IAgVAStoppingCondition;
                    sc.Trip = CommonData.RunList[listView1.FocusedItem.Index].PropTime;

                    AgVAElementCartesian element = intState.Element as AgVAElementCartesian;
                    intState.OrbitEpoch = CommonData.RunList[listView1.FocusedItem.Index].ManeuverTime;
                    element.Vx          = CommonData.RunList[listView1.FocusedItem.Index].Vx;
                    element.Vy          = CommonData.RunList[listView1.FocusedItem.Index].Vy;
                    element.Vz          = CommonData.RunList[listView1.FocusedItem.Index].Vz;
                    element.X           = CommonData.RunList[listView1.FocusedItem.Index].X;
                    element.Y           = CommonData.RunList[listView1.FocusedItem.Index].Y;
                    element.Z           = CommonData.RunList[listView1.FocusedItem.Index].Z;

                    passiveDriver.RunMCS();
                }
                else
                {
                    MessageBox.Show("Actor satellite has no maneuvers. Visualization is simply the Actor's current trjectory");
                }
            }
        }
        //create satellite function
        private void CreateSatellite(string objId, string source, string fpath)
        {
            IAgStkObject sat = null;

            try
            {
                string sname = objId + "_" + source.Replace(' ', '_').Trim();

                //create new if non-existant or get handle
                sat = CreatorFunctions.GetCreateSatellite(sname);

                //handle to satellite
                IAgSatellite zsat = sat as IAgSatellite;
                //Erase old TLE data and replace it with new data from specified file
                zsat.SetPropagatorType(AgEVePropagatorType.ePropagatorSGP4);
                IAgVePropagatorSGP4 tleprop = zsat.Propagator as IAgVePropagatorSGP4;
                tleprop.Segments.RemoveAllSegs();//clear before adding new
                tleprop.CommonTasks.AddSegsFromFile(objId, fpath);
                tleprop.Propagate();
                zsat.Graphics.Resolution.Orbit = 10;


                if (CoordSystem.SelectedIndex == 0)
                {
                    zsat.VO.OrbitSystems.FixedByWindow.IsVisible    = true;
                    zsat.VO.OrbitSystems.InertialByWindow.IsVisible = false;
                    string cmd = "VO */Satellite/" + sname + " ModelDetail Set ModelLabel 2000000000 MarkerLabel 2000000000";
                    try
                    {
                        CommonData.StkRoot.ExecuteCommand(cmd);
                    }
                    catch (Exception)
                    {
                    }
                }

                //Place into constellation
                IAgConstellation assets = null;
                if ((string)ConstType.SelectedItem == "Default Constellation")
                {
                    IAgStkObject conste = CreatorFunctions.GetCreateConstellation("Assets");
                    assets = conste as IAgConstellation;
                }
                else if ((string)ConstType.SelectedItem == "Existing Constellation")
                {
                    assets = (IAgConstellation)CommonData.StkRoot.GetObjectFromPath("Constellation/" + ExistingConst.Text);
                }
                else if ((string)ConstType.SelectedItem == "New Constellation")
                {
                    IAgStkObject conste = CreatorFunctions.GetCreateConstellation(ConstName.Text.Replace(" ", "_"));
                    assets = conste as IAgConstellation;
                }
                string objPath = "Satellite/" + sname;
                if (assets.Objects.IndexOf(objPath) == -1 && assets != null)
                {
                    assets.Objects.Add(objPath);
                }
            }
            catch (Exception ex)
            {
                //Identify the satellite with an issue
                MessageBox.Show(ex.Message + "\n" + "SSC: " + objId);
                //unload satellite if possible so there is not an empty object in STK from an error
                //try
                //{
                //    sat.Unload();
                //}
                //catch (Exception)
                //{
                //}
            }
        }
        private void Generate_Click(object sender, EventArgs e)
        {
            CommonData.StkRoot.ExecuteCommand("BatchGraphics * On");
            IAgConstellation myConst;

            if ((string)ImportType.SelectedItem == "TLE/TCE")
            {
                string      filepath      = TCEFile.Text;
                IAgScenario scenario      = (IAgScenario)CommonData.StkRoot.CurrentScenario;
                string      startTime     = scenario.StartTime;
                string      stopTime      = scenario.StopTime;
                string      constellation = null;
                string      cmd;

                try
                {
                    IAgExecCmdResult result = CommonData.StkRoot.ExecuteCommand("DoesObjExist / */Constellation/Assets");
                    if ((string)ConstType.SelectedItem == "Default Constellation")
                    {
                        if (result[0] == "0")
                        {
                            IAgConstellation assets = (IAgConstellation)CommonData.StkRoot.CurrentScenario.Children.New(AgESTKObjectType.eConstellation, "Assets");
                        }
                        constellation = "Assets";
                    }
                    else if ((string)ConstType.SelectedItem == "Existing Constellation")
                    {
                        result = CommonData.StkRoot.ExecuteCommand("DoesObjExist / */Constellation/" + ExistingConst.Text);
                        if (result[0] == "0")
                        {
                            IAgConstellation assets = (IAgConstellation)CommonData.StkRoot.CurrentScenario.Children.New(AgESTKObjectType.eConstellation, ExistingConst.Text);
                        }
                        constellation = ExistingConst.Text;
                    }
                    else if ((string)ConstType.SelectedItem == "New Constellation")
                    {
                        result = CommonData.StkRoot.ExecuteCommand("DoesObjExist / */Constellation/" + ConstName.Text);
                        if (result[0] == "0")
                        {
                            IAgConstellation assets = (IAgConstellation)CommonData.StkRoot.CurrentScenario.Children.New(AgESTKObjectType.eConstellation, ConstName.Text);
                        }
                        constellation = ConstName.Text;
                    }
                    //must parse satellites into constellation because of bug associated with ImportTLEFile connect command
                    //Get list of sats prior to import
                    result = CommonData.StkRoot.ExecuteCommand("ShowNames * Class Satellite");
                    string[] prevSatArray = null;
                    if (result[0] != "None")
                    {
                        prevSatArray = result[0].Split(null);
                    }

                    //Import TLE
                    cmd = "ImportTLEFile * " + "\"" + filepath + "\"" + " AutoPropagate On TimeStep 30.0 StartStop " + "\"" + startTime + "\" " + "\"" + stopTime + "\"";
                    CommonData.StkRoot.ExecuteCommand(cmd);

                    myConst = CommonData.StkRoot.GetObjectFromPath("Constellation/" + constellation) as IAgConstellation;
                    IAgSatellite sat;
                    //Compare prev satellite list to new satellite list
                    result = CommonData.StkRoot.ExecuteCommand("ShowNames * Class Satellite");
                    string[] newSatArray = null;
                    if (result[0] != "None")
                    {
                        newSatArray = result[0].Split(null);
                    }
                    if (prevSatArray == null)
                    {
                        if (newSatArray != null)
                        {
                            foreach (var item in newSatArray)
                            {
                                if (item != "")
                                {
                                    string newItem = item.Split('/').Last();
                                    string objPath = "Satellite/" + newItem;
                                    myConst.Objects.Add(objPath);
                                    sat = CommonData.StkRoot.GetObjectFromPath(item.ToString()) as IAgSatellite;
                                    if (CoordSystem.SelectedIndex == 0)
                                    {
                                        sat.VO.OrbitSystems.FixedByWindow.IsVisible    = true;
                                        sat.VO.OrbitSystems.InertialByWindow.IsVisible = false;
                                    }
                                    cmd = "VO */" + item.ToString() + " ModelDetail Set ModelLabel 2000000000 MarkerLabel 2000000000";
                                    CommonData.StkRoot.ExecuteCommand(cmd);
                                }
                            }
                        }
                    }
                    else
                    {
                        bool exists = false;
                        foreach (var newSat in newSatArray)
                        {
                            if (newSat != "")
                            {
                                exists = false;
                                foreach (var prevSat in prevSatArray)
                                {
                                    if (prevSat == newSat)
                                    {
                                        exists = true;
                                    }
                                }
                                if (exists != true)
                                {
                                    string newItem = newSat.Split('/').Last();
                                    string objPath = "Satellite/" + newItem;
                                    myConst.Objects.Add(objPath);
                                    sat = CommonData.StkRoot.GetObjectFromPath(objPath) as IAgSatellite;
                                    if (CoordSystem.SelectedIndex == 0)
                                    {
                                        sat.VO.OrbitSystems.FixedByWindow.IsVisible    = true;
                                        sat.VO.OrbitSystems.InertialByWindow.IsVisible = false;
                                    }
                                    cmd = "VO */" + objPath + " ModelDetail Set ModelLabel 2000000000 MarkerLabel 2000000000";
                                    CommonData.StkRoot.ExecuteCommand(cmd);
                                }
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show("Could not load asset(s)");
                }
            }
            else if ((string)ImportType.SelectedItem == "Orbital Elements")
            {
                int check = FieldCheck();
                if (check == 0)
                {
                    int errorNum = 0;
                    try
                    {
                        errorNum = 1;
                        IAgStkObject sat   = CreatorFunctions.GetCreateSatellite(NameValue.Text);
                        IAgSatellite mySat = sat as IAgSatellite;
                        if (CoordSystem.SelectedIndex == 0)
                        {
                            mySat.VO.OrbitSystems.FixedByWindow.IsVisible    = true;
                            mySat.VO.OrbitSystems.InertialByWindow.IsVisible = false;
                            string cmd = "VO */Satellite/" + NameValue.Text + " ModelDetail Set ModelLabel 2000000000 MarkerLabel 2000000000";
                            CommonData.StkRoot.ExecuteCommand(cmd);
                        }
                        ((IAgSatellite)mySat).SetPropagatorType(AgEVePropagatorType.ePropagatorJ2Perturbation);
                        IAgOrbitStateClassical keplerian;
                        keplerian = ((IAgOrbitStateClassical)((IAgVePropagatorJ2Perturbation)((IAgSatellite)mySat).Propagator).InitialState.Representation.ConvertTo(AgEOrbitStateType.eOrbitStateClassical));
                        keplerian.SizeShapeType = AgEClassicalSizeShape.eSizeShapeSemimajorAxis;
                        ((IAgVePropagatorJ2Perturbation)((IAgSatellite)mySat).Propagator).InitialState.Representation.AssignClassical(AgECoordinateSystem.eCoordinateSystemICRF, Double.Parse(SMAValue.Text), Double.Parse(EccValue.Text), Double.Parse(IncValue.Text), Double.Parse(AoPValue.Text), Double.Parse(RAANValue.Text), Double.Parse(TAValue.Text));
                        ((IAgVePropagatorJ2Perturbation)((IAgSatellite)mySat).Propagator).Propagate();
                        IAgExecCmdResult result = CommonData.StkRoot.ExecuteCommand("DoesObjExist / */Constellation/Assets");
                        errorNum = 2;
                        if ((string)ConstType.SelectedItem == "Default Constellation")
                        {
                            IAgStkObject     conste = CreatorFunctions.GetCreateConstellation("Assets");
                            IAgConstellation assets = conste as IAgConstellation;

                            string objPath = "Satellite/" + NameValue.Text;
                            assets.Objects.Add(objPath);
                        }
                        else if ((string)ConstType.SelectedItem == "Existing Constellation")
                        {
                            IAgConstellation assets  = (IAgConstellation)CommonData.StkRoot.GetObjectFromPath("Constellation/" + ExistingConst.Text);
                            string           objPath = "Satellite/" + NameValue.Text;
                            assets.Objects.Add(objPath);
                        }
                        else if ((string)ConstType.SelectedItem == "New Constellation")
                        {
                            IAgConstellation assets  = (IAgConstellation)CommonData.StkRoot.CurrentScenario.Children.New(AgESTKObjectType.eConstellation, ConstName.Text);
                            string           objPath = "Satellite/" + NameValue.Text;
                            assets.Objects.Add(objPath);
                        }
                    }
                    catch (Exception)
                    {
                        string errorMes = null;
                        if (errorNum == 1)
                        {
                            errorMes = "Could not load satellite- Improper Orbital Elements";
                        }
                        else if (errorNum == 2)
                        {
                            errorMes = "Could not add satellite to constellation";
                        }
                        MessageBox.Show(errorMes);
                    }
                }
            }
            else if ((string)ImportType.SelectedItem == "Satellite Database")
            {
                string           sscString = null;
                string           satName   = null;
                int              errorNum  = 0;
                string           errorSsc  = null;
                string           objPath   = null;
                IAgSatellite     mySat     = null;
                IAgConstellation assets    = null;
                IAgScenario      scenario  = CommonData.StkRoot.CurrentScenario as IAgScenario;
                string           startTime = scenario.StartTime;
                string           stopTime  = scenario.StopTime;
                string           cmd;
                int              errorId = 0;
                CommonData.StkRoot.ExecuteCommand("BatchGraphics * On");
                foreach (var item in _selectedSatList)
                {
                    //Determine the proper satellite name based on catalog
                    errorId = 5;
                    int        index      = CommonData.SatCatItemList.IndexOf(CommonData.SatCatItemList.Where(p => p.Ssc == item).FirstOrDefault());
                    SatCatItem currentSat = CommonData.SatCatItemList[index];
                    if (currentSat.OtherName != "Unspecified")
                    {
                        string otherName = currentSat.OtherName.Replace(" ", "_");
                        otherName = Regex.Replace(otherName, @"[^0-9a-zA-Z_]+", "");
                        //CommonData.StkRoot.ExecuteCommand("Rename */" + objPath + " " + otherName);
                        objPath = "Satellite/" + otherName;
                        satName = otherName;
                    }
                    else if (currentSat.CommonName != "Unspecified")
                    {
                        string commonName = currentSat.CommonName.Replace(" ", "_");
                        commonName = Regex.Replace(commonName, @"[^0-9a-zA-Z_]+", "");
                        objPath    = "Satellite/" + commonName;
                        satName    = commonName;
                    }
                    else
                    {
                        objPath = "Satellite/" + item;
                        satName = item;
                    }

                    //SSCString = "SSCNumber " + item + " ";
                    //cmd = "ImportTLEFile * " + "\"" + CommonData.SatDatabaseLocation + "\"" +SSCString+ "AutoPropagate On TimeStep 30.0 StartStop " + "\"" + startTime + "\" " + "\"" + stopTime + "\"";
                    try
                    {
                        errorId = 1;
                        //Create or get handle to satellite based on given name
                        mySat = (IAgSatellite)CreatorFunctions.GetCreateSatellite(satName);
                        //Erase old TLE data and replace it with new data from specified file
                        mySat.SetPropagatorType(AgEVePropagatorType.ePropagatorSGP4);
                        IAgVePropagatorSGP4 tleprop = mySat.Propagator as IAgVePropagatorSGP4;
                        tleprop.Segments.RemoveAllSegs();//clear before adding new
                        tleprop.CommonTasks.AddSegsFromFile(item, CommonData.Preferences.SatDatabaseLocation);
                        tleprop.Propagate();
                        mySat.Graphics.Resolution.Orbit = 20;
                        //Change trajectory representation to fixed if required. Inertial by default
                        if (CoordSystem.SelectedIndex == 0)
                        {
                            mySat.VO.OrbitSystems.FixedByWindow.IsVisible    = true;
                            mySat.VO.OrbitSystems.InertialByWindow.IsVisible = false;
                            string cmd1 = "VO */Satellite/" + satName + " ModelDetail Set ModelLabel 2000000000 MarkerLabel 2000000000";
                            CommonData.StkRoot.ExecuteCommand(cmd1);
                        }
                        else if (CoordSystem.SelectedIndex == 1)
                        {
                            mySat.VO.OrbitSystems.FixedByWindow.IsVisible    = false;
                            mySat.VO.OrbitSystems.InertialByWindow.IsVisible = true;
                            string cmd1 = "VO */Satellite/" + satName + " ModelDetail Set ModelLabel 2000000000 MarkerLabel 2000000000";
                            CommonData.StkRoot.ExecuteCommand(cmd1);
                        }

                        //Get handle to constellation or create if necessary. Add satellite to constellation
                        if ((string)ConstType.SelectedItem == "Default Constellation")
                        {
                            errorId = 2;
                            assets  = CreatorFunctions.GetCreateConstellation("Assets") as IAgConstellation;
                        }
                        else if ((string)ConstType.SelectedItem == "Existing Constellation")
                        {
                            errorId = 3;
                            assets  = CreatorFunctions.GetCreateConstellation(ExistingConst.Text) as IAgConstellation;
                        }
                        else if ((string)ConstType.SelectedItem == "New Constellation")
                        {
                            errorId = 4;
                            assets  = CreatorFunctions.GetCreateConstellation(ConstName.Text) as IAgConstellation;
                        }

                        if (!assets.Objects.Contains("Satellite/" + satName))
                        {
                            objPath = "Satellite/" + satName;
                            assets.Objects.Add(objPath);
                        }

                        errorId = 8;
                        CreatorFunctions.ChangeSatColor(objPath, index);

                        //Create sensor if applicable. Place sensor in appropiate constellation for sensors
                        if (currentSat.Fov != 0 && SensorToggle.Checked)
                        {
                            try
                            {
                                errorId = 6;
                                IAgStkObject assetsObject = assets as IAgStkObject;
                                IAgStkObject sat          = CommonData.StkRoot.GetObjectFromPath(objPath);
                                IAgSensor    sensor       = CreatorFunctions.GetCreateSensor(sat, sat.InstanceName + "_Sensor") as IAgSensor;
                                IAgStkObject sensorObject = sensor as IAgStkObject;
                                sensor.CommonTasks.SetPatternSimpleConic(currentSat.Fov / 2, 1);
                                sensor.VO.ProjectionType      = AgESnVOProjectionType.eProjectionEarthIntersections;
                                sensor.VO.PercentTranslucency = 70;

                                errorId = 7;
                                assets  = CreatorFunctions.GetCreateConstellation(assetsObject.InstanceName + "_Sensors") as IAgConstellation;
                                try
                                {
                                    assets.Objects.AddObject(sensorObject);
                                }
                                catch (Exception)
                                {
                                    //Likely already in the constellation
                                }
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                    catch (Exception)
                    {
                        string errorIdString = null;
                        if (errorId == 1)
                        {
                            errorIdString = "- Could not load from database";
                        }
                        else if (errorId == 2)
                        {
                            errorIdString = "- Could not add to Default constellation";
                        }
                        else if (errorId == 3)
                        {
                            errorIdString = "- Could not add to existing constellation";
                        }
                        else if (errorId == 4)
                        {
                            errorIdString = "- Could not add to new constellation";
                        }
                        else if (errorId == 5)
                        {
                            errorIdString = "- Could not change satellite name";
                        }
                        else if (errorId == 6)
                        {
                            errorIdString = "- Could not load sensor or update sensor properties";
                        }
                        else if (errorId == 7)
                        {
                            errorIdString = "- Could not add sensor to constellation";
                        }
                        else if (errorId == 8)
                        {
                            errorIdString = "- Could not change satellite color";
                        }
                        errorSsc = errorSsc + item + errorIdString + "\n\r";
                        errorNum++;
                    }
                }
                if (errorNum != 0)
                {
                    MessageBox.Show("Error loading the following satellites: \n\r" + errorSsc);
                }
                CommonData.StkRoot.ExecuteCommand("BatchGraphics * Off");
            }
            else if ((string)ImportType.SelectedItem == "Ephemeris")
            {
                try
                {
                    IAgConstellation assets        = null;
                    string           constellation = null;
                    if ((string)ConstType.SelectedItem == "Default Constellation")
                    {
                        IAgStkObject obj = CreatorFunctions.GetCreateConstellation("Assets");
                        assets        = obj as IAgConstellation;
                        constellation = "Assets";
                    }
                    else if ((string)ConstType.SelectedItem == "Existing Constellation")
                    {
                        IAgStkObject obj = CreatorFunctions.GetCreateConstellation(ExistingConst.Text);
                        assets        = obj as IAgConstellation;
                        constellation = ExistingConst.Text;
                    }
                    else if ((string)ConstType.SelectedItem == "New Constellation")
                    {
                        IAgStkObject obj = CreatorFunctions.GetCreateConstellation(ConstName.Text);
                        assets        = obj as IAgConstellation;
                        constellation = ConstName.Text;
                    }
                    string   filepath   = TCEFile.Text;
                    string[] separator1 = { "\\" };
                    string[] separator2 = { "." };
                    string   fileName   = filepath.Split(separator1, StringSplitOptions.None).Last();
                    string   satName    = fileName.Split(separator2, StringSplitOptions.None).First();
                    satName = Regex.Replace(satName, @"[^0-9a-zA-Z_]+", "");
                    IAgStkObject satObj = CreatorFunctions.GetCreateSatellite(satName);
                    IAgSatellite sat    = satObj as IAgSatellite;
                    sat.SetPropagatorType(AgEVePropagatorType.ePropagatorStkExternal);
                    IAgVePropagatorStkExternal prop = sat.Propagator as IAgVePropagatorStkExternal;
                    prop.Filename = filepath;
                    if (TimeSlip.Checked)
                    {
                        try
                        {
                            prop.Override = true;
                            prop.EphemerisStartEpoch.SetExplicitTime(SlipTime.Text);
                        }
                        catch (Exception)
                        {
                            MessageBox.Show("Could not apply time slip");
                        }
                    }
                    prop.Propagate();
                    try
                    {
                        assets.Objects.AddObject(satObj);
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("Could not add to constellation");
                    }

                    if (CoordSystem.SelectedIndex == 0)
                    {
                        sat.VO.OrbitSystems.FixedByWindow.IsVisible    = true;
                        sat.VO.OrbitSystems.InertialByWindow.IsVisible = false;
                        string cmd = "VO */Satellite/" + satName + " ModelDetail Set ModelLabel 2000000000 MarkerLabel 2000000000";
                        CommonData.StkRoot.ExecuteCommand(cmd);
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show("Error loading ephemeris");
                }
            }
            CommonData.StkRoot.ExecuteCommand("BatchGraphics * Off");
            PopulateExistingConstellations();
        }
Beispiel #6
0
        /// <summary>
        /// 新建一个SARSYS在当前sc文件中
        /// 需要建立最基础的系统
        /// 参数大多数有默认值
        /// </summary>
        public void newsarsys()
        {
            #region 写入信息
            AGI.STKX.IAgExecCmdResult resultmsg = rootapp.ExecuteCommand("SetDescription * long SARSYS");
            #endregion

            #region 设定单位、仿真时间
            // Reset the units to the STK defaults
            dimensions = root.UnitPreferences;
            dimensions.ResetUnits();

            // Set the date unit, acquire an interface to the scenario and use
            // it to set the time period and epoch
            dimensions.SetCurrentUnit("DateFormat", "UTCG");

            scene = (IAgScenario)root.CurrentScenario;
            scene.StartTime = simstarttime;
            scene.StopTime = simstoptime;
            scene.Epoch = simstarttime;

            // Set new preference for Temperature
            dimensions.SetCurrentUnit("Temperature", "degC");
            #endregion

            #region 放置发射站
            //SATELLITE #1: TDRS
            //Assign a two-body propagator to propagate it
            tdrs = (IAgSatellite)root.CurrentScenario.Children.New(AgESTKObjectType.
                eSatellite, "TDRS");
            tdrs.SetPropagatorType(AgEVePropagatorType.ePropagatorTwoBody);
            twobody = (IAgVePropagatorTwoBody)tdrs.Propagator;

            //Define the TDRS satellite's orbit using
            //classical (Keplerian) orbital elements
            classical = (IAgOrbitStateClassical)twobody.InitialState.Representation.ConvertTo(AgEOrbitStateType.eOrbitStateClassical);

            //Set J2000 as the coordinate system
            //and set the time period and time step
            classical.CoordinateSystemType = AgECoordinateSystem.eCoordinateSystemJ2000;
            twobody.EphemerisInterval.SetStartAndStopTimes(simstarttime, simstoptime);
            twobody.Step = 60;

            //定义半主轴长度,离心率
            //Use period and eccentricity to define the size
            //and shape of the orbit
            classical.SizeShapeType = AgEClassicalSizeShape.eSizeShapeSemimajorAxis;
            IAgClassicalSizeShapeSemimajorAxis semi = (IAgClassicalSizeShapeSemimajorAxis)classical.SizeShape;
            semi.SemiMajorAxis = 35860;
            semi.Eccentricity = 0.0;

            //定义轨道倾角,升交点赤经,近地点幅角
            //Use argument of perigee, inclination
            //and longitude of ascending node to
            //define the orientation of the orbit
            classical.Orientation.ArgOfPerigee = 15.0;
            classical.Orientation.Inclination = 40.0;
            classical.Orientation.AscNodeType = AgEOrientationAscNode.eAscNodeLAN;
            IAgOrientationAscNodeLAN lan = (IAgOrientationAscNodeLAN)classical.Orientation.AscNode;
            lan.Value = 259.999982;

            //定义真近点角(?)来定义初始位置
            //Use true anomaly to specify the position of
            //the satellite in orbit
            classical.LocationType = AgEClassicalLocation.eLocationTrueAnomaly;
            IAgClassicalLocationTrueAnomaly trueAnomaly = (IAgClassicalLocationTrueAnomaly)classical.Location;
            trueAnomaly.Value = 178.845262;

            //Assign the orbital elements to the TDRS
            //satellite's propagator and propagate the orbit
            twobody.InitialState.Representation.Assign(classical);
            twobody.Propagate();

            root.Rewind();

            #endregion

            #region 放置接收站
            cruise = (IAgAircraft)root.CurrentScenario.Children.New(AgESTKObjectType.eAircraft, "Cruise");
            cruise.SetRouteType(AgEVePropagatorType.ePropagatorGreatArc);
            greatArc = (IAgVePropagatorGreatArc)cruise.Route;
            greatArc.EphemerisInterval.SetStartAndStopTimes(simstarttime, simstoptime);
            greatArc.Method = AgEVeWayPtCompMethod.eDetermineTimeAccFromVel;

            ((IAgVOModelFile)cruise.VO.Model.ModelData).Filename = @"\STKData\VO\Models\Air\e-3a_sentry_awacs.mdl";
            cruise.VO.Offsets.Rotational.Enable = true;
            cruise.VO.Offsets.Rotational.X = 180;

            //Use the convenience method defined above
            //to add waypoints specifying the ship's route
            AddWaypoint(greatArc.Waypoints, -42.1, -121.5, 3.0, .15, 0.0);
            AddWaypoint(greatArc.Waypoints, 62.0, -56.6, 3.0, .15, 0.0);

            cruise.SetAttitudeType(AgEVeAttitude.eAttitudeStandard);
            IAgVeRouteAttitudeStandard attitude = (IAgVeRouteAttitudeStandard)cruise.Attitude;
            attitude.Basic.SetProfileType(AgEVeProfile.
                eProfileECFVelocityAlignmentWithRadialConstraint);
            cruise.Graphics.WaypointMarker.IsWaypointMarkersVisible = true;
            cruise.Graphics.WaypointMarker.IsTurnMarkersVisible = true;
            greatArc.Propagate();
            root.Rewind();

            #endregion

            #region 放置发射站雷达
            horizon = (IAgSensor)root.CurrentScenario.Children["TDRS"].Children.
                    New(AgESTKObjectType.eSensor, "Horizon");
            horizon.SetPatternType(AgESnPattern.eSnSimpleConic);
            IAgSnSimpleConicPattern simpleConic = (IAgSnSimpleConicPattern)horizon.Pattern;
            simpleConic.ConeAngle = 0.1;

            //Select a Fixed pointing type and the Az-El
            //orientation type, and set the elevation angle to
            //90 deg, so that the sensor points straight down
            //with reference to the satellite
            horizon.SetPointingType(AgESnPointing.eSnPtFixed);
            IAgSnPtFixed fixedPt = (IAgSnPtFixed)horizon.Pointing;
            IAgOrientationAzEl azEl = (IAgOrientationAzEl)fixedPt.Orientation.ConvertTo(AgEOrientationType.eAzEl);
            azEl.Elevation = 89.2;
            azEl.AboutBoresight = AgEAzElAboutBoresight.eAzElAboutBoresightRotate;
            fixedPt.Orientation.Assign(azEl);

            root.Rewind();

            #endregion
        }
Beispiel #7
0
        //Main Function
        private void Generate_Click(object sender, EventArgs e)
        {
            int check = FieldCheck();

            if (check == 0)
            {
                RemoveProximityGeometry();
                try
                {
                    CommonData.StkRoot.UnitPreferences.SetCurrentUnit("Distance", "km");
                    CommonData.RunList.Clear();
                    CommonData.TargetName = TargetSat.Text;
                    CommonData.ActorName  = ActorSat.Text;
                    //Set user bounds for safety
                    double userMinRange = Double.Parse(SphericalMag.Text) / 1000;
                    double userMinR     = Double.Parse(RMag.Text) / 1000;
                    double userMinI     = Double.Parse(IMag.Text) / 1000;
                    double userMinC     = Double.Parse(CMag.Text) / 1000;

                    IAgScenario  scenario = CommonData.StkRoot.CurrentScenario as IAgScenario;
                    IAgStkObject satObj   = CommonData.StkRoot.GetObjectFromPath("Satellite/" + ActorSat.Text);
                    IAgSatellite sat      = satObj as IAgSatellite;

                    //Get all maneuver end times for actor satellite
                    IAgDataProviderGroup   maneuverDpGroup = satObj.DataProviders["Astrogator Maneuver Ephemeris Block Final"] as IAgDataProviderGroup;
                    IAgDataPrvTimeVar      maneuverDp      = maneuverDpGroup.Group["Cartesian Elems"] as IAgDataPrvTimeVar;
                    IAgDrResult            result          = maneuverDp.Exec(scenario.StartTime, scenario.StopTime, 60);
                    IAgDrDataSetCollection maneuverData    = result.DataSets;



                    //If there is maneuvers, run iterations for each maneuver. If no maneuvers then just pull closest RIC data for entire trajectory
                    if (maneuverData.Count != 0)
                    {
                        CommonData.HasManeuvers = true;

                        //Get maneuver numbers
                        IAgDataPrvInterval summaryDp     = satObj.DataProviders["Maneuver Summary"] as IAgDataPrvInterval;
                        IAgDrResult        summaryResult = summaryDp.Exec(scenario.StartTime, scenario.StopTime);
                        Array maneuverNumbers            = summaryResult.DataSets.GetDataSetByName("Maneuver Number").GetValues();
                        int   maxManeuverNum             = maneuverNumbers.Length;

                        //Get handles to cartesian position and velocity to seed passive safety runs
                        IAgDataProviderGroup cartPos   = satObj.DataProviders["Cartesian Position"] as IAgDataProviderGroup;
                        IAgDataPrvTimeVar    cartPosDP = cartPos.Group["ICRF"] as IAgDataPrvTimeVar;

                        IAgDataProviderGroup cartVel   = satObj.DataProviders["Cartesian Velocity"] as IAgDataProviderGroup;
                        IAgDataPrvTimeVar    cartVelDP = cartVel.Group["ICRF"] as IAgDataPrvTimeVar;

                        //Create passive safety satellite. Set to Astrogator and pull handles to initial state and propagate segments
                        IAgStkObject passiveSatObj = CreatorFunctions.GetCreateSatellite("PassiveCheck");
                        IAgSatellite passiveSat    = passiveSatObj as IAgSatellite;
                        passiveSat.SetPropagatorType(AgEVePropagatorType.ePropagatorAstrogator);
                        IAgVADriverMCS passiveDriver = passiveSat.Propagator as IAgVADriverMCS;

                        IAgVAMCSInitialState          intState = passiveDriver.MainSequence[0] as IAgVAMCSInitialState;
                        IAgVAMCSPropagate             prop     = passiveDriver.MainSequence[1] as IAgVAMCSPropagate;
                        IAgVAStoppingConditionElement sc1      = prop.StoppingConditions[0];
                        IAgVAStoppingCondition        sc       = sc1.Properties as IAgVAStoppingCondition;
                        sc.Trip = PropTime.Text;

                        AgVAElementCartesian element = intState.Element as AgVAElementCartesian;
                        Array    epoch;
                        Array    vx;
                        Array    vy;
                        Array    vz;
                        Array    x;
                        Array    y;
                        Array    z;
                        String   epochCur;
                        DateTime dateCur;
                        //Assign cartesian elements to PassiveCheck satellite from actor maneuver maneuver data. Run each iteration to see if resulting trajectory violates constraints
                        for (int i = 0; i < maxManeuverNum; i++)
                        {
                            //Get maneuver time and offset in time by 0.25 sec to account for boundrary conditions around impulsive maneuvers
                            epoch    = maneuverData[0 + (i * 7)].GetValues();
                            epochCur = epoch.GetValue(0).ToString();
                            dateCur  = DateTime.Parse(epochCur);
                            dateCur  = dateCur.AddMilliseconds(250);
                            //dateCur = DateTime.ParseExact(epochCur, "dd MMM yyyy HH:mm:ss.fff", CultureInfo.InvariantCulture);
                            epochCur = dateCur.ToString("dd MMM yyyy HH:mm:ss.fff");

                            //Get cartesian state vector for given time
                            result = cartPosDP.ExecSingle(epochCur);
                            x      = result.DataSets.GetDataSetByName("x").GetValues();
                            y      = result.DataSets.GetDataSetByName("y").GetValues();
                            z      = result.DataSets.GetDataSetByName("z").GetValues();

                            result = cartVelDP.ExecSingle(epochCur);
                            vx     = result.DataSets.GetDataSetByName("x").GetValues();
                            vy     = result.DataSets.GetDataSetByName("y").GetValues();
                            vz     = result.DataSets.GetDataSetByName("z").GetValues();

                            //Create passive run output to be used in visualization
                            PassiveRun run = new PassiveRun();
                            run.UserMinRange    = Double.Parse(SphericalMag.Text) / 1000;
                            run.UserMinR        = Double.Parse(RMag.Text) / 1000;
                            run.UserMinI        = Double.Parse(IMag.Text) / 1000;
                            run.UserMinC        = Double.Parse(CMag.Text) / 1000;
                            intState.OrbitEpoch = epochCur;
                            element.Vx          = Double.Parse(vx.GetValue(0).ToString());
                            element.Vy          = Double.Parse(vy.GetValue(0).ToString());
                            element.Vz          = Double.Parse(vz.GetValue(0).ToString());
                            element.X           = Double.Parse(x.GetValue(0).ToString());
                            element.Y           = Double.Parse(y.GetValue(0).ToString());
                            element.Z           = Double.Parse(z.GetValue(0).ToString());

                            passiveDriver.RunMCS();

                            run.Vx       = Double.Parse(vx.GetValue(0).ToString());
                            run.Vy       = Double.Parse(vy.GetValue(0).ToString());
                            run.Vz       = Double.Parse(vz.GetValue(0).ToString());
                            run.X        = Double.Parse(x.GetValue(0).ToString());
                            run.Y        = Double.Parse(y.GetValue(0).ToString());
                            run.Z        = Double.Parse(z.GetValue(0).ToString());
                            run.PropTime = Double.Parse(PropTime.Text);

                            //Pull closest point to target for each iteration and save to passive run output
                            IAgDataProvider psatDp = passiveSatObj.DataProviders["RIC Coordinates"] as IAgDataProvider;
                            psatDp.PreData = "Satellite/" + TargetSat.Text;
                            IAgDataPrvTimeVar psatDpTimeVar = psatDp as IAgDataPrvTimeVar;
                            IAgDrResult       psatDp2       = psatDpTimeVar.Exec(scenario.StartTime, scenario.StopTime, Double.Parse(TimeStep.Text));
                            run.Range         = psatDp2.DataSets.GetDataSetByName("Range").GetValues();
                            run.Intrack       = psatDp2.DataSets.GetDataSetByName("In-Track").GetValues();
                            run.Crosstrack    = psatDp2.DataSets.GetDataSetByName("Cross-Track").GetValues();
                            run.Radial        = psatDp2.DataSets.GetDataSetByName("Radial").GetValues();
                            run.MinRange      = MathFunctions.ArrayMin(run.Range);
                            run.MinIntrack    = MathFunctions.ArrayMinAbs(run.Intrack);
                            run.MinCrosstrack = MathFunctions.ArrayMinAbs(run.Crosstrack);
                            run.MinRadial     = MathFunctions.ArrayMinAbs(run.Radial);
                            //run.ManeuverTime = epoch.GetValue(0).ToString();
                            run.ManeuverTime = epochCur;

                            //spherical
                            if (radioButton1.Checked)
                            {
                                run.IsSpherical = true;
                                if (run.MinRange < userMinRange)
                                {
                                    run.Safe = false;
                                }
                                else
                                {
                                    run.Safe = true;
                                }
                            }
                            //independent axis
                            else
                            {
                                run.IsSpherical = false;
                                if (Math.Abs(run.MinIntrack) < userMinI && Math.Abs(run.MinRadial) < userMinR && Math.Abs(run.MinCrosstrack) < userMinC)
                                {
                                    bool tripped = false;
                                    for (int j = 0; j < run.Range.Length; j++)
                                    {
                                        if (Math.Abs(Double.Parse(run.Intrack.GetValue(j).ToString())) < userMinI && Math.Abs(Double.Parse(run.Radial.GetValue(j).ToString())) < userMinR && Math.Abs(Double.Parse(run.Crosstrack.GetValue(j).ToString())) < userMinC)
                                        {
                                            run.Safe = false;
                                            tripped  = true;
                                            break;
                                        }
                                    }
                                    if (!tripped)
                                    {
                                        run.Safe = true;
                                    }
                                }
                                else
                                {
                                    run.Safe = true;
                                }
                            }

                            CommonData.RunList.Add(run);
                        }
                    }
                    else
                    {
                        CommonData.HasManeuvers = false;
                        PassiveRun      run   = new PassiveRun();
                        IAgDataProvider satDp = satObj.DataProviders["RIC Coordinates"] as IAgDataProvider;
                        satDp.PreData = "Satellite/" + TargetSat.Text;
                        IAgDataPrvTimeVar satDpTimeVar = satDp as IAgDataPrvTimeVar;
                        IAgDrResult       satDp2       = satDpTimeVar.Exec(scenario.StartTime, scenario.StopTime, Double.Parse(TimeStep.Text));
                        run.Range         = satDp2.DataSets.GetDataSetByName("Range").GetValues();
                        run.Intrack       = satDp2.DataSets.GetDataSetByName("In-Track").GetValues();
                        run.Crosstrack    = satDp2.DataSets.GetDataSetByName("Cross-Track").GetValues();
                        run.Radial        = satDp2.DataSets.GetDataSetByName("Radial").GetValues();
                        run.MinRange      = MathFunctions.ArrayMin(run.Range);
                        run.MinIntrack    = MathFunctions.ArrayMinAbs(run.Intrack);
                        run.MinCrosstrack = MathFunctions.ArrayMinAbs(run.Crosstrack);
                        run.MinRadial     = MathFunctions.ArrayMinAbs(run.Radial);
                        run.ManeuverTime  = "N/A";

                        //spherical
                        if (radioButton1.Checked)
                        {
                            run.IsSpherical = true;
                            if (run.MinRange < userMinRange)
                            {
                                run.Safe = false;
                            }
                            else
                            {
                                run.Safe = true;
                            }
                        }
                        //independent axis
                        else
                        {
                            run.IsSpherical = false;
                            if (Math.Abs(run.MinIntrack) < userMinI && Math.Abs(run.MinRadial) < userMinR && Math.Abs(run.MinCrosstrack) < userMinC)
                            {
                                bool tripped = false;
                                for (int j = 0; j < run.Range.Length; j++)
                                {
                                    if (Math.Abs(Double.Parse(run.Intrack.GetValue(j).ToString())) < userMinI && Math.Abs(Double.Parse(run.Radial.GetValue(j).ToString())) < userMinR && Math.Abs(Double.Parse(run.Crosstrack.GetValue(j).ToString())) < userMinC)
                                    {
                                        run.Safe = false;
                                        tripped  = true;
                                        break;
                                    }
                                }
                                if (!tripped)
                                {
                                    run.Safe = true;
                                }
                            }
                            else
                            {
                                run.Safe = true;
                            }
                        }

                        CommonData.RunList.Add(run);
                    }
                    CommonData.BeenRun = true;
                }
                catch (Exception)
                {
                    MessageBox.Show("Passive Safety Check Failed");
                }
            }
        }
Beispiel #8
0
        /// <summary>
        /// 新建一个SARSYS在当前sc文件中
        /// 需要建立最基础的系统
        /// 参数大多数有默认值
        /// </summary>
        public void newsarsys()
        {
            #region 写入信息
            AGI.STKX.IAgExecCmdResult resultmsg = rootapp.ExecuteCommand("SetDescription * long SARSYS");
            #endregion


            #region 设定单位、仿真时间
            // Reset the units to the STK defaults
            dimensions = root.UnitPreferences;
            dimensions.ResetUnits();

            // Set the date unit, acquire an interface to the scenario and use
            // it to set the time period and epoch
            dimensions.SetCurrentUnit("DateFormat", "UTCG");

            scene = (IAgScenario)root.CurrentScenario;
            scene.StartTime = simstarttime;
            scene.StopTime = simstoptime;
            scene.Epoch = simstarttime;

            //rootapp.ExecuteCommand("MapTracking * UTM");

            // Set new preference for Temperature
            dimensions.SetCurrentUnit("Temperature", "degC");
            #endregion

            #region 放置发射站
            //SATELLITE #1: TDRS
            //Assign a two-body propagator to propagate it
            tdrs = (IAgSatellite)root.CurrentScenario.Children.New(AgESTKObjectType.
                eSatellite, "TDRS");
            tdrs.SetPropagatorType(AgEVePropagatorType.ePropagatorTwoBody);
            twobody = (IAgVePropagatorTwoBody)tdrs.Propagator;

            //Define the TDRS satellite's orbit using
            //classical (Keplerian) orbital elements
            classical = (IAgOrbitStateClassical)twobody.InitialState.Representation.ConvertTo(AgEOrbitStateType.eOrbitStateClassical);

            //Set J2000 as the coordinate system
            //and set the time period and time step
            classical.CoordinateSystemType = AgECoordinateSystem.eCoordinateSystemJ2000;
            twobody.EphemerisInterval.SetStartAndStopTimes(simstarttime, simstoptime);
            twobody.Step = 60;

            //定义半主轴长度,离心率
            //Use period and eccentricity to define the size
            //and shape of the orbit
            classical.SizeShapeType = AgEClassicalSizeShape.eSizeShapeSemimajorAxis;
            IAgClassicalSizeShapeSemimajorAxis semi = (IAgClassicalSizeShapeSemimajorAxis)classical.SizeShape;
            semi.SemiMajorAxis = sasem;
            semi.Eccentricity = saecc;


            //定义轨道倾角,升交点赤经,近地点幅角
            //Use argument of perigee, inclination
            //and longitude of ascending node to
            //define the orientation of the orbit
            classical.Orientation.ArgOfPerigee = saaop;
            classical.Orientation.Inclination = sainc;
            classical.Orientation.AscNodeType = AgEOrientationAscNode.eAscNodeLAN;
            IAgOrientationAscNodeLAN lan = (IAgOrientationAscNodeLAN)classical.Orientation.AscNode;
            lan.Value = salan;

            //定义真近点角(?)来定义初始位置
            //Use true anomaly to specify the position of
            //the satellite in orbit
            classical.LocationType = AgEClassicalLocation.eLocationTrueAnomaly;
            IAgClassicalLocationTrueAnomaly trueAnomaly = (IAgClassicalLocationTrueAnomaly)classical.Location;
            trueAnomaly.Value = satra;


            //Assign the orbital elements to the TDRS
            //satellite's propagator and propagate the orbit	
            twobody.InitialState.Representation.Assign(classical);
            twobody.Propagate();

            root.Rewind();

            #endregion

            
            #region 放置接收站
            cruise = (IAgAircraft)root.CurrentScenario.Children.New(AgESTKObjectType.eAircraft, "Cruise");
            cruise.SetRouteType(AgEVePropagatorType.ePropagatorGreatArc);
            greatArc = (IAgVePropagatorGreatArc)cruise.Route;
            greatArc.EphemerisInterval.SetStartAndStopTimes(simstarttime, simstoptime);
            greatArc.Method = AgEVeWayPtCompMethod.eDetermineTimeAccFromVel;

            ((IAgVOModelFile)cruise.VO.Model.ModelData).Filename = @"\STKData\VO\Models\Air\rq-4a_globalhawk.mdl";
            cruise.VO.Offsets.Rotational.Enable = true;
            cruise.VO.Offsets.Rotational.X = 180;

            //Use the convenience method defined above
            //to add waypoints specifying the ship's route
            for (int ii = 0; ii < plwaypoints.Length; ii += 5)
            {
                AddWaypoint(greatArc.Waypoints, plwaypoints[ii], plwaypoints[ii + 1], plwaypoints[ii + 2], plwaypoints[ii + 3], plwaypoints[ii + 4]);
            }
              
            
            cruise.SetAttitudeType(AgEVeAttitude.eAttitudeStandard);
            IAgVeRouteAttitudeStandard attitude = (IAgVeRouteAttitudeStandard)cruise.Attitude;
            attitude.Basic.SetProfileType(AgEVeProfile.
                eProfileECFVelocityAlignmentWithRadialConstraint);
            cruise.Graphics.WaypointMarker.IsWaypointMarkersVisible = true;
            cruise.Graphics.WaypointMarker.IsTurnMarkersVisible = true;
            greatArc.Propagate();
            root.Rewind();


            #endregion

            #region 放置发射站雷达
            radar_t = (IAgSensor)root.CurrentScenario.Children["TDRS"].Children.New(AgESTKObjectType.eSensor, "radar_t");
            radar_t.SetPatternType(AgESnPattern.eSnSimpleConic);
            ((IAgSnSimpleConicPattern)radar_t.Pattern).ConeAngle = racoang;



            //Select a Fixed pointing type and the Az-El
            //orientation type, and set the elevation angle to
            //90 deg, so that the sensor points straight down
            //with reference to the satellite
            radar_t.SetPointingType(AgESnPointing.eSnPtFixed);
            IAgSnPtFixed fixedPt = (IAgSnPtFixed)radar_t.Pointing;
            IAgOrientationAzEl azEl = (IAgOrientationAzEl)fixedPt.Orientation.ConvertTo(AgEOrientationType.eAzEl);
            azEl.Elevation = raeleva;
            azEl.AboutBoresight = AgEAzElAboutBoresight.eAzElAboutBoresightRotate;
            fixedPt.Orientation.Assign(azEl);

            radar_t.Graphics.FillVisible = true;
            radar_t.VO.FillVisible = true;
            

            root.Rewind();


            #endregion


            #region 放置接收站雷达


            target = (IAgSensor)root.CurrentScenario.Children["TDRS"].Children.New(AgESTKObjectType.eSensor, "target");

            target.SetLocationType(AgESnLocation.eSnLocationCrdnPoint);
            IAgLocationCrdnPoint vgtPoint = target.LocationData as IAgLocationCrdnPoint;
            //vgtPoint.PointPath = "TDRS/radar_t BoresightIntersection(Terrain)";
            vgtPoint.PointPath = "Satellite/TDRS/Sensor/radar_t BoresightIntersection(Terrain)";
            target.SetPatternType(AgESnPattern.eSnSimpleConic);
            ((IAgSnSimpleConicPattern)target.Pattern).ConeAngle = 0.00001;
           
            

            IAgSnPtTargeted targetedSensor1 = target.CommonTasks.SetPointingTargetedTracking(
   AgETrackModeType.eTrackModeTranspond, AgEBoresightType.eBoresightRotate, "*/Aircraft/Cruise");


            target.SetPointingType(AgESnPointing.eSnPtTargeted);
            IAgSnPtTargeted rpt1 = (IAgSnPtTargeted)target.Pointing;
            rpt1.Boresight = AgESnPtTrgtBsightType.eSnPtTrgtBsightTracking;
            root.Rewind();
            rootapp.ExecuteCommand("Graphics */Satellite/TDRS/Sensor/target Show Off");


            /////////////////////////
            radar_r = (IAgSensor)root.CurrentScenario.Children["Cruise"].Children.New(AgESTKObjectType.eSensor, "radar_r");
            radar_r.SetPatternType(AgESnPattern.eSnSimpleConic);
            ((IAgSnSimpleConicPattern)radar_r.Pattern).ConeAngle = 3;
        

            IAgSnPtTargeted targetedSensor = radar_r.CommonTasks.SetPointingTargetedTracking(
    AgETrackModeType.eTrackModeTranspond, AgEBoresightType.eBoresightRotate, "*/Satellite/TDRS/Sensor/target");   

            
            radar_r.SetPointingType(AgESnPointing.eSnPtTargeted);
            IAgSnPtTargeted rpt = (IAgSnPtTargeted)radar_r.Pointing;
            rpt.Boresight = AgESnPtTrgtBsightType.eSnPtTrgtBsightTracking;
            

            root.Rewind();
            #endregion
        }
Beispiel #9
0
        public static PropagationResults PropagateAstrogatorSatellite(AgStkObjectRoot root, AgUiApplication app, InitialState state, TLE tle, Data satData, Uncertainty uncertainty, int runId, int nRuns, string propName)
        {
            PropagationResults propResults = new PropagationResults();

            propResults.RunNumber = runId.ToString().PadLeft(3, '0');
            IAgSatellite sat = root.CurrentScenario.Children.New(AgESTKObjectType.eSatellite, tle.GetSatNumber() + "Astrogator") as IAgSatellite;

            //Set the propagator to Astrogator
            sat.SetPropagatorType(AgEVePropagatorType.ePropagatorAstrogator);
            //get the Driver for the Propagator
            IAgVADriverMCS driver = sat.Propagator as IAgVADriverMCS;

            //Clear all segments from the MCS
            driver.MainSequence.RemoveAll();

            //// Target Sequence ////
            IAgVAMCSTargetSequence ts = driver.MainSequence.Insert(AgEVASegmentType.eVASegmentTypeTargetSequence, "SetupState", "-") as IAgVAMCSTargetSequence;

            ts.Action = AgEVATargetSeqAction.eVATargetSeqActionRunActiveProfiles;

            // add the initial state segment in the target sequence
            IAgVAMCSInitialState initState = ts.Segments.Insert(AgEVASegmentType.eVASegmentTypeInitialState, "InitialState", "-") as IAgVAMCSInitialState;

            initState.OrbitEpoch = ((IAgScenario)root.CurrentScenario).StartTime;
            // define elements
            initState.SetElementType(AgEVAElementType.eVAElementTypeCartesian);
            IAgVAElementCartesian cart = initState.Element as IAgVAElementCartesian;

            cart.X  = Convert.ToDouble(state.CartesianPosX);
            cart.Y  = Convert.ToDouble(state.CartesianPosY);
            cart.Z  = Convert.ToDouble(state.CartesianPosZ);
            cart.Vx = Convert.ToDouble(state.CartesianVelX);
            cart.Vy = Convert.ToDouble(state.CartesianVelY);
            cart.Vz = Convert.ToDouble(state.CartesianVelZ);

            // spacecraft parameters
            IAgVASpacecraftParameters spacecraftParameters = (IAgVASpacecraftParameters)initState.SpacecraftParameters;

            spacecraftParameters.DryMass  = satData.Mass;
            spacecraftParameters.Cd       = satData.Cd;
            spacecraftParameters.DragArea = satData.DragArea;
            spacecraftParameters.Cr       = satData.Cr;
            spacecraftParameters.SolarRadiationPressureArea = satData.SunArea;
            spacecraftParameters.RadiationPressureArea      = 1e-10;
            IAgVAFuelTank fuelTank = (IAgVAFuelTank)initState.FuelTank;

            fuelTank.FuelMass = 0;

            // enable the control parameter for the state variables
            initState.EnableControlParameter(AgEVAControlInitState.eVAControlInitStateCartesianX);
            initState.EnableControlParameter(AgEVAControlInitState.eVAControlInitStateCartesianY);
            initState.EnableControlParameter(AgEVAControlInitState.eVAControlInitStateCartesianZ);
            initState.EnableControlParameter(AgEVAControlInitState.eVAControlInitStateCartesianVx);
            initState.EnableControlParameter(AgEVAControlInitState.eVAControlInitStateCartesianVy);
            initState.EnableControlParameter(AgEVAControlInitState.eVAControlInitStateCartesianVz);

            // add the results
            ((IAgVAMCSSegment)initState).Results.Add("Relative Motion/InTrack");
            IAgVAStateCalcRelMotion intrackRel = ((IAgVAMCSSegment)initState).Results[0] as IAgVAStateCalcRelMotion;

            intrackRel.ReferenceSelection = AgEVACalcObjectReference.eVACalcObjectReferenceSpecified;
            IAgLinkToObject link_1 = intrackRel.Reference as IAgLinkToObject;

            link_1.BindTo("Satellite/" + tle.GetSatNumber().ToString());

            ((IAgVAMCSSegment)initState).Results.Add("Relative Motion/Radial");
            IAgVAStateCalcRelMotion radialRel = ((IAgVAMCSSegment)initState).Results[1] as IAgVAStateCalcRelMotion;

            radialRel.ReferenceSelection = AgEVACalcObjectReference.eVACalcObjectReferenceSpecified;
            IAgLinkToObject link_2 = radialRel.Reference as IAgLinkToObject;

            link_2.BindTo("Satellite/" + tle.GetSatNumber().ToString());

            ((IAgVAMCSSegment)initState).Results.Add("Relative Motion/CrossTrack");
            IAgVAStateCalcRelMotion crosstrackRel = ((IAgVAMCSSegment)initState).Results[2] as IAgVAStateCalcRelMotion;

            crosstrackRel.ReferenceSelection = AgEVACalcObjectReference.eVACalcObjectReferenceSpecified;
            IAgLinkToObject link_3 = crosstrackRel.Reference as IAgLinkToObject;

            link_3.BindTo("Satellite/" + tle.GetSatNumber().ToString());

            ((IAgVAMCSSegment)initState).Results.Add("Relative Motion/InTrackRate");
            IAgVAStateCalcRelMotion intrackrateRel = ((IAgVAMCSSegment)initState).Results[3] as IAgVAStateCalcRelMotion;

            intrackrateRel.ReferenceSelection = AgEVACalcObjectReference.eVACalcObjectReferenceSpecified;
            IAgLinkToObject link_4 = intrackrateRel.Reference as IAgLinkToObject;

            link_4.BindTo("Satellite/" + tle.GetSatNumber().ToString());

            ((IAgVAMCSSegment)initState).Results.Add("Relative Motion/RadialRate");
            IAgVAStateCalcRelMotion radialrateRel = ((IAgVAMCSSegment)initState).Results[4] as IAgVAStateCalcRelMotion;

            radialrateRel.ReferenceSelection = AgEVACalcObjectReference.eVACalcObjectReferenceSpecified;
            IAgLinkToObject link_5 = radialrateRel.Reference as IAgLinkToObject;

            link_5.BindTo("Satellite/" + tle.GetSatNumber().ToString());

            ((IAgVAMCSSegment)initState).Results.Add("Relative Motion/CrossTrackRate");
            IAgVAStateCalcRelMotion crosstrackrateRel = ((IAgVAMCSSegment)initState).Results[5] as IAgVAStateCalcRelMotion;

            crosstrackrateRel.ReferenceSelection = AgEVACalcObjectReference.eVACalcObjectReferenceSpecified;
            IAgLinkToObject link_6 = crosstrackrateRel.Reference as IAgLinkToObject;

            link_6.BindTo("Satellite/" + tle.GetSatNumber().ToString());

            /// differential corrector setup ///
            IAgVAProfileDifferentialCorrector dc = ts.Profiles["Differential Corrector"] as IAgVAProfileDifferentialCorrector;

            // control parameters
            IAgVADCControl xControlParam = dc.ControlParameters.GetControlByPaths("InitialState", "InitialState.Cartesian.X");

            xControlParam.Enable       = true;
            xControlParam.MaxStep      = 1;
            xControlParam.Perturbation = 0.1;
            IAgVADCControl yControlParam = dc.ControlParameters.GetControlByPaths("InitialState", "InitialState.Cartesian.Y");

            yControlParam.Enable       = true;
            yControlParam.MaxStep      = 1;
            yControlParam.Perturbation = 0.1;
            IAgVADCControl zControlParam = dc.ControlParameters.GetControlByPaths("InitialState", "InitialState.Cartesian.Z");

            zControlParam.Enable       = true;
            zControlParam.MaxStep      = 1;
            zControlParam.Perturbation = 0.1;
            IAgVADCControl vxControlParam = dc.ControlParameters.GetControlByPaths("InitialState", "InitialState.Cartesian.Vx");

            vxControlParam.Enable       = true;
            vxControlParam.MaxStep      = 0.001;
            vxControlParam.Perturbation = 1e-04;
            IAgVADCControl vyControlParam = dc.ControlParameters.GetControlByPaths("InitialState", "InitialState.Cartesian.Vy");

            vyControlParam.Enable       = true;
            vyControlParam.MaxStep      = 0.001;
            vyControlParam.Perturbation = 1e-04;
            IAgVADCControl vzControlParam = dc.ControlParameters.GetControlByPaths("InitialState", "InitialState.Cartesian.Vz");

            vzControlParam.Enable       = true;
            vzControlParam.MaxStep      = 0.001;
            vzControlParam.Perturbation = 1e-04;

            // results
            double[] deviations = uncertainty.GetRandomDeviation();

            IAgVADCResult intrackResult = dc.Results.GetResultByPaths("InitialState", "InTrack");

            intrackResult.Enable       = true;
            intrackResult.DesiredValue = deviations[0];
            intrackResult.Tolerance    = 0.01;
            IAgVADCResult radialResult = dc.Results.GetResultByPaths("InitialState", "Radial");

            radialResult.Enable       = true;
            radialResult.DesiredValue = deviations[1];
            radialResult.Tolerance    = 0.01;
            IAgVADCResult crosstrackResult = dc.Results.GetResultByPaths("InitialState", "CrossTrack");

            crosstrackResult.Enable       = true;
            crosstrackResult.DesiredValue = deviations[2];
            crosstrackResult.Tolerance    = 0.01;
            IAgVADCResult intrackRateResult = dc.Results.GetResultByPaths("InitialState", "InTrackRate");

            intrackRateResult.Enable       = true;
            intrackRateResult.DesiredValue = deviations[3] / 1000;
            intrackRateResult.Tolerance    = 0.001;
            IAgVADCResult radialRateResult = dc.Results.GetResultByPaths("InitialState", "RadialRate");

            radialRateResult.Enable       = true;
            radialRateResult.DesiredValue = deviations[4] / 1000;
            radialRateResult.Tolerance    = 0.001;
            IAgVADCResult crosstrackRateResult = dc.Results.GetResultByPaths("InitialState", "CrossTrackRate");

            crosstrackRateResult.Enable       = true;
            crosstrackRateResult.DesiredValue = deviations[5] / 1000;
            crosstrackRateResult.Tolerance    = 0.001;

            /// Propagator ///
            IAgVAMCSPropagate propagate = driver.MainSequence.Insert(AgEVASegmentType.eVASegmentTypePropagate, "ToGround", "-") as IAgVAMCSPropagate;

            ((IAgVAMCSSegment)propagate).Properties.Color = Color.Red;
            //propagate.PropagatorName = "CustomProp";
            propagate.PropagatorName = propName;

            // add an Epoch stopping condition
            IAgVAStoppingConditionCollection propStoppingConditions = propagate.StoppingConditions as IAgVAStoppingConditionCollection;
            IAgVAStoppingConditionElement    epochElement           = propStoppingConditions.Add("Epoch");
            IAgVAStoppingCondition           epoch = (IAgVAStoppingCondition)epochElement.Properties;

            epoch.Trip = ((IAgScenario)root.CurrentScenario).StopTime;
            // add an Altitude stopping condition
            IAgVAStoppingConditionElement altitudeElement = propStoppingConditions.Add("Altitude");
            IAgVAStoppingCondition        altitude        = (IAgVAStoppingCondition)altitudeElement.Properties;

            altitude.Trip = 0;
            // remove the original stopping condition
            propagate.StoppingConditions.Remove("Duration");

            // run the MCS
            driver.RunMCS();
            driver.ClearDWCGraphics();


            // get the stop time
            IAgDataPrvInterval dp          = ((IAgStkObject)sat).DataProviders.GetDataPrvIntervalFromPath("Astrogator MCS Ephemeris Segments") as IAgDataPrvInterval;
            IAgDrResult        result      = dp.Exec(((IAgScenario)root.CurrentScenario).StartTime, ((IAgScenario)root.CurrentScenario).StopTime);
            string             satStopTime = result.DataSets[3].GetValues().GetValue(1).ToString();

            if (satStopTime.Equals((Convert.ToString(((IAgScenario)root.CurrentScenario).StopTime))))
            {
                // the satellite does not decay (it is propagated until the scenario stop time)
                propResults.IsDecayed = false;
            }
            else
            {
                propResults.IsDecayed   = true;
                propResults.ImpactEpoch = satStopTime;
                // remove the millisecond part
                satStopTime = satStopTime.Split('.')[0];

                //ask for LLA data at stop time
                IAgDataPrvTimeVar dpInfo  = ((IAgStkObject)sat).DataProviders.GetDataPrvInfoFromPath("LLA State//Fixed") as IAgDataPrvTimeVar;
                IAgDrResult       resInfo = dpInfo.ExecSingle(satStopTime);
                string            lat     = resInfo.DataSets[1].GetValues().GetValue(0).ToString();
                string            lon     = resInfo.DataSets[2].GetValues().GetValue(0).ToString();
                string            alt     = resInfo.DataSets[3].GetValues().GetValue(0).ToString();
                propResults.ImpactLat = lat;
                propResults.ImpactLon = lon;
                propResults.ImpactAlt = alt;

                // create a target object
                IAgTarget target = root.CurrentScenario.Children.New(AgESTKObjectType.eTarget, "Target" + (runId).ToString().PadLeft(3, '0')) as IAgTarget;
                target.Graphics.Color        = Color.Red;
                target.Graphics.LabelVisible = false;
                IAgPosition pos = target.Position;
                pos.AssignGeodetic(lat, lon, 0);

                // create and display the time event
                IAgCrdnProvider   provider   = root.CurrentScenario.Children["Target" + (runId).ToString().PadLeft(3, '0')].Vgt;
                IAgCrdnEventEpoch eventEpoch = provider.Events.Factory.CreateEventEpoch(runId.ToString().PadLeft(3, '0') + "_Impact", "Impact Epoch") as IAgCrdnEventEpoch;
                eventEpoch.Epoch = satStopTime;
                try { root.ExecuteCommand("Timeline * TimeComponent Add ContentView \"Scenario Availability\" \"Target/Target" + (runId).ToString().PadLeft(3, '0') + " " + runId.ToString().PadLeft(3, '0') + "_Impact Time Instant\""); }
                catch (Exception) { }
                root.ExecuteCommand("Timeline * Refresh");

                // create a unique ephemeris file for each Astrogator run
                DateTime now = DateTime.Now;
                string   satEphemerisPath = Directory.GetCurrentDirectory() + "\\Ephemeris\\Reentry_run_" + (runId).ToString().PadLeft(3, '0') + ".e";
                root.ExecuteCommand("ExportDataFile */Satellite/" + tle.GetSatNumber() + "Astrogator Ephemeris \"" + satEphemerisPath + "\" Type STK CoordSys ICRF CentralBody Earth InterpBoundaries Include");
                propResults.EphemerisFilePath = satEphemerisPath;
                // unload Astrogator satellite
                root.CurrentScenario.Children[tle.GetSatNumber() + "Astrogator"].Unload();

                if (runId == nRuns)
                {
                    // remove the TLE sat
                    // root.CurrentScenario.Children[tle.GetSatNumber()].Unload();
                }
            }

            try
            {
                AGI.Ui.Core.IAgUiWindowsCollection windows = app.Windows;
                foreach (dynamic window in app.Windows)
                {
                    string windowCaption = (string)window.Caption;
                    if (windowCaption.Contains("Setup"))
                    {
                        window.Close();
                    }
                }
            }
            catch (Exception ex)
            {
            }

            return(propResults);
        }
Beispiel #10
0
        public static void CreateScenarioFromTle(ref AgStkObjectRoot root, double duration, ref InitialState initState, TLE currentTle)
        {
            root.NewScenario(currentTle.GetSatNumber() + "_Reentry");
            DateTime startDate = currentTle.GetTleEpoch();
            DateTime stopDate  = startDate.AddDays(duration);

            IAgScenario scenario = root.CurrentScenario as IAgScenario;

            // Set scenario start and stop times
            scenario.SetTimePeriod(startDate.ToString("dd MMM yyyy hh:mm:ss.fff"), stopDate.ToString("dd MMM yyyy hh:mm:ss.fff"));

            // remove the terrain option
            root.ExecuteCommand("Terrain * TerrainServer UseTerrainForAnalysis No");

            // create the SGP4 object from the TLE
            IAgSatellite decayingSat = (IAgSatellite)root.CurrentScenario.Children.New(AgESTKObjectType.eSatellite, currentTle.GetSatNumber());

            decayingSat.SetPropagatorType(AgEVePropagatorType.ePropagatorSGP4);
            IAgVePropagatorSGP4 sgp4 = decayingSat.Propagator as IAgVePropagatorSGP4;

            sgp4.CommonTasks.AddSegsFromFile(currentTle.GetSatNumber(), currentTle.GetFilePath());
            IAgVeGfxAttributesBasic att = decayingSat.Graphics.Attributes as IAgVeGfxAttributesBasic;

            att.Color = Color.Yellow;

            // Configure time period
            sgp4.EphemerisInterval.SetExplicitInterval(scenario.StartTime, scenario.StopTime);
            sgp4.Step = 60.0;
            // Propagate
            sgp4.Propagate();

            // change the 3D model
            try
            {
                root.ExecuteCommand("VO */Satellite/" + currentTle.GetSatNumber() + " Model File \"C:\\Program Files\\AGI\\STK 11\\STKData\\VO\\Models\\Misc\\explosion.mdl\"");
            }
            catch (Exception)
            {
            }

            //// get the initial state from the TLE
            initState.Epoch = scenario.StartTime;

            IAgDataPrvTimeVar      dpPos       = ((IAgStkObject)decayingSat).DataProviders.GetDataPrvTimeVarFromPath("Cartesian Position//ICRF");
            IAgDrResult            resultPos   = dpPos.Exec(scenario.StartTime, scenario.StartTime, 60.0);
            IAgDrDataSetCollection datasetsPos = resultPos.DataSets;

            if (resultPos.DataSets.Count > 0)
            {
                initState.CartesianPosX = datasetsPos[1].GetValues().GetValue(0).ToString();
                initState.CartesianPosY = datasetsPos[2].GetValues().GetValue(0).ToString();
                initState.CartesianPosZ = datasetsPos[3].GetValues().GetValue(0).ToString();
            }

            IAgDataPrvTimeVar      dpVel       = ((IAgStkObject)decayingSat).DataProviders.GetDataPrvTimeVarFromPath("Cartesian Velocity//ICRF");
            IAgDrResult            resultVel   = dpVel.Exec(scenario.StartTime, scenario.StartTime, 60.0);
            IAgDrDataSetCollection datasetsVel = resultVel.DataSets;

            if (resultVel.DataSets.Count > 0)
            {
                initState.CartesianVelX = datasetsVel[1].GetValues().GetValue(0).ToString();
                initState.CartesianVelY = datasetsVel[2].GetValues().GetValue(0).ToString();
                initState.CartesianVelZ = datasetsVel[3].GetValues().GetValue(0).ToString();
            }

            // configure the 2D graphics
            root.ExecuteCommand("Graphics * BackgroundImage Show Off");
            root.ExecuteCommand("MapDetails * LatLon Lon On 15");
            root.ExecuteCommand("MapDetails * Map RWDB2_Islands State On Color green");
            root.ExecuteCommand("MapDetails * Map RWDB2_International_Borders State On ");
            root.ExecuteCommand("MapDetails * Map RWDB2_Lakes State On");

            try
            {
                root.ExecuteCommand("VO * Globe Show On File \"C:\\Program Files\\AGI\\STK 11\\STKData\\VO\\Globes\\Earth\\WhiteOnBlue.glb\"");
            }
            catch (Exception)
            {
            }

            // configure the 3D graphics
            root.ExecuteCommand("VO * GlobeDetails MapDetail Show On Map RWDB2_Coastlines ShowDetail On");
            root.ExecuteCommand("VO * GlobeDetails MapDetail Show On Map RWDB2_Islands ShowDetail On DetailColor green");
            root.ExecuteCommand("VO * GlobeDetails MapDetail Show On Map RWDB2_Lakes ShowDetail On DetailColor lightblue");


            //dynamic uiApp = System.Runtime.InteropServices.Marshal.GetActiveObject("STK11.Application");
            //try
            //{
            //    foreach (dynamic window in uiApp.Windows)
            //    {
            //        string windowCaption = (string)window.Caption;
            //        if (windowCaption.Contains("2D"))
            //        {
            //            window.DockStyle = 3;
            //        }
            //    }

            //}
            //catch (Exception ex)
            //{
            //    string error = ex.Message;
            //}
        }