MATLAB Code Snippets

Introduction

The following code snippets demonstrate tasks that are commonly encountered when working with the STK Object Model.

How do I ...

Initialization

STK Objects

Connect

Camera

Graphics

Graphics

Analysis Workbench

Scenario

Engine

Get a reference to the AgStkObjectRoot using the running STK instance

[MATLAB]

% Get reference to running STK instance
uiApplication = actxGetRunningServer('STK.Application');

% Get our IAgStkObjectRoot interface
root = uiApplication.Personality2;

Start STK and get a reference to IAgStkObjectRoot

[MATLAB]

% Create an instance of STK
uiApplication = actxserver('STK.Application');
uiApplication.Visible = 1;

% Get our IAgStkObjectRoot interface
root = uiApplication.Personality2;

Add an Exclusion Zone access constraint

[MATLAB]

% IAgAccessConstraintCollection accessConstraints: Access Constraint collection
excludeZone = accessConstraints.AddNamedConstraint('ExclusionZone');
excludeZone.MaxLat = 45;
excludeZone.MinLat = 15;
excludeZone.MinLon = -75;
excludeZone.MaxLon = -35;

Add and configure a central body obstruction access constraint

[MATLAB]

% IAgAccessConstraintCollection accessConstraints: Access Constraint collection
% Get IAgAccessCnstrCbObstruction interface
cbObstrConstraint = accessConstraints.AddConstraint('eCstrCbObstruction');

% AvailableObstructions returns a one dimensional array of obstruction paths
availableArray = cbObstrConstraint.AvailableObstructions;

% In this example add all available obstructions
disp('Available obstructions');
for i=1:length(availableArray)
    disp(availableArray{i, 1});
    if (strcmp(availableArray{i, 1}, 'Sun')) == false % Sun is enabled by default
        cbObstrConstraint.AddObstruction(availableArray{i, 1});
    end
end

% AssignedObstructions returns a one dimensional array of obstruction paths
assignedArray = cbObstrConstraint.AssignedObstructions;

disp('Assigned obstructions');
for i=1:length(assignedArray)
    disp(assignedArray{i, 1});
end

Add and configure a lighting condition access constraint

[MATLAB]

% IAgAccessConstraintCollection accessConstraints: Access Constraint collection

% Condition constraint
light = accessConstraints.AddConstraint('eCstrLighting');
light.Condition = 'eDirectSun';

Add and configure a LOS sun exclusion access constraint

[MATLAB]

% IAgAccessConstraintCollection accessConstraints: Access Constraint collection

% To make this more efficient, wrap this method between calls to root.BeginUpdate() and root.EndUpdate()
% Angle constraint
cnstrAngle = accessConstraints.AddConstraint('eCstrLOSSunExclusion');
cnstrAngle.Angle = 176.0;

Add and configure a lunar elevation angle access constraint

[MATLAB]

% IAgAccessConstraintCollection accessConstraints: Access Constraint collection

% To make this more efficient, wrap this method between calls to root.BeginUpdate() and root.EndUpdate()
minmax = accessConstraints.AddConstraint('eCstrLunarElevationAngle');
minmax.EnableMin = true;
minmax.Min = 11.1;
minmax.EnableMax = true;
minmax.Max = 88.8;

Add and configure a sun elevation angle access constraint

[MATLAB]

% IAgAccessConstraintCollection accessConstraints: Access Constraint collection

% To make this more efficient, wrap this method between calls to root.BeginUpdate() and root.EndUpdate()
minmax = accessConstraints.AddConstraint('eCstrSunElevationAngle');
minmax.EnableMin = true;
minmax.Min = 22.2;
minmax.EnableMax = true;
minmax.Max = 77.7;

Add and configure an altitude access constraint

[MATLAB]

% IAgAccessConstraintCollection accessConstraints: Access Constraint collection

% To make this more efficient, wrap this method between calls to root.BeginUpdate() and root.EndUpdate()
% Attitude constraint
altitude = accessConstraints.AddConstraint('eCstrAltitude');
altitude.EnableMin = true;
altitude.Min = 20.5;    % km

Add multiple access constraints of the same type to an STK Object

[MATLAB]

% IAgAccessConstraintCollection accessConstraints: Access Constraint collection


objExcl1 = accessConstraints.AddConstraint('eCstrObjectExclusionAngle');
objExcl2 = accessConstraints.AddConstraint('eCstrObjectExclusionAngle');

Compute Access with Advanced Settings

[MATLAB]

% IAgStkAccess access: Access object

access.Advanced.EnableLightTimeDelay = true;
access.Advanced.TimeLightDelayConvergence = .00005;
access.Advanced.AberrationType = 'eAberrationAnnual';
access.Advanced.UseDefaultClockHostAndSignalSense = false;
access.Advanced.ClockHost = 'eIvBase';
access.Advanced.SignalSenseOfClockHost = 'eIvTransmit';
access.ComputeAccess;

Compute an access between two STK Objects (using IAgStkObject interface)

[MATLAB]

% IAgSatellite satellite: Satellite object
% IAgFacility facility: Facility object

% Get access by STK Object
access = satellite.GetAccessToObject(facility);

% Compute access
access.ComputeAccess();

Compute an access between two STK Objects (using object path)

[MATLAB]

% IAgSatellite satellite: Satellite object

% Get access by object path
access = satellite.GetAccess('Facility/MyFacility');

% Compute access
access.ComputeAccess();

Compute an access for one point

[MATLAB]

% IAgStkObject facility: Facility object
onePtAccess = facility.CreateOnePointAccess('Satellite/MySatellite');

% Configure properties (if necessary)
onePtAccess.StartTime = root.CurrentScenario.StartTime;
onePtAccess.StopTime = root.CurrentScenario.stopTime;
onePtAccess.StepSize = 600;
onePtAccess.SummaryOption = 'eOnePtAccessSummaryDetailed';

% Compute results
results = onePtAccess.Compute();

% Print results
for i = 0:results.Count - 1
    result = results.Item(i);
    disp(['Time: ' result.Time ' HasAccess: ' num2str(result.AccessSatisfied)]);

    for j = 0:result.Constraints.Count - 1
        constraint = result.Constraints.Item(j);
        disp(['Constraint: ' constraint.Constraint ' Object: ' constraint.ObjectPath ' Status: ' constraint.Status ' Value: ' num2str(constraint.Value)]);
    end
end

Compute and extract access interval times

[MATLAB]

% IAgStkAccess access: Access calculation
% Get and display the Computed Access Intervals
intervalCollection = access.ComputedAccessIntervalTimes;

% Set the intervals to use to the Computed Access Intervals
computedIntervals = intervalCollection.ToArray(0, -1);
access.SpecifyAccessIntervals(computedIntervals);

Configure the access analysis time period to specified time instants.

[MATLAB]

% IAgStkObjectRoot root: STK Object Model root

satellite = root.GetObjectFromPath('Satellite/MySatellite');
facility = root.GetObjectFromPath('Facility/MyFacility');

% For this code snippet, let's use the time interval when the satellite reached min and max altitude values.
% Note, this assumes time at min happens before time at max.
timeOfAltMin = satellite.Vgt.Events.Item('GroundTrajectory.Detic.LLA.Altitude.TimeOfMin');
timeOfAltMax = satellite.Vgt.Events.Item('GroundTrajectory.Detic.LLA.Altitude.TimeOfMax');

% Set the access time period with the times we figured out above.
access = satellite.GetAccessToObject(facility);
access.AccessTimePeriod = 'eUserSpecAccessTime';
accessTimePeriod = access.AccessTimePeriodData;

accessTimePeriod.AccessInterval.State = 'eCrdnSmartIntervalStateStartStop';

accessStartEpoch = accessTimePeriod.AccessInterval.GetStartEpoch();
accessStartEpoch.SetImplicitTime(timeOfAltMin);
accessTimePeriod.AccessInterval.SetStartEpoch(accessStartEpoch);

accessStopEpoch = accessTimePeriod.AccessInterval.GetStopEpoch();
accessStopEpoch.SetImplicitTime(timeOfAltMax);
accessTimePeriod.AccessInterval.SetStopEpoch(accessStopEpoch);

Configure the access interval to the availability time span of the object where access is being computed to.

[MATLAB]

% IAgStkObjectRoot root: STK Object Model root

satellite = root.GetObjectFromPath('Satellite/MySatellite');
facility = root.GetObjectFromPath('Facility/MyFacility');
access = satellite.GetAccessToObject(facility);

access.AccessTimePeriod = 'eUserSpecAccessTime';
accessTimePeriod = access.AccessTimePeriodData;

if (satellite.Vgt.EventIntervals.Contains('AvailabilityTimeSpan'))
    availabilityTimeSpan = satellite.Vgt.EventIntervals.Item('AvailabilityTimeSpan');
    accessTimePeriod.AccessInterval.SetImplicitInterval(availabilityTimeSpan);
end

Get handle to the object access constraints

[MATLAB]

% IAgSatellite satellite: Satellite object
accessConstraints = satellite.AccessConstraints;

GetAccessBetweenObjectsByPath using the output of GetExistingAccesses

[MATLAB]

% IAgStkObjectRoot root: STK Object Model root
scenario = root.CurrentScenario;
accesses = scenario.GetExistingAccesses();

[row, col] = size(accesses);  % number of accesses

object1 = accesses{1, 1};   % e.g. "Satellite/MySatellite"
object2 = accesses{1, 2};  % e.g.  "Facility/MyFacility"
computed = accesses{1, 3};          % e.g. true  (if access has been computed)

access = scenario.GetAccessBetweenObjectsByPath(object1, object2);

Remove all access constraints except for Line Of Sight

[MATLAB]

% IAgAccessConstraintCollection accessConstraints: Access Constraint collection
for i=accessConstraints.Count - 1:-1:0
    constraint = accessConstraints.Item(i).ConstraintName;

    if (strcmp(constraint, 'LineOfSight')) == false
        if (strcmp(constraint, 'ExclusionZone'))
            accessConstraints.GetActiveNamedConstraint('ExclusionZone').RemoveAll;

        else
            accessConstraints.RemoveNamedConstraint(constraint);
        end
    end
end

Remove Line of Sight access constraint

[MATLAB]

% IAgAccessConstraintCollection accessConstraints: Access Constraint collection
accessConstraints.RemoveNamedConstraint('LineOfSight');

Return a list of available constraints

[MATLAB]

% IAgAccessConstraintCollection accessConstraints: Access Constraint collection
constraintArray = accessConstraints.AvailableConstraints;

disp('List of Available Constraints:');
for i=1:length(constraintArray)
   disp(constraintArray{i, 1});
end

Create a New AdvCAT Object

[MATLAB]

% IAgScenario scenario: Scenario object
advCAT = scenario.Children.New('eAdvCAT', 'AdvCAT');

Add Array of Waypoints to Aircraft

[MATLAB]

% IAgAircraft aircraft: Aircraft object
route = aircraft.Route;
ptsArray = {37.5378, 14.2207, 3.0480, 0.0772, 2;
            47.2602, 30.5517, 3.0480, 0.0772, 2};
route.SetPointsSmoothRateAndPropagate(ptsArray);
% Propagate the route
route.Propagate();

Create a New Aircraft (on the current scenario central body)

[MATLAB]

% IAgStkObjectRoot root: STK Object Model root
aircraft = root.CurrentScenario.Children.New('eAircraft', 'MyAircraft');

Set aircraft to use Realtime propagator

[MATLAB]

% IAgStkObjectRoot root: STK Object Model root
% IAgAircraft aircraft: Aircraft object
% Set route to Realtime
aircraft.SetRouteType('ePropagatorRealtime');
% Set up real time propagator settings
aircraft.Route.TimeStep = 1; % sec
aircraft.Route.TimeoutGap = 1; % sec
aircraft.Route.Duration.LookAhead = 1; % sec
aircraft.Route.LookAheadPropagator = 'eLookAheadHoldCBFPosition';
aircraft.Route.Propagate();
% Add a realtime waypoint
aircraft.Route.PointBuilder.LLA.AddPosition(root.CurrentTime, 40, -70, 1000);

Set Great Arc Propagator and Add Individual Waypoints to Aircraft

[MATLAB]

% IAgAircraft aircraft: Aircraft object
% Set route to great arc, method and altitude reference
aircraft.SetRouteType('ePropagatorGreatArc');
route = aircraft.Route;
route.Method = 'eDetermineTimeAccFromVel';
route.SetAltitudeRefType('eWayPtAltRefMSL');
% Add first point
waypoint = route.Waypoints.Add();
waypoint.Latitude = 37.5378;
waypoint.Longitude = 14.2207;
waypoint.Altitude = 5;  % km
waypoint.Speed = .1;    % km/sec
% Add second point
waypoint2 = route.Waypoints.Add();
waypoint2.Latitude = 47.2602;
waypoint2.Longitude = 30.5517;
waypoint2.Altitude = 5; % km
waypoint2.Speed = .1;    % km/sec
% Propagate the route
route.Propagate();

Set the Attitude of the Aircraft

[MATLAB]

% IAgAircraft aircraft: Aircraft object
aircraft.Attitude.Basic.SetProfileType('eCoordinatedTurn');

Set the Propagator to GreatArc and set the start time

[MATLAB]

% IAgAircraft aircraft: Aircraft object
% Set the propagator to GreatArc
aircraft.SetRouteType('ePropagatorGreatArc');

% Set the start time to a new start time
aircraft.Route.EphemerisInterval.SetExplicitInterval('25 Dec 2019 00:00:00.00', '25 Dec 2019 00:00:00.00'); % stop time computed based on Propagate call
aircraft.Route.Propagate();

Create an area target (on the current scenario central body)

[MATLAB]

% IAgStkObjectRoot root: STK Object Model Root

% Create the AreaTarget on the current scenario central body (use
% NewOnCentralBody to specify explicitly the central body)
areaTarget = root.CurrentScenario.Children.New('eAreaTarget', 'MyAreaTarget');

Define area target boundary and position from list of lat/lon/alt

[MATLAB]

% IAgStkObjectRoot root: STK Object Model Root
% IAgAreaTarget areaTarget: AreaTarget object

% By using the fine grained interfaces,
% BeginUpdate/EndUpdate prevent intermediate redraws
root.BeginUpdate();
areaTarget.AreaType = 'ePattern';
patterns = areaTarget.AreaTypeData;
patterns.Add(48.897, 18.637);
patterns.Add(46.534, 13.919);
patterns.Add(44.173, 21.476);
root.EndUpdate();
areaTarget.AutoCentroid = true;

Define area target boundary and position from list of lat/lon/alt (using common tasks)

[MATLAB]

% IAgStkObjectRoot root: STK Object Model Root
% IAgAreaTarget areaTarget: AreaTarget object
% Remove all points in the area target
areaTarget.AreaTypeData.RemoveAll;

% By using the CommonTasks interface,
% make an array of latitude and longitude boundary points
boundary = {29, -12;
            29, 34;
            6, 34;
            6, -12};

% SetAreaTypePattern expects a two dimensional array of latitude and longitude values
areaTarget.CommonTasks.SetAreaTypePattern(boundary);

List all points in an area target

[MATLAB]

% IAgAreaTarget areaTarget: AreaTarget object
if strcmp(areaTarget.AreaType, 'ePattern')

    % Get IAgAreaTypePatternCollection interface from AreaTypeData
    patternPoints = areaTarget.AreaTypeData;

    % ToArray returns a two dimensional array of latitude and longitude points
    areaTargetPoints = patternPoints.ToArray();

    disp('All points in Area Target');
    for i= 1:length(areaTargetPoints)
        disp(['Latitude ' num2str(areaTargetPoints{i, 1}) ' Longitude: ' num2str(areaTargetPoints{i, 2})]);
    end
end

Set an elliptical area target

[MATLAB]

% IAgStkObjectRoot root: STK Object Model Root
% IAgAreaTarget areaTarget: AreaTarget object

% By using the fine grained interfaces,
% BeginUpdate/EndUpdate prevent intermediate redraws
root.BeginUpdate();
areaTarget.AreaType = 'eEllipse';
ellipse = areaTarget.AreaTypeData;
ellipse.SemiMajorAxis = 85.25; % in km (distance dimension)
ellipse.SemiMinorAxis = 80.75; % in km (distance dimension)
ellipse.Bearing = 44; % in deg (angle dimension)
root.EndUpdate();

Set an elliptical area target (using common tasks)

[MATLAB]

% IAgStkObjectRoot root: STK Object Model Root
% IAgAreaTarget areaTarget: AreaTarget object

% By using the CommonTasks interface
areaTarget.CommonTasks.SetAreaTypeEllipse(85.25, 80.75, 44);

Create a chain (on the current scenario central body)

[MATLAB]

% IAgStkObjectRoot root: STK Object Model Root
% Create the Chain on the current scenario central body (use
% NewOnCentralBody to specify explicitly the central body)
chain = root.CurrentScenario.Children.New('eChain', 'MyChain');

Define and compute a chain (advanced)

[MATLAB]

% IAgScenario scenario: Scenario object
% IAgChain chain: Chain object

% Remove all previous accesses
chain.ClearAccess();

% Add some objects to chain
chain.StartObject = scenario.Children.GetItemByName('fac1');
chain.EndObject = scenario.Children.GetItemByName('air1');

connections = chain.Connections;
connections.Add(scenario.Children.GetItemByName('sat2'), scenario.Children.GetItemByName('air1'), 1, 1);
connections.Add(scenario.Children.GetItemByName('fac1'), scenario.Children.GetItemByName('sat1'), 1, 1);
connections.Add(scenario.Children.GetItemByName('sat1'), scenario.Children.GetItemByName('sat2'), 1, 1);

% Configure chain parameters
chain.AutoRecompute = false;
chain.EnableLightTimeDelay = false;
chain.TimeConvergence = 0.001;
chain.DataSaveMode = 'eSaveAccesses';

% Specify our own time period
chain.SetTimePeriodType('eUserSpecifiedTimePeriod');

% Get chain time period interface
chainUserTimePeriod = chain.TimePeriod;
chainUserTimePeriod.TimeInterval.SetExplicitInterval( ...
    scenario.AnalysisInterval.FindStartTime(), ...
    scenario.AnalysisInterval.FindStopTime()); % Set to scenario period

% Compute the chain
chain.ComputeAccess();

Define and compute a chain (basic)

[MATLAB]

% IAgScenario scenario: Scenario object
% IAgChain chain: Chain object

chain.StartObject = scenario.Children.GetItemByName('fac1');
chain.EndObject = scenario.Children.GetItemByName('air1');

connections = chain.Connections;
connections.Add(scenario.Children.GetItemByName('sat2'), scenario.Children.GetItemByName('air1'), 1, 1);
connections.Add(scenario.Children.GetItemByName('fac1'), scenario.Children.GetItemByName('sat1'), 1, 1);
connections.Add(scenario.Children.GetItemByName('sat1'), scenario.Children.GetItemByName('sat2'), 1, 1);

% Compute the chain
chain.ComputeAccess();

Prints the strand intervals of chain object

[MATLAB]

% IAgChain chain: Chain Object
% Compute the chain access if not done already.
chain.ComputeAccess();

% Considered Start and Stop time
disp(['Chain considered start time: ' chain.Vgt.Events.Item('ConsideredStartTime').FindOccurrence.Epoch]);
disp(['Chain considered stop time: ', chain.Vgt.Events.Item('ConsideredStopTime').FindOccurrence.Epoch]);

objectParticipationIntervals = chain.Vgt.EventIntervalCollections.Item('StrandAccessIntervals');
intervalListResult = objectParticipationIntervals.FindIntervalCollection();

for i = 0:intervalListResult.IntervalCollections.Count -1

    if intervalListResult.IsValid

        disp(['Link Name: ' objectParticipationIntervals.Labels(i+1)]);
        disp('--------------');
        for j = 0:intervalListResult.IntervalCollections.Item(i).Count - 1

            startTime = intervalListResult.IntervalCollections.Item(i).Item(j).Start;
            stopTime = intervalListResult.IntervalCollections.Item(i).Item(j).Stop;
            disp(['Start: ' startTime ' Stop: ' stopTime]);
        end
    end
end

Create a New Antenna Object

[MATLAB]

% IAgStkObject satellite: STK object
antenna = satellite.Children.New('eAntenna', 'MyAntenna');

Modify Antenna Graphics

[MATLAB]

% IAgAntenna antenna: Antenna object
contours = antenna.Graphics.ContourGraphics;
contours.SetContourType('eAntennaContourTypeGain');
contours.Show = true;
for i = -30:5:30
    contours.Contour.Levels.Add(i);
end
antenna.VO.ShowContours = true;
antenna.VO.VolumeGraphics.Show = true;
antenna.VO.VolumeGraphics.GainScale = 0.005; % km

Modify Antenna Model Type

[MATLAB]

% IAgAntenna antenna: Antenna object
antenna.ModelComponentLinking.SetComponent('Dipole');
antennaModel = antenna.ModelComponentLinking.Component;
antennaModel.DesignFrequency = 15; % GHz
antennaModel.Length = 1.5; % m
antennaModel.LengthToWavelengthRatio = 45;
antennaModel.Efficiency = 85; % Percent

Modify Antenna Orientation and Position

[MATLAB]

% IAgAntenna antenna: Antenna object
antOrientation = antenna.Orientation;
antOrientation.AssignAzEl(0, -90, 1) % 1 represents Rotate About Boresight
antOrientation.PositionOffset.X = 0.0; % m
antOrientation.PositionOffset.Y = 1; % m
antOrientation.PositionOffset.Z = 0.25; % m

Modify Antenna Refraction

[MATLAB]

% IAgAntenna antenna: Antenna object
antenna.UseRefractionInAccess = true;
antenna.Refraction = 'eITU_R_P834_4';
refraction = antenna.RefractionModel;
refraction.Ceiling = 5000; % m
refraction.AtmosAltitude = 10000; % m
refraction.KneeBendFactor = 0.2;

Create a New Receiver Object

[MATLAB]

% IAgStkObject satellite: STK object
receiver = satellite.Children.New('eReceiver', 'MyReceiver');

Modify Orientation of the Receiver Antenna

[MATLAB]

% IAgReceiver receiver: Receiver object
receiver.ModelComponentLinking.SetComponent('Complex Receiver Model');
recModel = receiver.ModelComponentLinking.Component;
antennaControl = recModel.AntennaControl;
antOrientation = antennaControl.EmbeddedModelOrientation;
antOrientation.AssignAzEl(45, 85, 1); % 1 represents Rotate About Boresight
antOrientation.PositionOffset.X = 0.5; % m
antOrientation.PositionOffset.Y = 0.75; % m
antOrientation.PositionOffset.Z = 1; % m

Modify Receiver Demodulator Properties

[MATLAB]

% IAgReceiver receiver: Receiver object
recModel = receiver.ModelComponentLinking.Component;
recModel.AutoSelectDemodulator = false;
recModel.SetDemodulator('16PSK');

Modify Receiver Embedded Antenna

[MATLAB]

% IAgReceiver receiver: Receiver object
receiver.ModelComponentLinking.SetComponent('Complex Receiver Model');
recModel = receiver.ModelComponentLinking.Component;
antennaControl = recModel.AntennaControl;
antennaControl.EmbeddedModelComponentLinking.SetComponent('Hemispherical');
antennaControl.EmbeddedModelComponentLinking.Component.Efficiency = 85; % Percent

Modify Receiver Filter Properties

[MATLAB]

% IAgReceiver receiver: Receiver object
recModel = receiver.ModelComponentLinking.Component;
recModel.EnableFilter = true;
recModel.FilterComponentLinking.SetComponent('Bessel');
recFilter = recModel.FilterComponentLinking.Component;
recFilter.LowerBandwidthLimit = -20;
recFilter.UpperBandwidthLimit = 20;
recFilter.CutoffFrequency = 10;

Modify Receiver Model Type

[MATLAB]

% IAgReceiver receiver: Receiver object
receiver.ModelComponentLinking.SetComponent('Complex Receiver Model');
recModel = receiver.ModelComponentLinking.Component;
recModel.AutoTrackFrequency = false;
recModel.Frequency = 11.81;

Modify Receiver Polarization Properties

[MATLAB]

% IAgReceiver receiver: Receiver object
recModel = receiver.ModelComponentLinking.Component;
recModel.EnablePolarization = true;
recModel.SetPolarizationType('ePolarizationTypeLinear');
polarization = recModel.Polarization;
polarization.ReferenceAxis = 'ePolarizationReferenceAxisZ';
polarization.CrossPolLeakage = -60; % dB

Modify Receiver System Noise Temperature

[MATLAB]

% IAgReceiver receiver: Receiver object
receiver.ModelComponentLinking.SetComponent('Complex Receiver Model');
recModel = receiver.ModelComponentLinking.Component;
recModel.SystemNoiseTemperature.ConstantNoiseTemperature = 280; % K

Receiver additional Gain

[MATLAB]

% IAgReceiver receiver: Receiver object
recModel = receiver.ModelComponentLinking.Component;
gain = recModel.PreReceiveGainsLosses.Add(5); % dB
gain.Identifier = 'Example Gain';

Create a New Transmitter Object

[MATLAB]

% IAgStkObject satellite: STK object
transmitter = satellite.Children.New('eTransmitter', 'MyTransmitter');

Modify the Linked Antenna

[MATLAB]

% IAgTransmitter transmitter: Transmitter object
transmitter.ModelComponentLinking.SetComponent('Complex Transmitter Model')
transmitter.ModelComponentLinking.Component.AntennaControl.ReferenceType = 'eAntennaControlRefTypeLink';
transmitter.ModelComponentLinking.Component.AntennaControl.LinkedAntennaObject = 'Antenna/MyAntenna';

Modify Transmitter Embedded Antenna

[MATLAB]

% IAgTransmitter transmitter: Transmitter object
transmitter.ModelComponentLinking.SetComponent('Complex Transmitter Model');
txModel = transmitter.ModelComponentLinking.Component;
antennaControl = txModel.AntennaControl;
antennaControl.EmbeddedModelComponentLinking.SetComponent('Isotropic');
antennaControl.EmbeddedModelComponentLinking.Component.Efficiency = 85; % Percent

Modify Transmitter Filter

[MATLAB]

% IAgTransmitter transmitter: Transmitter object
txModel = transmitter.ModelComponentLinking.Component;
txModel.EnableFilter = true;
txModel.FilterComponentLinking.SetComponent('Butterworth');
recFilter = txModel.FilterComponentLinking.Component;
recFilter.LowerBandwidthLimit = -20;
recFilter.UpperBandwidthLimit = 20;
recFilter.CutoffFrequency = 10;

Modify Transmitter Model Type

[MATLAB]

% IAgTransmitter transmitter: Transmitter object
transmitter.ModelComponentLinking.SetComponent('Complex Transmitter Model');
txModel = transmitter.ModelComponentLinking.Component;
txModel.Frequency = 14; % GHz
txModel.Power = 25; % dBW
txModel.DataRate = 15; % Mb/sec

Modify Transmitter Modulator Properties

[MATLAB]

% IAgTransmitter transmitter: Transmitter object
txModel = transmitter.ModelComponentLinking.Component;
txModel.SetModulator('BPSK');
txModel.Modulator.AutoScaleBandwidth = true;

Modify Transmitter Orientation and Position

[MATLAB]

% IAgTransmitter transmitter: Transmitter object
transmitter.ModelComponentLinking.SetComponent('Complex Transmitter Model');
txModel = transmitter.ModelComponentLinking.Component;
antennaControl = txModel.AntennaControl;
antOrientation = antennaControl.EmbeddedModelOrientation;
antOrientation.AssignAzEl(0, 90, 1); % 1 represents Rotate About Boresight
antOrientation.PositionOffset.X = 0.0; % m
antOrientation.PositionOffset.Y = 1; % m
antOrientation.PositionOffset.Z = 0.25; % m

Modify Transmitter Polarization Properties

[MATLAB]

% IAgTransmitter transmitter: Transmitter object
transmitter.ModelComponentLinking.SetComponent('Complex Transmitter Model');
txModel = transmitter.ModelComponentLinking.Component;
txModel.EnablePolarization = true;
txModel.SetPolarizationType('ePolarizationTypeLinear');
polarization = txModel.Polarization;
polarization.ReferenceAxis = 'ePolarizationReferenceAxisY';
polarization.TiltAngle = 15; % deg

Transmitter additional Gain

[MATLAB]

% IAgTransmitter transmitter: Transmitter object
txModel = transmitter.ModelComponentLinking.Component;
gain = txModel.PostTransmitGainsLosses.Add(-5); % dB
gain.Identifier = 'Example Loss';

Define a constellation

[MATLAB]

% IAgStkObjectRoot root: STK Object Model Root
% IAgSatellite satellite: Satellite object
constellation = root.CurrentScenario.Children.New('eConstellation', 'MyConstellation');
constellation.Objects.AddObject(satellite);
constellation.Objects.Add('*/Facility/MyFacility');

Add Grid Constraint to Coverage

[MATLAB]

% IAgCoverageDefinition coverage: Coverage object
coverage.PointDefinition.GridClass = 'eGridClassFacility';
coverage.PointDefinition.UseGridSeed =  true;
coverage.PointDefinition.SeedInstance = 'Facility/MyFacility';

Compute Coverage

[MATLAB]

% IAgCoverageDefinition coverage: Coverage object
coverage.ComputeAccesses;

Create a New CoverageDefinition (on the current scenario central body)

[MATLAB]

% IAgScenario scenario: Scenario object
% Create new Coverage Definition and set the Bounds to an area target
coverage = scenario.Children.New('eCoverageDefinition', 'MyCoverage');
coverage.Grid.BoundsType = 'eBoundsCustomRegions';
covGrid = coverage.Grid;
bounds = covGrid.Bounds;
bounds.AreaTargets.Add('AreaTarget/MyAreaTarget');
% Define the Grid Resolution
Res = covGrid.Resolution;
Res.LatLon = .5;   % deg
% Set the satellite as the Asset
coverage.AssetList.Add('Satellite/MySatellite');

% Turn off Show Grid Points
coverage.Graphics.Static.IsPointsVisible = false;

Set Advanced Settings for Coverage

[MATLAB]

% IAgCoverageDefinition coverage: Coverage object
advanced = coverage.Advanced;
advanced.AutoRecompute = false;
advanced.DataRetention = 'eAllData';
advanced.SaveMode = 'eSaveAccesses';

Set the Coverage Interval to an object's availability Analysis interval

[MATLAB]

% IAgSatellite satellite: Satellite object
% IAgCoverageDefinition coverage: Coverage object
satVGT = satellite.Vgt;
AvailTimeSpan = satVGT.EventIntervals.Item('AvailabilityTimeSpan');
IntResult = AvailTimeSpan.FindInterval;
coverage.Interval.AnalysisInterval.SetStartAndStopTimes(IntResult.Interval.Start, IntResult.Interval.Stop)

Extracting Elements from Data Providers with Groups

[MATLAB]

% IAgStkObjectRoot root: STK Object Model root
% IAgSatellite satellite: Satellite object
% IAgScenario scenario: Scenario object
% Change DateFormat dimension to epoch seconds to make the data easier to handle in
% MATLAB
root.UnitPreferences.Item('DateFormat').SetCurrentUnit('EpSec');
satPosDP = satellite.DataProviders.Item('Cartesian Position').Group.Item('ICRF').Exec(scenario.StartTime, scenario.StopTime, 60);
satx = cell2mat(satPosDP.DataSets.GetDataSetByName('x').GetValues);
saty = cell2mat(satPosDP.DataSets.GetDataSetByName('y').GetValues);
satz = cell2mat(satPosDP.DataSets.GetDataSetByName('z').GetValues);

satVelDP = satellite.DataProviders.GetDataPrvTimeVarFromPath('Cartesian Velocity/ICRF').Exec(scenario.StartTime, scenario.StopTime, 60);
% There are 4 Methods to get DP From a Path depending on the kind of DP:
%   GetDataPrvTimeVarFromPath
%   GetDataPrvIntervalFromPath
%   GetDataPrvInfoFromPath
%   GetDataPrvFixedFromPath
satvx = cell2mat(satVelDP.DataSets.GetDataSetByName('x').GetValues);
satvy = cell2mat(satVelDP.DataSets.GetDataSetByName('y').GetValues);
satvz = cell2mat(satVelDP.DataSets.GetDataSetByName('z').GetValues);

Extracting Elements from Data Providers with PreData

[MATLAB]

% IAgStkObjectRoot root: STK Object Model root
% IAgFacility facility: Facility object
% IAgScenario scenario: Scenario object
% Change DateFormat dimension to epoch seconds to make the data easier to handle in
% MATLAB
root.UnitPreferences.Item('DateFormat').SetCurrentUnit('EpSec');
facChooseDP = facility.DataProviders.Item('Points Choose System');
dataProvCenter = facChooseDP.Group.Item('Center');
% Choose the reference system you want to report the Center point in
dataProvCenter.PreData = 'CentralBody/Earth TOD';
rptElems = {'Time';'x';'y';'z'};
results = dataProvCenter.ExecElements(scenario.StartTime, scenario.StopTime, 60, rptElems);
datasets = results.DataSets;
Time = cell2mat(datasets.GetDataSetByName('Time').GetValues);
facTODx = cell2mat(datasets.GetDataSetByName('x').GetValues);
facTODy = cell2mat(datasets.GetDataSetByName('y').GetValues);
facTODz = cell2mat(datasets.GetDataSetByName('z').GetValues);

Getting Data for a Single Point in Time

[MATLAB]

% IAgStkObjectRoot root: STK Object Model root
% IAgSatellite satellite: Satellite object
% Change DateFormat dimension to epoch seconds to make the data easier to handle in
% MATLAB
root.UnitPreferences.Item('DateFormat').SetCurrentUnit('EpSec');
satPassDP = satellite.DataProviders.Item('Precision Passes').ExecSingle(2600);
pass = cell2mat(satPassDP.DataSets.GetDataSetByName('Precision Pass Number').GetValues);

Getting Data for Specific Points and Elements

[MATLAB]

% IAgStkObjectRoot root: STK Object Model root
% IAgSatellite satellite: Satellite object
% Change DateFormat dimension to epoch seconds to make the data easier to handle in
% MATLAB
root.UnitPreferences.Item('DateFormat').SetCurrentUnit('EpSec');
times = {0;15000;20000;55000};
elems = {'Time';'Precision Pass Number'};
satPassesDP = satellite.DataProviders.Item('Precision Passes').ExecSingleElementsArray(times, elems);
passes = cell2mat(satPassesDP.GetArray(cast(1, 'int32')));

Getting Time Dependent Data that's broken into Sections

[MATLAB]

% IAgStkObjectRoot root: STK Object Model root
% IAgScenario scenario: Scenario object
% IAgStkAccess access: Access calculation
% Change DateFormat dimension to epoch seconds to make the data easier to handle in
% MATLAB
root.UnitPreferences.Item('DateFormat').SetCurrentUnit('EpSec');
accessAER = access.DataProviders.Item('AER Data').Group.Item('BodyFixed').Exec(scenario.StartTime, scenario.StopTime, 60);
AERTimes = cell2mat(accessAER.Interval.Item(cast(0, 'int32')).DataSets.GetDataSetByName('Time').GetValues);
Az = cell2mat(accessAER.Interval.Item(cast(0, 'int32')).DataSets.GetDataSetByName('Azimuth').GetValues);
El = cell2mat(accessAER.Interval.Item(cast(0, 'int32')).DataSets.GetDataSetByName('Elevation').GetValues);
for i = 1:1:accessAER.Interval.Count-1
    AERTimes = [AERTimes; cell2mat(accessAER.Interval.Item(cast(i, 'int32')).DataSets.GetDataSetByName('Time').GetValues)];
    Az = [Az; cell2mat(accessAER.Interval.Item(cast(i, 'int32')).DataSets.GetDataSetByName('Azimuth').GetValues)];
    El = [El; cell2mat(accessAER.Interval.Item(cast(i, 'int32')).DataSets.GetDataSetByName('Elevation').GetValues)];
end

Using a Time Dependent Data Provider and requesting only specified elements

[MATLAB]

% IAgStkObjectRoot root: STK Object Model root
% IAgSatellite satellite: Satellite object
% IAgScenario scenario: Scenario object
% Change DateFormat dimension to epoch seconds to make the data easier to handle in
% MATLAB
root.UnitPreferences.Item('DateFormat').SetCurrentUnit('EpSec');
elems = {'Time';'q1';'q2';'q3';'q4'};
satDP = satellite.DataProviders.Item('Attitude Quaternions').ExecElements(scenario.StartTime, scenario.StopTime, 60, elems);
% Whenever you pass an index to an array, you need to cast it to a long
% equivalent (int32)
satTime = cell2mat(satDP.DataSets.Item(cast(0, 'int32')).GetValues);
satq1 = cell2mat(satDP.DataSets.Item(cast(1, 'int32')).GetValues);
satq2 = cell2mat(satDP.DataSets.Item(cast(2, 'int32')).GetValues);
satq3 = cell2mat(satDP.DataSets.Item(cast(3, 'int32')).GetValues);
satq4 = cell2mat(satDP.DataSets.Item(cast(4, 'int32')).GetValues);

Using a Time Independent Data Provider

[MATLAB]

% IAgStkObjectRoot root: STK Object Model root
% IAgFacility facility: Facility object
% Change DateFormat dimension to epoch seconds to make the data easier to handle in
% MATLAB
root.UnitPreferences.Item('DateFormat').SetCurrentUnit('EpSec');
facDP = facility.DataProviders.Item('Cartesian Position').Exec;
facx = cell2mat(facDP.DataSets.GetDataSetByName('x').GetValues);
facy = cell2mat(facDP.DataSets.GetDataSetByName('y').GetValues);
facz = cell2mat(facDP.DataSets.GetDataSetByName('z').GetValues);

Using an interval Data Provider

[MATLAB]

% IAgStkObjectRoot root: STK Object Model root
% IAgSatellite satellite: Satellite object
% IAgFacility facility: Facility object

% Change DateFormat dimension to epoch seconds to make the data easier to handle in
% MATLAB
root.UnitPreferences.Item('DateFormat').SetCurrentUnit('EpSec');
% Get the current scenario
scenario = root.CurrentScenario;
% Set up the access object
access = satellite.GetAccessToObject(facility);
access.ComputeAccess;
% Get the Access AER Data Provider
accessDP = access.DataProviders.Item('Access Data').Exec(scenario.StartTime, scenario.StopTime);
% DP results return cell data types.  cell2mat
accessStartTimes = cell2mat(accessDP.DataSets.GetDataSetByName('Start Time').GetValues);
accessStopTimes = cell2mat(accessDP.DataSets.GetDataSetByName('Stop Time').GetValues);

Add an AzEl Mask to a Facility

[MATLAB]

% IAgFacility facility: Facility Object
facility.SetAzElMask('eTerrainData', 0);

Create a facility (on the current scenario central body)

[MATLAB]

% IAgStkObjectRoot root: STK Object Model Root
facility = root.CurrentScenario.Children.New('eFacility', 'MyFacility');

Set the geodetic position of the facility

[MATLAB]

% IAgFacility facility: Facility Object
facility.Position.AssignGeodetic(41.9849, 21.4039, 0) % Latitude, Longitude, Altitude

% Set altitude to height of terrain
facility.UseTerrain = true;

% Set altitude to a distance above the ground
facility.HeightAboveGround = .05;   % km

Display the AzElMask in 2D/3D

[MATLAB]

% IAgFacility facility: Facility Object
azelMask = facility.Graphics.AzElMask;
azelMask.RangeVisible = true;
azelMask.NumberOfRangeSteps = 10;
azelMask.DisplayRangeMinimum = 0;   % km
azelMask.DisplayRangeMaximum = 100;  % km
azelMask.RangeColorVisible = true;
azelMask.RangeColor = 16776960; % cyan

Configure the Contours of the FOM and define a color ramp

[MATLAB]

% IAgCoverageDefinition coverage: Coverage object
% IAgFigureOfMerit fom: Figure Of Merit object
satisfaction = coverage.Graphics.Static;
satisfaction.IsRegionVisible = false;
Animation = fom.VO.Animation;
Animation.IsVisible = false;
VOcontours = fom.VO.Static;
VOcontours.IsVisible = true;
contours = fom.Graphics.Static.Contours;
contours.IsVisible = true;
contours.ContourType = 'eSmoothFill';
contours.ColorMethod = 'eColorRamp';
contours.LevelAttributes.RemoveAll;

contours.LevelAttributes.AddLevelRange(590, 660, 10);   % Start, Start, Step
contours.RampColor.StartColor = 255;        % Red
contours.RampColor.EndColor = 16711680;     % Blue

Create a new Figure of Merit of type Access Duration

[MATLAB]

% IAgCoverageDefinition coverage: Coverage object
fom = coverage.Children.New('eFigureOfMerit', 'AccessDuration');
fom.SetDefinitionType('eFmAccessDuration');
fom.Definition.SetComputeType('eMaximum');

Add Array of Waypoints to Ground Vehicle and Interpolate over Terrain

[MATLAB]

% IAgGroundVehicle grndVehicle: Ground Vehicle object
route = grndVehicle.Route;
ptsArray = {41.97766217, 21.44863761, 0, 0.026, .5;
            41.97422351, 21.39956154, 0, 0.026, .5;
            41.99173299, 21.40796942, 0, 0.026, .5};
route.SetPointsSmoothRateAndPropagate(ptsArray);
route.SetAltitudeRefType('eWayPtAltRefTerrain');
route.AltitudeRef.Granularity = .001;
route.AltitudeRef.InterpMethod = 'eWayPtTerrainHeight';
% Propagate the route
route.Propagate();

Create a New Ground Vehicle (on the current scenario central body)

[MATLAB]

% IAgScenario scenario: Scenario object
grndVehicle = scenario.Children.New('eGroundVehicle', 'MyVehicle');
grndVehicle.SetRouteType('ePropagatorGreatArc');

Set Great Arc Propagator and Add Individual Waypoints to Ground Vehicle

[MATLAB]

% IAgGroundVehicle grndVehicle: Ground Vehicle object
% Set route to great arc, method and altitude reference
grndVehicle.SetRouteType('ePropagatorGreatArc');
route = grndVehicle.Route;
route.Method = 'eDetermineTimeAccFromVel';
route.SetAltitudeRefType('eWayPtAltRefWGS84');
% Add first point
waypoint = route.Waypoints.Add();
waypoint.Latitude = 56.18;
waypoint.Longitude = 40.91;
waypoint.Altitude = 0;  % km
waypoint.Speed = .026;    % km/sec
% Add second point
waypoint2 = route.Waypoints.Add();
waypoint2.Latitude = 50.22;
waypoint2.Longitude = 11.05;
waypoint2.Altitude = 0; % km
waypoint2.Speed = .026;    % km/sec
% Propagate the route
route.Propagate();

Create a New LineTarget (on the current scenario central body)

[MATLAB]

% IAgScenario scenario: Scenario object
lineTarget = scenario.Children.New('eLineTarget', 'MyLineTarget');
point1 = lineTarget.Points.Add(34.72, -118.34);
point2 = lineTarget.Points.Add(30.83, -82.67);

Create a New Missile (on the current scenario central body)

[MATLAB]

% IAgScenario scenario: Scenario object
missile = scenario.Children.New('eMissile', 'MyMissile');
missile.SetTrajectoryType('ePropagatorBallistic');
trajectory = missile.Trajectory;
root.UnitPreferences.Item('DateFormat').SetCurrentUnit('EpSec');
trajectory.EphemerisInterval.SetExplicitInterval(0, 0) % stop time later computed based on propagation
trajectory.Launch.Lat = 29;
trajectory.Launch.Lon = -81;
trajectory.ImpactLocation.Impact.Lat = 27;
trajectory.ImpactLocation.Impact.Lon = -43;
trajectory.ImpactLocation.SetLaunchControlType('eLaunchControlFixedApogeeAlt');
trajectory.ImpactLocation.LaunchControl.ApogeeAlt = 1200;   % km
trajectory.Propagate();

Create a New MTO (on the current scenario central body)

[MATLAB]

% IAgScenario scenario: Scenario object
mto = scenario.Children.New('eMTO', 'MyMTO');
root.UnitPreferences.Item('DateFormat').SetCurrentUnit('EpSec');
mtoTimes = {0; 7200};
mtoLats = {36.77; 34.80};
mtoLons = {-77.25; -78.37};
mtoAlts = {5; 5};

track1 = mto.Tracks.AddTrack(1, mtoTimes, mtoLats, mtoLons, mtoAlts);
track1.Interpolate = true;
% Change the color of the track
mto.Graphics.Tracks.GetTrackFromId(1).Color = 255;

Load MTO track points from file

[MATLAB]

% LoadPoints expects the path an Ephemeris file path
% IAgMto mto: MTO Object
track2 = mto.Tracks.Add(2);
track2.Points.LoadPoints('C:\Program Files\AGI\STK_ODTK 13\Data\Resources\stktraining\text\EphemerisLLATimePosVel_Example.e');
track2.Interpolate = true;

Compute Object Coverage

[MATLAB]

% IAgAircraft aircraft: Aircraft object
objCoverage = aircraft.ObjectCoverage;
objCoverage.Assets.RemoveAll;
objCoverage.Assets.Add('Satellite/MySatellite');
objCoverage.UseObjectTimes = true;
objCoverage.Compute;

objCoverageFOM = objCoverage.FOM;
if objCoverageFOM.IsDefinitionTypeSupported('eFmAccessDuration')
    objCoverageFOM.SetDefinitionType('eFmAccessDuration');
    objCoverageFOM.Definition.SetComputeType('eMaximum');
end

Create a New Planet

[MATLAB]

% IAgScenario scenario: Scenario object
planet = scenario.Children.New('ePlanet', 'Mars');
planet.CommonTasks.SetPositionSourceCentralBody('Mars', 'eEphemJPLDE');

Modify Planet 2D Properties

[MATLAB]

% IAgPlanet planet: Planet object
planet2D = planet.Graphics;
planet2D.Color = 255;   % Red
planet2D.Inherit = false;
planet2D.OrbitVisible = true;
planet2D.SubPlanetPointVisible = false;
planet2D.SubPlanetLabelVisible = false;

Create a satellite (on the current scenario central body)

[MATLAB]

% IAgStkObjectRoot root: STK Object Model Root
satellite = root.CurrentScenario.Children.New('eSatellite', 'MySatellite');

Export an ephemeris file to scenario folder

[MATLAB]

% IAgStkObjectRoot root: STK Object Model Root
% IAgSatellite satellite: Satellite object
scenPath = root.ExecuteCommand('GetDirectory / Scenario').Item(0);
satelliteFilePath = [scenPath '\' satellite.InstanceName '.e'];
satellite.ExportTools.GetEphemerisStkExportTool.Export(satelliteFilePath);

Set initial state of satellite and propagate

[MATLAB]

% IAgSatellite satellite: Satellite object
keplerian = satellite.Propagator.InitialState.Representation.ConvertTo('eOrbitStateClassical'); % Use the Classical Element interface
keplerian.SizeShapeType = 'eSizeShapeAltitude';  % Changes from Ecc/Inc to Perigee/Apogee Altitude
keplerian.LocationType = 'eLocationTrueAnomaly'; % Makes sure True Anomaly is being used
keplerian.Orientation.AscNodeType = 'eAscNodeLAN'; % Use LAN instead of RAAN for data entry

% Assign the perigee and apogee altitude values:
keplerian.SizeShape.PerigeeAltitude = 500;      % km
keplerian.SizeShape.ApogeeAltitude = 600;       % km

% Assign the other desired orbital parameters:
keplerian.Orientation.Inclination = 90;         % deg
keplerian.Orientation.ArgOfPerigee = 12;        % deg
keplerian.Orientation.AscNode.Value = 24;       % deg
keplerian.Location.Value = 180;                 % deg

% Apply the changes made to the satellite's state and propagate:
satellite.Propagator.InitialState.Representation.Assign(keplerian);
satellite.Propagator.Propagate();

Set satellite attitude basic spinning

[MATLAB]

% IAgSatellite satellite: Satellite object
basic = satellite.Attitude.Basic;
basic.SetProfileType('eProfileSpinning')
basic.Profile.Body.AssignXYZ(0, 0, 1)
basic.Profile.Inertial.AssignXYZ(0, 1, 0);
basic.Profile.Rate = 6;  % rev/sec

Set satellite attitude external

[MATLAB]

% IAgSatellite satellite: Satellite object
satellite.Attitude.External.Load('C:\Program Files\AGI\STK_ODTK 13\Data\Resources\stktraining\text\AttitudeTimeEulerAngles_Example.a');

Set satellite attitude targeting

[MATLAB]

% IAgSatellite satellite: Satellite object
attitudePointing = satellite.Attitude.Pointing;
attitudePointing.UseTargetPointing = 1;
attitudePointing.Targets.RemoveAll;
attitudePointing.Targets.Add('AreaTarget/MyAreaTarget');
attitudePointing.TargetTimes.UseAccessTimes;

Set satellite model pointing

[MATLAB]

% IAgSatellite satellite: Satellite object
satellite.VO.Model.ModelData.Filename = 'C:\Program Files\AGI\STK_ODTK 13\STKData\VO\Models\Space\iss.glb'
satellite.VO.ModelPointing.AddInterval('SPP_Arrays-000000', 'Sun', root.CurrentScenario.StartTime, root.CurrentScenario.StopTime);

Set satellite propagator to Astrogator and clear segments

[MATLAB]

% IAgSatellite satellite: Satellite object
satellite.SetPropagatorType('ePropagatorAstrogator');
driver = satellite.Propagator;
% Clear all segments from the MCS
driver.MainSequence.RemoveAll();

Set satellite propagator to HPOP and set force model properties

[MATLAB]

% IAgSatellite satellite: Satellite object
satellite.SetPropagatorType('ePropagatorHPOP');
set(satellite.Propagator, 'Step', 60);
satellite.Propagator.InitialState.Representation.AssignCartesian('eCoordinateSystemFixed', 6406.92, -1787.59, -506.422, 2.10185, 6.48871, 3.64041);

forceModel = satellite.Propagator.ForceModel;
forceModel.CentralBodyGravity.File = 'C:\Program Files\AGI\STK_ODTK 13\STKData\CentralBodies\Earth\WGS84_EGM96.grv';
forceModel.CentralBodyGravity.MaxDegree = 21;
forceModel.CentralBodyGravity.MaxOrder = 21;
forceModel.Drag.Use=1;
forceModel.Drag.DragModel.Cd=0.01;
forceModel.Drag.DragModel.AreaMassRatio=0.01;
forceModel.SolarRadiationPressure.Use=0;

integrator = satellite.Propagator.Integrator;
integrator.DoNotPropagateBelowAlt=-1e6;
integrator.IntegrationModel=3;
integrator.StepSizeControl.Method=1;
integrator.StepSizeControl.ErrorTolerance=1e-13;
integrator.StepSizeControl.MinStepSize=0.1;
integrator.StepSizeControl.MaxStepSize=30;
integrator.Interpolation.Method=1;
integrator.Interpolation.Order=7;

satellite.Propagator.Propagate();

Set satellite propagator to J4 and assign cartesian position

[MATLAB]

% IAgSatellite satellite: Satellite object
satellite.SetPropagatorType('ePropagatorJ4Perturbation');
propagator = satellite.Propagator;
propagator.InitialState.Representation.AssignCartesian('eCoordinateSystemICRF', 6678.14, 0, 0, 0, 6.78953, 3.68641)
propagator.Propagate();

Set satellite propagator to SGP4 and propagate

[MATLAB]

% IAgSatellite satellite: Satellite object
satellite.SetPropagatorType('ePropagatorSGP4');
propagator = satellite.Propagator;
propagator.EphemerisInterval.SetImplicitInterval( ...
    root.CurrentScenario.Vgt.EventIntervals.Item("AnalysisInterval")) % Link to scenario period
propagator.CommonTasks.AddSegsFromOnlineSource('25544'); % International Space Station
propagator.AutoUpdateEnabled = true;
propagator.Propagate();

Set satellite propagator to SPICE and propagate

[MATLAB]

% IAgSatellite satellite: Satellite object
% IAgStkObjectRoot root: STK Object Model Root
satellite.SetPropagatorType('ePropagatorSPICE');
propagator = satellite.Propagator;
propagator.Spice = 'C:\Program Files\AGI\STK_ODTK 13\STKData\Spice\planets.bsp';   % Make sure this is a valid path
propagator.BodyName = 'MARS';

propagator.EphemerisInterval.SetImplicitInterval( ...
    root.CurrentScenario.Vgt.EventIntervals.Item("AnalysisInterval")) % Link to scenario period
propagator.Step = 60.0;
propagator.Propagate();

Set up target slewing

[MATLAB]

% IAgSatellite satellite: Satellite object
satellite.Attitude.Pointing.UseTargetPointing = true;
satellite.Attitude.Pointing.Targets.Add('Facility/FacSlew');

attitudeSlewing = satellite.Attitude.Pointing.TargetSlew;
attitudeSlewing.SetSlewModeType('eVeSlewModeConstrained2ndOrderSpline');

constrainedSlew = attitudeSlewing.SlewMode;
constrainedSlew.MaximumSlewTime = 20; % sec
constrainedSlew.SlewTimingBetweenTargets = 'eVeSlewTimingBetweenTargetsOptimal';

maxRate = constrainedSlew.MaximumSlewRate;
maxRate.Magnitude = 10; % deg/sec
maxRate.PerAxisXEnabled = 1;
maxRate.PerAxisX = 5; % deg/sec
maxRate.PerAxisYEnabled = 1;
maxRate.PerAxisY = 5; % deg/sec
maxRate.PerAxisZEnabled = 1;
maxRate.PerAxisZ = 5; % deg/sec

maxAcceleration = constrainedSlew.MaximumSlewAcceleration;
maxAcceleration.Magnitude = 10; % deg/sec^2
maxAcceleration.PerAxisXAccelEnabled = 1;
maxAcceleration.PerAxisXAccel = 5; % deg/sec^2
maxAcceleration.PerAxisYAccelEnabled = 1;
maxAcceleration.PerAxisYAccel = 5; % deg/sec^2
maxAcceleration.PerAxisZAccelEnabled = 1;
maxAcceleration.PerAxisZAccel = 5; % deg/sec^2

Create a new component through the Component Browser

[MATLAB]

% IAgVADriverMCS driver: MCS driver interface
% IAgScenario scenario: Scenario object
% Get the Prop Funct Folder
compBrowser = scenario.ComponentDirectory.GetComponents('eComponentAstrogator').GetFolder('Propagator Functions');
% Get the Atmospheric Models Folder
atmos = compBrowser.GetFolder('Atmospheric Models');
% Grab the Mars Exponential Model
mars = atmos.Item('Exponential - Mars');
% Make a copy of the Model to Edit it
marsClone = mars.CloneObject;

% Grab a handle of the new Mars Model and edit properties
newMars = atmos.Item('Exponential - Mars1');
newMars.Name = 'New Mars';
newMars.ReferenceAltitude = 0; % km
newMars.ReferenceDensity = 20000000; % kg/km^3
newMars.ScaleAltitude = 11.1; % km

Insert a Propagate State Segment into the MCS and Add/Remove Stopping Conditions

[MATLAB]

% IAgVADriverMCS driver: MCS driver interface
transferEllipse = driver.MainSequence.Insert('eVASegmentTypePropagate', 'Transfer Ellipse', '-');

transferEllipse.Properties.Color = 255; % Red
transferEllipse.PropagatorName = 'Earth Point Mass';
transferEllipse.StoppingConditions.Add('Apoapsis');
transferEllipse.StoppingConditions.Remove('Duration');

Insert a Propagate State Segment into the MCS and configure

[MATLAB]

% IAgVADriverMCS driver: MCS driver interface
propagate = driver.MainSequence.Insert('eVASegmentTypePropagate', 'Propagate', '-');
propagate.PropagatorName = 'Earth Point Mass';
propagate.Properties.Color = 16711680;  % Blue
propagate.StoppingConditions.Item('Duration').Properties.Trip = 7200;

Insert a Target Sequence Segment into the MCS and configure

[MATLAB]

% IAgVADriverMCS driver: MCS driver interface
ts = driver.MainSequence.Insert('eVASegmentTypeTargetSequence', 'Start Transfer', '-');
dv1 = ts.Segments.Insert('eVASegmentTypeManeuver', 'DV1', '-');
% Insert maneuver into target sequence and target thrust vector
dv1.SetManeuverType('eVAManeuverTypeImpulsive');
impulsive = dv1.Maneuver;
impulsive.SetAttitudeControlType('eVAAttitudeControlThrustVector');
thrustVector = impulsive.AttitudeControl;
thrustVector.ThrustAxesName = 'Satellite/MySatellite VNC(Earth)';
dv1.EnableControlParameter('eVAControlManeuverImpulsiveCartesianX');
dv1.Results.Add('Keplerian Elems/Radius of Apoapsis');
% Handle to differential corrector profile
dc = ts.Profiles.Item('Differential Corrector');
% Set up control parameter
xControlParam = dc.ControlParameters.GetControlByPaths('DV1', 'ImpulsiveMnvr.Cartesian.X');
xControlParam.Enable = true;
xControlParam.MaxStep = 0.3;
% Set up result for control parameter
roaResult = dc.Results.GetResultByPaths('DV1', 'Radius Of Apoapsis');
roaResult.Enable = true;
roaResult.DesiredValue = 42238;
roaResult.Tolerance = 0.1;

dc.MaxIterations = 50;
ts.Action = 'eVATargetSeqActionRunActiveProfiles';

Insert an Initial State Segment into the MCS and configure

[MATLAB]

% IAgScenario scenario: Scenario object
% IAgVADriverMCS driver: MCS driver interface
initState = driver.MainSequence.Insert('eVASegmentTypeInitialState', 'Inner Orbit', '-');
initState.InitialState.Epoch = scenario.StartTime;
initState.SetElementType('eVAElementTypeKeplerian');
kep = initState.Element;
kep.PeriapsisRadiusSize = 6700;
kep.ArgOfPeriapsis = 0;
kep.Eccentricity = 0;
kep.Inclination = 0;
kep.RAAN = 0;
kep.TrueAnomaly = 0;

Run the Astrogator MCS

[MATLAB]

% IAgVADriverMCS driver: MCS driver interface
driver.RunMCS;

Add a Data Display to the 3D Window

[MATLAB]

% IAgSatellite satellite: Satellite object
% Remove all data displays so you can easily pick one that may already be in
% the list
satellite.VO.DataDisplay.RemoveAll;
% Add LLA data display and change size/title
datadisplay = satellite.VO.DataDisplay.Add('LLA Position');
datadisplay.IsVisible = true;
datadisplay.FontSize = 'eMedium';
datadisplay.TitleText = 'My Data Display';
datadisplay.IsShowNameEnabled = false;

Add a Vector to display in 3D

[MATLAB]

% IAgSatellite satellite: Satellite object
vector = satellite.VO.Vector;
angVel = vector.RefCrdns.Add('eVectorElem', 'Satellite/MySatellite AngVelocity');
angVel.LabelVisible = true;

Add Fixed System Orbit System in 3D Display

[MATLAB]

% IAgSatellite satellite: Satellite object
orbitsystems = satellite.VO.OrbitSystems;
orbitsystems.FixedByWindow.IsVisible = true;
orbitsystems.FixedByWindow.Inherit = false;
orbitsystems.FixedByWindow.Color = 65535;   % yellow

Change the 3D Model and marker properties

[MATLAB]

% IAgSatellite satellite: Satellite object
model = satellite.VO.Model;
model.ModelData.Filename = 'STKData\VO\Models\Space\dsp.glb';
orbitmarker = model.OrbitMarker;
orbitmarker.SetMarkerImageFile('C:\Program Files\AGI\STK_ODTK 13\STKData\VO\Markers\Satellite.ppm');
orbitmarker.MarkerData.IsTransparent = true;
orbitmarker.PixelSize = 18;
orbitmarker.OrientationMode = 'eVOMarkerOrientationFollowDirection';

Change the Display Label of the vehicle

[MATLAB]

% IAgSatellite satellite: Satellite object
satellite.Graphics.UseInstNameLabel = false;
satellite.Graphics.LabelName = 'Matlab Satellite';

Change the graphics resolution of the orbit for a smooth path

[MATLAB]

% IAgSatellite satellite: Satellite object
resolution = satellite.Graphics.Resolution;
resolution.Orbit = 60;

Display droplines in 3D Window

[MATLAB]

% IAgSatellite satellite: Satellite object
orbitDroplines = satellite.VO.DropLines.Orbit;
wgs84 = orbitDroplines.Item(0); %   Droplines to WGS84 surface
wgs84.IsVisible = true;
wgs84.LineWidth = 1;
wgs84.Use2DColor = false;
wgs84.Color = 255;  % red

Display Vector and set properties in 3D Display

[MATLAB]

% IAgSatellite satellite: Satellite object
vector = satellite.VO.Vector;
sunVector = vector.RefCrdns.Add('eVectorElem', 'Satellite/MySatellite Sun Vector');
vector.VectorSizeScale = 2;
sunVector.Visible = true;
sunVector.Color = 65535;    % yellow
sunVector.LabelVisible = true;
sunVector.MagnitudeVisible = true;

Modify the Detail Thresholds Levels

[MATLAB]

% IAgSatellite satellite: Satellite object
details = satellite.VO.Model.DetailThreshold;
details.EnableDetailThreshold = true;
details.All = 1;    %   km
details.ModelLabel = 2; %   km
details.MarkerLabel = 40000;    %   km
details.Marker = 500000;    %   km
details.Point = 500000; %   km

Set 2D Display times to Custom and add intervals

[MATLAB]

% IAgStkObjectRoot root: STK Object Model root
% IAgSatellite satellite: Satellite object
root.UnitPreferences.Item('DateFormat').SetCurrentUnit('EpSec');
graphics = satellite.Graphics;
graphics.SetAttributesType('eAttributesCustom');
graphics.Attributes.Default.IsVisible = false;

interval1 = graphics.Attributes.Intervals.Add(0, 3600);
interval1.GfxAttributes.IsVisible = true;
interval1.GfxAttributes.Inherit = false;
interval1.GfxAttributes.Line.Width = 1;
interval1.GfxAttributes.Line.Style = 'eLongDash';
interval1.GfxAttributes.Color = 16711935;
interval1.GfxAttributes.MarkerStyle = 'X';

interval2 = satellite.Graphics.Attributes.Intervals.Add(7200, 86400);
interval2.GfxAttributes.IsVisible = true;
interval2.GfxAttributes.Inherit = false;
interval2.GfxAttributes.Line.Width = 1;
interval2.GfxAttributes.Line.Style = 'eDashed';
interval2.GfxAttributes.Color = 65280;
interval2.GfxAttributes.MarkerStyle = 'Point';

Set 2D Graphics display properties

[MATLAB]

% IAgStkObjectRoot root: STK Object Model root
% IAgSatellite satellite: Satellite object
% Change the line width, style, color and marker

graphics = satellite.Graphics;
graphics.SetAttributesType('eAttributesBasic');
attributes = graphics.Attributes;
attributes.Inherit = false;
attributes.Line.Width = 3;
attributes.Line.Style = 'eLongDash';
attributes.Color = 65280;
attributes.MarkerStyle = 'C:\Program Files\AGI\STK_ODTK 13\STKData\Pixmaps\MarkersWin\m010Satellite.bmp';

Set 2D Swath

[MATLAB]

% IAgSatellite satellite: Satellite object
% Set swath in the 2D properties
swath = satellite.Graphics.Swath;
swath.SetElevationType('eElevationGroundElevation');
swath.Elevation.Angle = 30;  % deg
satellite.Graphics.Swath.Options = 'eOptionsEdgeLimits';

Set 2D/3D Elevation Contours

[MATLAB]

% IAgSatellite satellite: Satellite object
% Set the contours in the 2D properties
contours = satellite.Graphics.ElevContours;
contours.IsVisible = true;
contours.NumOfDecimalDigits = 0;
contours.Elevations.AddLevelRange(0, 90, 10); %   Min, Max, Step
% Turn the contours on in the 3D properties
satellite.VO.ElevContours.IsVisible = true;

Set 2D/3D Pass Display Properties

[MATLAB]

% IAgSatellite satellite: Satellite object
% Display one pass for ground track and orbit on 2D
passdata = satellite.Graphics.PassData;
groundTrack = passdata.GroundTrack;
groundTrack.SetLeadDataType('eDataOnePass');
groundTrack.SetTrailSameAsLead;
orbit = passdata.Orbit;
orbit.SetLeadDataType('eDataOnePass');
orbit.SetTrailSameAsLead;
% Display one orbit pass and no ground track on 3D
passdata3D = satellite.VO.Pass.TrackData.PassData;
groundTrack3D = passdata3D.GroundTrack;
groundTrack3D.SetLeadDataType('eDataNone');
groundTrack3D.SetTrailSameAsLead;
orbit3D = passdata3D.Orbit;
orbit3D.SetLeadDataType('eDataOnePass');
orbit3D.SetTrailSameAsLead;

Set 2D/3D Range Contours

[MATLAB]

% IAgSatellite satellite: Satellite object
% Set a contour level in the 2D properties
rangeContours = satellite.Graphics.RangeContours;
rangeContours.IsVisible = true;
rangeLevel = rangeContours.LevelAttributes.AddLevel(2000);  % km
rangeLevel.Color = 16711935;
rangeLevel.LineWidth = 4;
rangeLevel.LabelAngle = 90;
rangeLevel.UserTextVisible = true;
rangeLevel.UserText = 'Range';
% Turn the contours on in the 3D properties
satellite.VO.RangeContours.IsVisible = true;

Set Vehicle Lighting Properties

[MATLAB]

% IAgSatellite satellite: Satellite object
lighting = satellite.Graphics.Lighting;
% Settings for vehicle in sunlight
sunlight = lighting.Sunlight;
sunlight.Visible = true;
sunlight.Color = 65535; % yellow
sunlight.LineWidth = 3;
% Settings for vehicle in penumbra
penumbra = lighting.Penumbra;
penumbra.Visible = true;
penumbra.Color = 42495; % orange
penumbra.LineWidth = 2;
% Settings for vehicle in umbra
umbra = lighting.Umbra;
umbra.Visible = true;
umbra.Color = 255;  % red
umbra.LineWidth = 1;

Attach a Sensor Object to a Vehicle

[MATLAB]

% IAgSatellite satellite: Satellite object
sensor = satellite.Children.New('eSensor', 'MySensor');

Define sensor pointing fixed axes AzEl

[MATLAB]

% IAgSensor sensor: Sensor object
% Change pointing and set
sensor.CommonTasks.SetPointingFixedAxesAzEl('CentralBody/Sun J2000 Axes', 11, 22, 'eAzElAboutBoresightHold')

Define sensor pointing fixed axes Euler

[MATLAB]

% IAgSensor sensor: Sensor object
% Change pointing and set
sensor.CommonTasks.SetPointingFixedAxesEuler('CentralBody/Sun J2000 Axes', 'e132', 30, 40, 50)

Define sensor pointing fixed axes Quaternion

[MATLAB]

% IAgSensor sensor: Sensor object
% Change pointing and set
sensor.CommonTasks.SetPointingFixedAxesQuat('CentralBody/Sun J2000 Axes', 0.1, 0.2, 0.3, 0.4)

Define sensor pointing fixed axes YPR

[MATLAB]

% IAgSensor sensor: Sensor object
% Change pointing and set
sensor.CommonTasks.SetPointingFixedAxesYPR('CentralBody/Sun J2000 Axes', 'eRYP', 11, 22, 33)

Define sensor pointing fixed AzEl

[MATLAB]

% IAgSensor sensor: Sensor object
% Change pointing and set
sensor.CommonTasks.SetPointingFixedAzEl(4.5, -45.0, 'eAzElAboutBoresightRotate')

Define sensor pointing fixed Euler

[MATLAB]

% IAgSensor sensor: Sensor object
% Change pointing and set
sensor.CommonTasks.SetPointingFixedEuler('e132', 30, 40, 50)

Define sensor pointing fixed Quaternion

[MATLAB]

% IAgSensor sensor: Sensor object
% Change pointing and set
sensor.CommonTasks.SetPointingFixedQuat(0.1, 0.2, 0.3, 0.4)

Define sensor pointing fixed YPR

[MATLAB]

% IAgSensor sensor: Sensor object
% Change pointing and set
sensor.CommonTasks.SetPointingFixedYPR('eRPY', 12, 24, 36)

Sensor Body Mask

[MATLAB]

% IAgSensor sensor: Sensor object
sensor.SetAzElMaskFile('C:\Program Files\AGI\STK_ODTK 13\Data\Resources\stktraining\text\BodyMask_hga.bmsk');

Set a Targeted Sensor

[MATLAB]

% IAgSensor sensor: Sensor object
sensor.CommonTasks.SetPointingTargetedTracking('eTrackModeTranspond', 'eBoresightRotate', '*/AreaTarget/MyAreaTarget');

Set Sensor Properties

[MATLAB]

% IAgSensor sensor: Sensor object
% Change pattern and set
sensor.CommonTasks.SetPatternRectangular(20, 25);
% Change pointing and set
sensor.CommonTasks.SetPointingFixedAzEl(90, 60, 'eAzElAboutBoresightRotate');
% Change location and set
sensor.SetLocationType('eSnFixed');
sensor.LocationData.AssignCartesian(-.0004, -.0004, .004);

Sensor Persistence

[MATLAB]

% IAgSensor sensor: Sensor object
projection = sensor.Graphics.Projection;
projection.Persistence = 7200;  % sec
projection.ForwardPersistence = true;
projection.FillPersistence = true;
sensor.Graphics.FillVisible = true;
sensor.Graphics.PercentTranslucency = 50;

Add a new phase and use the same performance models as the first phase

[MATLAB]

% IAgAvtrPhases phases: Phase Collection object
% Add a new phase at the end of the mission
newPhase = phases.Add();
% Rename the phase
newPhase.Name = 'New Phase';
% Copy the performance models from the first phase and paste it to the new phase
phases.Item(0).CopyPerformanceModels();
newPhase.PastePerformanceModels();

Add a takeoff procedure from a runway

[MATLAB]

% IAgAvtrProcedureCollection procedures: Procedure Collection object
% Add a takeoff procedure with a runway as a site
takeoff = procedures.Add('eSiteRunway', 'eProcTakeoff');

% Get the runway heading options
headingOptions = takeoff.RunwayHeadingOptions;
% Opt to use the headwind runway
headingOptions.RunwayMode = 'eHeadwind';

% Set the takeoff mode and get that interface
takeoff.TakeoffMode = 'eTakeoffNormal';
takeoffNormal = takeoff.ModeAsNormal;

% Set the takeoff climb angle
takeoffNormal.TakeoffClimbAngle = 5;
% Set the departure altitude above the runway
takeoffNormal.DepartureAltitude = 600;
% Set the altitude offset for the runway
takeoffNormal.RunwayAltitudeOffset = 10;
% Use terrain for the runway's altitude
takeoffNormal.UseRunwayTerrain = 1;

Add and configure a basic maneuver procedure

[MATLAB]

% IAgAvtrProcedureCollection procedures: Procedure Collection object
% Add a basic maneuver procedure
basicManeuver = procedures.Add('eSiteEndOfPrevProcedure', 'eProcBasicManeuver');

% Set the navigation to use a Straight Ahead strategy
basicManeuver.NavigationStrategyType = 'Straight Ahead';
% Get the options for the straight ahead strategy
straightAhead = basicManeuver.Navigation;
% Opt to maintain course (as opposed to maintain heading)
straightAhead.ReferenceFrame = 'eMaintainCourse';

% Set the profile to use a Autopilot - Vertical Plane strategy
basicManeuver.ProfileStrategyType = 'Autopilot - Vertical Plane';
% Get the options for the profile strategy
autopilot = basicManeuver.Profile;
% Opt to maintain the initial altitude
autopilot.AltitudeMode = 'eAutopilotHoldInitAltitude';
airspeedOptions = autopilot.AirspeedOptions;
% Opt to maintain a specified airspeed
airspeedOptions.AirspeedMode = 'eMaintainSpecifiedAirspeed';
% Specify the airspeed
airspeedOptions.SpecifiedAirspeed = 250;

% Configure the options on the Attitude / Performance / Fuel page
basicManeuver.FlightMode = 'eFlightPhaseCruise';
% Override the fuel flow
basicManeuver.FuelFlowType = 'eBasicManeuverFuelFlowOverride';
basicManeuver.OverrideFuelFlowValue = 1000;

% Set the basic stopping conditions
basicManeuver.UseMaxDownrange = 1;
basicManeuver.MaxDownrange = 10;
basicManeuver.UseStopFuelState = 0;
basicManeuver.UseMaxTimeOfFlight = 0;

Add and configure a landing procedure

[MATLAB]

% IAgAvtrProcedureCollection procedures: Procedure Collection object
% Add a landing procedure
landing = procedures.Add('eSiteRunway', 'eProcLanding');

% Get the runway heading options
headingOptions = landing.RunwayHeadingOptions;
% Land from the low end
headingOptions.RunwayMode = 'eLowEnd';

% Use a standard instrument approach
landing.ApproachMode = 'eStandardInstrumentApproach';
% Get the options for a standard instrument approach
sia = landing.ModeAsStandardInstrumentApproach;
% Change the approach altitude
sia.ApproachAltitude = 1000;
% Change the glideslope
sia.Glideslope = 4;
% Offset the runway altitude
sia.RunwayAltitudeOffset = 10;
% Use the terrain as an altitude reference for the runway
sia.UseRunwayTerrain = 1;

Add and configure an enroute procedure

[MATLAB]

% IAgAvtrProcedureCollection procedures: Procedure Collection object
% Add an enroute procedure with a site type of End of Previous Procedure
enroute = procedures.Add('eSiteEndOfPrevProcedure', 'eProcEnroute');
%Get the altitude options
altitudeOptions = enroute.AltitudeMSLOptions;
% To specify an altitude, turn off the option to use the default cruise altitude
altitudeOptions.UseDefaultCruiseAltitude = 0;
% Set the altitude
altitudeOptions.MSLAltitude = 10000;

%Get the navigation options
navigationOptions = enroute.NavigationOptions;
% Set the route to arrive on a specified course
navigationOptions.NavMode = 'eArriveOnCourse';
% Set the course
navigationOptions.ArriveOnCourse = 30;
% Use a magnetic heading
navigationOptions.UseMagneticHeading = 1;

%Get the navigation options
airspeedOptions = enroute.EnrouteCruiseAirspeedOptions;
% Fly at max speed
airspeedOptions.CruiseSpeedType = 'eMaxAirspeed';
% To specify an airspeed to fly at, set the speed type to other airspeed
airspeedOptions.CruiseSpeedType = 'eOtherAirspeed';
% Then set the airspeed and airspeed type
airspeedOptions.SetOtherAirspeed('eTAS', 200);

Add and remove procedures

[MATLAB]

% IAgAvtrProcedureCollection procedures: Procedure Collection object
% IAgAvtrPropagator propagator: Aviator Propagator object
% Add a takeoff procedure with a runway as a site. This will add the procedure
takeoff = procedures.Add('eSiteRunway', 'eProcTakeoff');
% Add a procedure at a given index (starting from 0)
enroute = procedures.AddAtIndex(1, 'eSiteEndOfPrevProcedure', 'eProcEnroute');

% Make sure to propagate the mission to calculate the route
propagator.Propagate();
% Get the mission
mission = propagator.AvtrMission;
% Check to see if the mission is valid (must first be propagated)
isValid = mission.IsValid;

% Get the number of procedures
procedureCount = procedures.Count;
% Remove the procedure at the given index
procedures.RemoveAtIndex(1);
% Remove the given procedure
procedures.Remove(takeoff);

% Propagate the mission
propagator.Propagate();

Configure a procedure time options

[MATLAB]

% IAgAvtrProcedure procedure: Procedure object
% Get the time in epoch seconds
root.UnitPreferences.SetCurrentUnit('DateFormat', 'EpSec');
% Get the time options
timeOptions = procedure.TimeOptions;
% Get the start time
startTime = timeOptions.StartTime;
% Set the procedure to interrupt after 15 seconds
timeOptions.SetInterruptTime(15);

Configure a runway site

[MATLAB]

% IAgAvtrSiteRunway runway: Runway object
% Set the latitude, longitude, and altitude
runway.Latitude = 41;
runway.Longitude = 77;
runway.Altitude = 5;

% Set the altitude reference
runway.AltitudeRef = 'eAltMSL';

% Set the heading
runway.HighEndHeading = 195;
% Opt to use true heading
runway.IsMagnetic = false;

% Set the length of the runway
runway.Length = 5;

% Rename the runway
runway.Name = 'New User Runway';
% Add the runway to the catalog to use it for next time
runway.AddToCatalog(1);

Configure a runway site from a runway in the Aviator catalog

[MATLAB]

% IAgAvtrSiteRunway runway: Runway object
% IAgAvtrCatalog catalog: Aviator catalog object
% Get the source of user runways
userRunways = catalog.RunwayCategory.UserRunways;
% Check that the runway exists in the catalog
if (userRunways.Contains('New User Runway'))
    % If so, get the user runway with the given name
    runwayFromCatalog = userRunways.GetUserRunway('New User Runway');
    % Copy the parameters of that runway
    runway.CopyFromCatalog(runwayFromCatalog);
end

Configure the Advanced Fixed Wing Tool and set the aircraft to use the resulting performance models

[MATLAB]

% IAgAvtrAircraft aviatorAircraft: Aviator Aircraft object
% Get the advanced fixed wing tool
advFixedWingTool = aviatorAircraft.AdvFixedWingTool;
% Set the basic geometry
advFixedWingTool.WingArea = 300;
advFixedWingTool.FlapsArea = 50;
advFixedWingTool.SpeedbrakesArea = 10;
% Set the structural and human factor limits
advFixedWingTool.MaxAltitude = 65000;
advFixedWingTool.MaxMach = 0.98;
advFixedWingTool.MaxEAS = 460;
advFixedWingTool.MinLoadFactor = -2.5;
advFixedWingTool.MaxLoadFactor = 4.5;

% Opt to enforce the max temperature limit
advFixedWingTool.UseMaxTemperatureLimit = 1;
advFixedWingTool.MaxTemperature = 900;

% Use a subsonic aerodynamic strategy
advFixedWingTool.AeroStrategy = 'eSubsonicAero';
% Cache the aerodynamic data to improve calculation speed
advFixedWingTool.CacheAeroData = 1;
% Use a high bypass turbofan
advFixedWingTool.PowerplantStrategy = 'eTurbofanHighBypass';
% Cache the fuel flow data to improve calculation speed
advFixedWingTool.CacheFuelFlow = 1;

% Create the corresponding performance models that reference the advanced fixed wing tool
% Specify the name, whether to override any existing models with the same name, and whether to set the new models as the default performance models
advFixedWingTool.CreateAllPerfModels("AdvancedModels", 1, 1);

% Save the changes in the catalog
aviatorAircraft.Save();

Configure the Aviator propagator

[MATLAB]

% IAgAircraft aircraft: Aircraft object
% Set to Propagator to Aviator
aircraft.SetRouteType('ePropagatorAviator');
% Get the aircraft's route
aircraftRoute = aircraft.Route;
% Get the Aviator propagator
propagator = aircraftRoute.AvtrPropagator;
% Get the Aviator mission
mission = propagator.AvtrMission;
% Get the list of phases from the mission
phases = mission.Phases;
% Get the list of procedures from the first phase
procedures = phases.Item(0).Procedures;
% Propagate the route
propagator.Propagate();

Configure the basic acceleration performance model of an aircraft

[MATLAB]

% IAgAvtrAircraft aviatorAircraft: Aviator Aircraft object
% Get the acceleration type
acceleration = aviatorAircraft.Acceleration;
% Get the build in performance model
basicAccModel = acceleration.GetBuiltInModel();

% Get the level turns options
levelTurns = basicAccModel.LevelTurns;
% Set a max bank angle of 25
levelTurns.SetLevelTurn('eTurnModeBankAngle', 25);
% Get the climb and descent transition options
climbAndDescent = basicAccModel.ClimbAndDescentTransitions;
% Set the max pull up G to 1
climbAndDescent.MaxPullUpG = 1.2;
% Get the attitude transition options
attitudeTransitions = basicAccModel.AttitudeTransitions;
% Set the max roll rate to 25
attitudeTransitions.RollRate = 25;

% Get the aerodynamics
aero = basicAccModel.Aerodynamics;
% Use simple aerodynamics
aero.AeroStrategy = 'eAircraftAeroSimple';
% Get the options for the simple aerodynamics and set some parameters
simpleAero = aero.ModeAsSimple;
simpleAero.SRef = 5;
simpleAero.ClMax = 3.1;
simpleAero.Cd = 0.05;

% Get the propulsion
prop = basicAccModel.Propulsion;
% Use simple propulsion
prop.PropStrategy = 'eAircraftPropSimple';
% Get the simple propulsion options and set some parameters
simpleProp = prop.ModeAsSimple;
simpleProp.MaxThrustAccel = 0.6;
simpleProp.MinThrustDecel = 0.4;
simpleProp.SetDensityScaling(true, 0.02);

% Save the changes to the catalog
aviatorAircraft.Save();

Configure the basic cruise performance model of an aircraft

[MATLAB]

% IAgAvtrAircraft aviatorAircraft: Aviator Aircraft object
% Get the cruise type
cruise = aviatorAircraft.Cruise;
% Get the build in performance model
basicCruiseModel = cruise.GetBuiltInModel();

% Set the ceiling altitude
basicCruiseModel.CeilingAltitude = 50000;
% Set the default cruise altitude
basicCruiseModel.DefaultCruiseAltitude = 10000;
% Set the airspeed type
basicCruiseModel.AirspeedType = 'eTAS';
% Opt to not use the fuel flow calculated by the aero/prop model and instead specify the values
basicCruiseModel.UseAeroPropFuel = 0;

% Set the various airspeeds and fuel flows
basicCruiseModel.MinAirspeed = 110;
basicCruiseModel.MinAirspeedFuelFlow = 10000;

basicCruiseModel.MaxEnduranceAirspeed = 135;
basicCruiseModel.MaxEnduranceFuelFlow = 8000;

basicCruiseModel.MaxAirspeed = 570;
basicCruiseModel.MaxAirspeedFuelFlow = 30000;

basicCruiseModel.MaxRangeAirspeed = 140;
basicCruiseModel.MaxRangeFuelFlow = 9000;

basicCruiseModel.MaxPerfAirspeed = 150;
basicCruiseModel.MaxPerfAirspeedFuelFlow = 12000;

% Save the changes to the catalog
aviatorAircraft.Save();

Configure the performance models to be used in the phase

[MATLAB]

% IAgAvtrPhase phase: Phase object
% Get the acceleration performance model used for the current phase
acceleration = phase.GetPerformanceModelByType('Acceleration');
% Check if it is linked to the catalog
isLinkedToCatalog = acceleration.IsLinkedToCatalog;
% Use the performance model in the catalog named "Built-In Model"
acceleration.LinkToCatalog('Built-In Model');

% Get the VTOL performance model
vtol = phase.GetPerformanceModelByType('VTOL');
% Create a new vtol model of type AGI VTOL Model. Note that this new model does not exist in the catalog and only exists in the phase.
vtol.CreateNew('AGI VTOL Model');
% Rename the performance model
vtol.Rename('Temporary VTOL Model');

Configure the weather and atmosphere of the Mission

[MATLAB]

% IAgAvtrMission mission: Aviator Mission object
% Get the wind model used for the mission
windModel = mission.WindModel;
% Let's use the mission model
windModel.WindModelSource = 'eMissionModel';
% Let's use constant wind
windModel.WindModelType = 'eConstantWind';
% Get the constant wind model options
constantWind = windModel.ModeAsConstant;
% Set the wind bearing
constantWind.WindBearing = 30;
% Set the wind speed
constantWind.WindSpeed = 5;

% Get the atmosphere model used for the mission
atmosphere = mission.AtmosphereModel;
% Let's use the mission model
atmosphere.AtmosphereModelSource = 'eMissionModel';
% Get the basic atmosphere options
basicAtmosphere = atmosphere.ModeAsBasic;
% Use standard 1976 atmosphere
basicAtmosphere.BasicModelType = 'eStandard1976';
% Opt to override the values
basicAtmosphere.UseNonStandardAtmosphere = 1;
% Override the temperature
basicAtmosphere.Temperature = 290;

Configure the wind and atmosphere for a procedure

[MATLAB]

% IAgAvtrProcedure procedure: Procedure object
% Get the wind model for the procedure
windModel = procedure.WindModel;
% Use the procedure model
windModel.WindModelSource = 'eProcedureModel';
% Let's use constant wind
windModel.WindModelType = 'eConstantWind';
% Get the constant wind model options
constantWind = windModel.ModeAsConstant;
% Set the wind bearing
constantWind.WindBearing = 30;
% Set the wind speed
constantWind.WindSpeed = 5;

% Get the atmosphere model used for the procedure
atmosphere = procedure.AtmosphereModel;
% Let's use the procedure model
atmosphere.AtmosphereModelSource = 'eProcedureModel';
% Get the basic atmosphere options
basicAtmosphere = atmosphere.ModeAsBasic;
% Use standard 1976 atmosphere
basicAtmosphere.BasicModelType = 'eStandard1976';

Create a new performance model for an aircraft

[MATLAB]

% IAgAvtrAircraft aviatorAircraft: Aviator Aircraft object
% Get the acceleration type
acceleration = aviatorAircraft.Acceleration;
% Get the names of the current acceleration models
modelNames = acceleration.ChildNames;
% Check how many models there are
modelCount = length(modelNames);
% Get the child types (for example AGI Basic Acceleration Model, Advanced Acceleration Model)
modelTypes = acceleration.ChildTypes;
% Create a new performance model of type "Advanced Acceleration Model"
newPerformanceModel = acceleration.AddChildOfType('Advanced Acceleration Model', 'Model Name');
% Save the changes to the catalog
aviatorAircraft.Save();

Rename a procedure and its site

[MATLAB]

% IAgAvtrProcedure procedure: Procedure object
% Rename the procedure
procedure.Name = 'New Procedure';
% Get the site corresponding to the procedure
site = procedure.Site;
% Rename the site
site.Name = 'New Site';

Set the aircraft used for the mission to an aircraft found in the Aviator catalog

[MATLAB]

% IAgAvtrPropagator propagator: Aviator Propagator object
% Get the Aviator catalog
catalog = propagator.AvtrCatalog;
% Get the aircraft category
category = catalog.AircraftCategory;
% Get the user aircraft models
aircraftModels = category.AircraftModels;
% Get the basic fighter
fighter = aircraftModels.GetAircraft("Basic Fighter");
% Get the mission
mission = propagator.AvtrMission;
% Set the vehicle used for the mission
mission.Vehicle = fighter;

Set the Configuration used for the Mission

[MATLAB]

% IAgAvtrMission mission: Aviator Mission object
% Get the configuration used for the mission
configuration = mission.Configuration;
% Set the max landing weight
configuration.MaxLandingWeight = 300000;
% Set the empty weight
configuration.EmptyWeight = 210000;
% Update the center of gravity of the aircraft when empty
configuration.SetEmptyCG(2, 0, 1);

% Get the stations
stations = configuration.GetStations();
% Check if there is an internal fuel station
hasInternalFuel = stations.ContainsStation("Internal Fuel");

if (hasInternalFuel > 0)
    % Get the fuel tank
    fuelTank = stations.GetInternalFuelTankByName("Internal Fuel");
    % Set the capacity of the fuel tank
    fuelTank.Capacity = 175000;
    % Set the initial state of the fuel tank
    fuelTank.InitialFuelState = 125000;
end

% Add a new payload station
newPayload = stations.AddPayloadStation();
% Set the position of the payload station
newPayload.SetPosition(0, 2, 0);
% Add an external fuel tank
externalTank = newPayload.AddExternalFuelTank();
% Set the empty weight of the tank
externalTank.EmptyWeight = 2000;

Execute Connect command

[MATLAB]

root.ExecuteCommand('New / */Target MyTarget');

Execute multiple Connect commands

[MATLAB]

commandList = {'New / */Place MyPlace';'SetPosition */Place/MyPlace Geodetic 37.9 -75.5 0.0'};
root.ExecuteMultipleCommands(commandList, 'eExceptionOnError');

Extract data from Connect result

[MATLAB]

result = root.ExecuteCommand('Report_RM */Place/MyPlace Style "Cartesian Position"');

for i = 0:result.Count-1
    cmdRes = result.Item(i);
    fprintf(' %s \n', cmdRes);
end

Camera view object with offset

[MATLAB]

% IAgSatellite satellite: Satellite object
% IAgScenario scenario: Scenario object
axes = satellite.Vgt.Axes.Item('TopoCentric');
point = satellite.Vgt.Points.Item('Center');
offset = {0.0975; 0.0279; 0.0273};
upDirection = {-0.0906; -0.6908; 0.7173};

manager = scenario.SceneManager;
camera = manager.scenes.Item(0).Camera;
camera.ViewOffsetWithUpAxis(axes , point, offset, upDirection);
camera.ConstrainedUpAxis = 'eStkGraphicsConstrainedUpAxisZ';
camera.FieldOfView = deg2rad(45);
camera.LockViewDirection = false;
manager.Render();

Change camera reference frame

[MATLAB]

% IAgScenario scenario: Scenario object
% IAgStkObjectRoot root: STK Object Model Root
manager = scenario.SceneManager;
manager.scenes.Item(0).Camera.ViewCentralBody('Earth', root.CentralBodies.Earth.Vgt.Axes.Item('Fixed'));
manager.Render();

Change camera view to Imagery Extents

[MATLAB]

% IAgScenario scenario: Scenario object
% IAgStkGraphicsAGIProcessedImageGlobeOverlay imageryTile: Image Overlay object
manager = scenario.SceneManager;
extent = imageryTile.Extent;
% Change extent in the default 3D window
manager.scenes.Item(0).Camera.ViewExtent('Earth', extent);
manager.Render();

Add Imagery and Terrain to the Scene

[MATLAB]

% IAgScenario scenario: Scenario object
% Retrieve the boundaries of the imported files
manager = scenario.SceneManager;
% Add Terrain
terrainTile = manager.Scenes.Item(0).CentralBodies.Earth.Terrain.AddUriString('C:\Program Files\AGI\STK_ODTK 13\Data\Resources\stktraining\samples\SRTM_Skopje.pdtt');
extentTerrain = terrainTile.Extent;
disp(['Terrain boundaries: LatMin: ' num2str(extentTerrain{1}) ' LatMax: ' num2str(extentTerrain{3}) ' LonMin: ' num2str(extentTerrain{2}) ' LonMax: ' num2str(extentTerrain{4})]);
% Add Imagery
imageryTile = manager.Scenes.Item(0).CentralBodies.Earth.Imagery.AddUriString('C:\Program Files\AGI\STK_ODTK 13\Data\Resources\stktraining\imagery\NPS_OrganPipeCactus_Map.pdttx');
extentImagery = imageryTile.Extent;
disp(['Imagery boundaries: LatMin: ' num2str(extentImagery{1}) ' LatMax: ' num2str(extentImagery{3}) ' LonMin: ' num2str(extentImagery{2}) ' LonMax: ' num2str(extentImagery{4})]);

Control Display of Stars and Water Texture

[MATLAB]

% IAgScenario scenario: Scenario object
% Turn off the stars and water texture
manager = scenario.SceneManager;
manager.Scenes.Item(0).ShowStars = false;
manager.Scenes.Item(0).ShowWaterSurface = false;

Control the Lighting of the 3D scene

[MATLAB]

% IAgScenario scenario: Scenario object
% Modify the lighting levels
manager = scenario.SceneManager;
lighting = manager.Scenes.Item(0).Lighting;
lighting.AmbientIntensity = .20;    % Percent
lighting.DiffuseIntensity = 4;  % Percent
lighting.NightLightsIntensity = 5;  % Percent

Create a Bounding Sphere

[MATLAB]

% IAgScenario scenario: Scenario object
manager = scenario.SceneManager;
sphere = manager.Initializers.BoundingSphere.Initialize({-1061.22;-5773.98;4456.04}, 100);

Display a Primitive During an Interval

[MATLAB]

% IAgScenario scenario: Scenario object
% IAgStkGraphicsModelPrimitive model: Graphics Primitive
manager = scenario.SceneManager;
composite = manager.Initializers.CompositeDisplayCondition.Initialize;
root.UnitPreferences.Item('DateFormat').SetCurrentUnit('EpSec')
start = root.ConversionUtility.NewDate('EpSec', num2str(scenario.StartTime));
stop = root.ConversionUtility.NewDate('EpSec', num2str(scenario.StartTime + 600));
timeInterval = manager.Initializers.TimeIntervalDisplayCondition.InitializeWithTimes(start, stop);
composite.Add(timeInterval);
model.DisplayCondition = composite;

Draw a new Model Primitive

[MATLAB]

% IAgScenario scenario: Scenario object
% Create a model primitive and sets properties
manager = scenario.SceneManager;
model = manager.Initializers.ModelPrimitive.InitializeWithStringUri('C:\Program Files\AGI\STK_ODTK 13\STKData\VO\Models\Air\f-22a_raptor.glb');
model.SetPositionCartographic('Earth', {0; -3; 15});    % Lat, Lon, Alt
model.Scale = 10000;
model.Translucency = 0;
manager.Primitives.Add(model);
manager.Render();

Draw a new Model Primitive in a Reference Frame

[MATLAB]

% IAgScenario scenario: Scenario object
% IAgSatellite satellite: Satellite object
% Create a model primitive and sets properties
manager = scenario.SceneManager;
modelRefFrame = manager.Initializers.ModelPrimitive.InitializeWithStringUri('C:\Program Files\AGI\STK_ODTK 13\STKData\VO\Models\Space\cubesat_1u.glb');
modelRefFrame.Position = {0;.005;0};
modelRefFrame.ReferenceFrame = satellite.Vgt.Systems.Item('Body');
modelRefFrame.Scale = 1;
manager.Primitives.Add(modelRefFrame);
manager.Render();

Draw a new Polyline Primitive

[MATLAB]

% IAgScenario scenario: Scenario object
% 3(n) x 1 cell result: cell of LLA values
% Create a polyline primitive and sets properties
manager = scenario.SceneManager;
polyline = manager.Initializers.PolylinePrimitive.InitializeWithType('eStkGraphicsPolylineTypeLineStrip');
polyline.SetCartographic('Earth', {43.6364; -106.364; 1.0;
                                   43.6364; -85.2273; 2.0,
                                   34.7727; -81.1363; 1.0});
polyline.Color = 255; % Red
polyline.Width = 3;
polyline.Translucency = 0;
polyline.Display = true;
polyline.DisplayOutline = false;
manager.Primitives.Add(polyline);
manager.Render();

%%
path = manager.Initializers.PathPrimitive.Initialize();
path.Width = 2;

interpolator = manager.Initializers.GreatArcInterpolator.InitializeWithCentralBody('Earth');
interpolator.Granularity = 1;
interpolator.PolylineType(1);

result = interpolator.Interpolate({2.383;13.049;10;0.054;35.919;10});
% path.AddRangeToFront(reshape(result, length(result)/3, 3));

counter = 1;
for i=counter:3:length(result)
    cartesian = root.ConversionUtility.ConvertPositionArray('eGeodetic', {result{i}, result{i+1}, result{i+2}}, 'eCartesian');
    pt = manager.Initializers.PathPoint.Initialize;
    pt.Position = cartesian';
    pt.Translucency = .25;

    counter = counter + 1;
    if (rem(counter, 2) == 0)
        pt.Color = 255;
    else
        pt.Color = 65280;
    end
    path.AddBack(pt);
end

manager.Primitives.Add(path);
manager.Render();

Draw a new Surface Extent Triangulator

[MATLAB]

% IAgScenario scenario: Scenario object
manager = scenario.SceneManager;
texture = manager.Textures.LoadFromStringUri('c:\Program Files\AGI\STK_ODTK 13\STKData\VO\Textures\AGI_logo.png');
mesh = manager.Initializers.SurfaceMeshPrimitive.Initialize();
mesh.Texture = texture;
mesh.Translucency = 0;
cartographicExtent = {-55;10;-24;30};

triangles = manager.Initializers.SurfaceExtentTriangulator.ComputeSimple('Earth', cartographicExtent);
mesh.Set(triangles);
mesh.Translucency = .25;
c0 = {10;-55};
c1 = {30;-55};
c2 = {30;-24};
c3 = {10;-24};

mesh.TextureMatrix = manager.Initializers.TextureMatrix.InitializeWithRectangles(c0, c1, c2, c3);
mesh.TransparentTextureBorder = true;
manager.Primitives.Add(mesh);
manager.Render();

Draw a new Surface Mesh

[MATLAB]

% IAgScenario scenario: Scenario object
manager = scenario.SceneManager;
cartesianPts = {6030.721052;1956.627139;-692.397578;
    5568.375825;2993.600713;-841.076362;
    5680.743568;2490.379622;-1480.882721};  % X, Y, Z (km)

triangles = manager.Initializers.SurfacePolygonTriangulator.Compute('Earth', cartesianPts);
surfaceMesh = manager.Initializers.SurfaceMeshPrimitive.Initialize();
surfaceMesh.Color = 255;    % red
surfaceMesh.Set(triangles);
manager.Primitives.Add(surfaceMesh);
manager.Render();

Draw a new Text Primitive

[MATLAB]

% IAgScenario scenario: Scenario object
manager = scenario.SceneManager;
font = manager.Initializers.GraphicsFont.InitializeWithNameSizeFontStyleOutline('MS Sans Serif', 24, 'eStkGraphicsFontStyleBold', true);
textBatch = manager.Initializers.TextBatchPrimitive.InitializeWithGraphicsFont(font);
textBatch.SetCartographic('Earth', {0;0;0}, {'Example Text'});   % Lat, Lon, Alt
manager.Primitives.Add(textBatch);

Draw a new Texture Screen Overlay

[MATLAB]

% IAgScenario scenario: Scenario object
manager = scenario.SceneManager;
overlays = manager.ScreenOverlays.Overlays;
textureOverlay = manager.Initializers.TextureScreenOverlay.InitializeWithXYWidthHeight(0, 0, 128, 128);
textureOverlay.Texture = manager.Textures.LoadFromStringUri('C:\Program Files\AGI\STK_ODTK 13\STKData\VO\Textures\agilogo3.ppm');
textureOverlay.MaintainAspectRatio = true;
textureOverlay.Origin = 'eStkGraphicsScreenOverlayOriginTopLeft';
textureOverlay.Position = {0;20;'eStkGraphicsScreenOverlayUnitPixels';'eStkGraphicsScreenOverlayUnitPixels'};
overlays.Add(textureOverlay);
% Render the Scene
manager.Render();

Draw a new Video Stream primitive

[MATLAB]

% IAgScenario scenario: Scenario object
manager = scenario.SceneManager;
% Extract "C:\Program Files\AGI\STK_ODTK 13\CodeSamples\CodeSamples.zip" to "C:\Temp\CodeSamples"
video = manager.Initializers.VideoStream.InitializeWithStringUri('c:\Temp\CodeSamples\CustomApplications\Data\HowTo\Videos\ShenzhouVII_BX1.wmv');
% Playback options are 'eStkGraphicsVideoPlaybackTimeInterval'
% 'eStkGraphicsVideoPlaybackRealTime'
video.Playback = 'eStkGraphicsVideoPlaybackRealTime';
video.Loop = true;
overlay = manager.Initializers.TextureScreenOverlay.InitializeWithXYWidthHeight(0, 0, video.Width / 3, video.Height / 3);
overlay.MaintainAspectRatio = true;
overlay.Translucency = 0;
overlay.BorderSize = 1;
overlay.BorderTranslucency = .25;
overlay.Origin = 'eStkGraphicsScreenOverlayOriginTopRight';
overlay.Texture = scenario.SceneManager.Textures.FromRaster(video);
manager.ScreenOverlays.Overlays.Add(overlay);
% Render the Scene
manager.Render();

Draw a Point Primitive and set properties

[MATLAB]

% IAgScenario scenario: Scenario object
manager = scenario.SceneManager;
point = manager.Initializers.PointBatchPrimitive.Initialize();
ptPosition = {0;-1;0};  % Lat, Lon, Alt

point.SetCartographic('Earth', ptPosition)
point.PixelSize = 15;
point.Color = 65280;
point.DisplayOutline = true;
point.OutlineWidth = 5;
point.OutlineColor = 255;

manager.Primitives.Add(point);
% Render the Scene
manager.Render();

Draw a Solid Box Primitive and set properties

[MATLAB]

% IAgScenario scenario: Scenario object
manager = scenario.SceneManager;
originBox = root.ConversionUtility.NewPositionOnEarth();
originBox.AssignGeodetic(0, 3, 100);

orientBox = root.ConversionUtility.NewOrientation();
orientBox.AssignAzEl(0, 0, 'eAzElAboutBoresightRotate');

size = {100; 100; 200};
result = manager.Initializers.BoxTriangulator.Compute(size);
solidBox = manager.Initializers.SolidPrimitive.Initialize();
solidBox.ReferenceFrame = root.CentralBodies.Earth.Vgt.Systems.Item('Fixed');
solidBox.Position = originBox.QueryCartesianArray;
solidBox.SetWithResult(result);
solidBox.Color = 255;
solidBox.OutlineColor = 16776974;
solidBox.Translucency = .75;
solidBox.Rotation = orientBox;
manager.Primitives.Add(solidBox);
manager.Render();

Draw a Solid Cylinder Primitive and set properties

[MATLAB]

% IAgScenario scenario: Scenario object
manager = scenario.SceneManager;
originCylinder = root.ConversionUtility.NewPositionOnEarth();
originCylinder.AssignGeodetic(0, 7, 100);

orientCylinder = root.ConversionUtility.NewOrientation();
orientCylinder.AssignAzEl(0, 0, 'eAzElAboutBoresightRotate');

cylinder = manager.Initializers.CylinderTriangulator.CreateSimple(200, 100);
solidCylinder = manager.Initializers.SolidPrimitive.Initialize();
solidCylinder.ReferenceFrame = root.CentralBodies.Earth.Vgt.Systems.Item('Fixed');
solidCylinder.Position = originCylinder.QueryCartesianArray;
solidCylinder.SetWithResult(cylinder);
solidCylinder.Color = 65280;
solidCylinder.OutlineColor = 16711680;
solidCylinder.OutlineWidth = 3;
solidCylinder.Translucency = .75;
solidCylinder.Rotation = orientCylinder;
manager.Primitives.Add(solidCylinder);
manager.Render();

Draw a Solid Ellipsoid Primitive and set properties

[MATLAB]

% IAgScenario scenario: Scenario object
manager = scenario.SceneManager;
originEllipsoid = root.ConversionUtility.NewPositionOnEarth();
originEllipsoid.AssignGeodetic(0, 5, 100);

orientEllipsoid = root.ConversionUtility.NewOrientation();
orientEllipsoid.AssignAzEl(0, 0, 'eAzElAboutBoresightRotate');

radii = {200; 100; 100};
ellipsoid = manager.Initializers.EllipsoidTriangulator.ComputeSimple(radii);
solidEllipsoid = manager.Initializers.SolidPrimitive.Initialize();
solidEllipsoid.ReferenceFrame = root.CentralBodies.Earth.Vgt.Systems.Item('Fixed'); % vgtSat.Systems.Item('Body');
solidEllipsoid.Position = originEllipsoid.QueryCartesianArray;
solidEllipsoid.SetWithResult(ellipsoid);
solidEllipsoid.Color = 16777215;
solidEllipsoid.OutlineColor = 15863551;
solidEllipsoid.Translucency = .75;
solidEllipsoid.Rotation = orientEllipsoid;
manager.Primitives.Add(solidEllipsoid);
manager.Render();

GreatArcInterpolator Primitives

[MATLAB]

% IAgScenario scenario: Scenario object
% Create a array of LLA values and interoplate them over the specified
% central body
positionArray = {35.017; -118.540; 0; 44.570; -96.474; 0; 31.101; -82.619; 0};
manager = scenario.SceneManager;
% Interpolate points over great arc
interpolator = manager.Initializers.GreatArcInterpolator.InitializeWithCentralBody('Earth');
interpolator.Granularity = .1;
result = interpolator.Interpolate(positionArray);

Create a Data Element Scalar

[MATLAB]

% IAgCrdnProvider vgtSat: Vector Geometry Tool Interface
calcFactory = vgtSat.CalcScalars.Factory;
trueAnom = calcFactory.Create('TrueAnomaly', '', 'eCrdnCalcScalarTypeDataElement');
trueAnom.SetWithGroup('Classical Elements', 'ICRF', 'True Anomaly');

Create a Function XY Scalar

[MATLAB]

% IAgCrdnProvider vgtSat: Vector Geometry Tool Interface
% IAgCrdnCalcScalar displScalar: calc scalar component
% IAgCrdnCalcScalar trueAnom: calc scalar component
calcFactory = vgtSat.CalcScalars.Factory;
functionScalar = calcFactory.CreateCalcScalarFunction2Var('FunctionXY', 'Difference between the 2 scalars');

functionScalar.X = displScalar;
functionScalar.Y = trueAnom;
functionScalar.A = 1;
functionScalar.B = 1;
functionScalar.C = 1;
functionScalar.SelectedFunction = 'a*x-b*y';
functionScalar.OutputDimensionInheritance = 'eCrdnDimensionInheritanceFromX';

Create a new Aligned and Constrained Axes

[MATLAB]

% IAgCrdnProvider vgtSat: Vector Geometry Tool Interface
% IAgCrdnVectorDisplacement Sat2EarthCenter: vector component
% IAgCrdnVectorFixedInAxes bodyYSat: vector component
AxesFactory = vgtSat.Axes.Factory;
AlignConstain = AxesFactory.Create('AlignConstrain', 'Aligned to displacement vector and constrained to Body Y', 'eCrdnAxesTypeAlignedAndConstrained');
AlignConstain.AlignmentReferenceVector.SetVector(Sat2EarthCenter);
AlignConstain.AlignmentDirection.AssignXYZ(1, 0, 0);
AlignConstain.ConstraintReferenceVector.SetVector(bodyYSat);
AlignConstain.ConstraintDirection.AssignXYZ(0, 0, 1);

Create a new Assembled System

[MATLAB]

% IAgCrdnProvider vgtSat: Vector Geometry Tool Interface
% IAgCrdnPointFixedInSystem fixedPt: point component
% IAgCrdnAxes bodyAxes: axes component
SysFactory = vgtSat.Systems.Factory;
assemSys = SysFactory.Create('FixedPtSystem', 'System with origin at the new point', 'eCrdnSystemTypeAssembled');
assemSys.OriginPoint.SetPoint(fixedPt);
assemSys.ReferenceAxes.SetAxes(bodyAxes);

Create a new Attitude Parameter Set

[MATLAB]

% IAgCrdnProvider vgtSat: Vector Geometry Tool Interface
% IAgCrdnAxes bodyAxes: axes component
% IAgCrdnAxes icrfAxes: axes component
paraFactory = vgtSat.ParameterSets.Factory;
paraSet = paraFactory.Create('attitudeICRF', 'Attitude Set', 'eCrdnParameterSetTypeAttitude');
paraSet.Axes = bodyAxes;
paraSet.ReferenceAxes = icrfAxes;

Create a new Between Vectors Angle

[MATLAB]

% IAgCrdnProvider vgtSat: Vector Geometry Tool Interface
% IAgCrdnVectorDisplacement Sat2EarthCenter: vector component
% IAgCrdnVectorFixedInAxes bodyYSat: vector component
AngFactory = vgtSat.Angles.Factory;
betwVect = AngFactory.Create('SatEarth2Y', 'Displacement Vector to Sat Body Y', 'eCrdnAngleTypeBetweenVectors');
betwVect.FromVector.SetVector(Sat2EarthCenter);
betwVect.ToVector.SetVector(bodyYSat);

Create a new Central Body Intersection Point

[MATLAB]

% IAgCrdnProvider vgtSat: Vector Geometry Tool Interface
% IAgCrdnPoint centerPtSat: point component
PtFactory = vgtSat.Points.Factory;
cbIntersectPt = PtFactory.Create('CBIntersectPt', 'Point on surface along nadir vector', 'eCrdnPointTypeCentralBodyIntersect');
cbIntersectPt.CentralBody = 'Earth';
cbIntersectPt.ReferencePoint = centerPtSat;
cbIntersectPt.DirectionVector = vgtSat.Vectors.Item('Nadir(Detic)');
cbIntersectPt.IntersectionSurface = 'eCrdnIntersectionSurfaceAtCentralBodyEllipsoid';

Create a new Collection of Interval List

[MATLAB]

% IAgCrdnProvider vgtSat: Vector Geometry Tool Interface
% IAgCrdnPoint centerPtSat: point component
timeCollListFactory = vgtSat.EventIntervalCollections.Factory;
timeColl = timeCollListFactory.CreateEventIntervalCollectionLighting('LightingList', 'Collection of lighting intervals');
timeColl.UseObjectEclipsingBodies = true;
timeColl.Location = centerPtSat;

Create a new Condition

[MATLAB]

% IAgCrdnProvider vgtSat: Vector Geometry Tool Interface
% IAgCrdnCalcScalarDataElement trueAnom: calc scalar component
condFactory = vgtSat.Conditions.Factory;
scaleBound = condFactory.Create('BelowMax', 'Valid for displacement', 'eCrdnConditionTypeScalarBounds');
scaleBound.Scalar = trueAnom;
scaleBound.Operation = 'eCrdnConditionThresholdOptionBelowMax';
maxValue = root.ConversionUtility.NewQuantity('Angle', 'deg', 180);
scaleBound.SetMaximum(maxValue); % Maximum

Create a new Cross Product Vector

[MATLAB]

% IAgCrdnProvider vgtSat: Vector Geometry Tool Interface
% IAgCrdnVectorDisplacement Sat2EarthCenter: vector component
% IAgCrdnVectorDisplacement fixedAxesVector: vector component
VectFactory = vgtSat.Vectors.Factory;
lineOfNodesVector = VectFactory.CreateCrossProductVector('CrossProduct', Sat2EarthCenter, fixedAxesVector);

Create a new Custom Script Vector

[MATLAB]

% IAgCrdnProvider vgtSat: Vector Geometry Tool Interface
VectFactory = vgtSat.Vectors.Factory;
customScript = VectFactory.Create('Script', 'Description', 'eCrdnVectorTypeCustomScript');
% Initialization script if needed
% customScript.InitializationScriptFile = '';
try
    customScript.ScriptFile = 'C:\Program Files\AGI\STK_ODTK 13\CodeSamples\Extend\PluginScripts\VB_CustomVector.vbs';
catch
end
if customScript.IsValid == false
    disp('Script component not valid!');
    disp(['Extract vbs file from C:\Program Files\AGI\STK_ODTK 13\CodeSamples\CodeSamples.zip, Extend\PluginScripts\VB_CustomVector.vbs to C:\Users\' getenv('USERNAME') '\Documents\STK_ODTK 13\Config\Scripting\VectorTool']);
end

Create a new Displacement Vector

[MATLAB]

% IAgCrdnProvider vgtSat: Vector Geometry Tool Interface
% IAgCrdnPoint centerPtSat: point component
% IAgCrdnPoint centerPtEarth: point component
VectFactory = vgtSat.Vectors.Factory;
Sat2EarthCenter = VectFactory.CreateDisplacementVector('Sat2EarthCenter', centerPtSat, centerPtEarth);

Create a new Fixed at Time Instant Point

[MATLAB]

% IAgCrdnProvider vgtSat: Vector Geometry Tool Interface
% IAgCrdnSystemAssembled icrf: system component
PtFactory = vgtSat.Points.Factory;
timeInstantPt = PtFactory.Create('AtTimePt', 'Point at time instant', 'eCrdnPointTypeAtTimeInstant');
timeInstantPt.SourcePoint = vgtSat.Points.Item('Center');
timeInstantPt.ReferenceSystem = icrf;
timeInstantPt.ReferenceTimeInstant = vgtSat.Events.Item('AvailabilityStartTime');

Create a new Fixed in Axes

[MATLAB]

% IAgCrdnProvider vgtSat: Vector Geometry Tool Interface
% IAgStkObjectRoot root: STK Object Model root
AxesFactory = vgtSat.Axes.Factory;
fixed = AxesFactory.Create('Fixed', 'Axes fixed in Earth Fixed frame using Euler 321 sequence', 'eCrdnAxesTypeFixed');
earthFixed = root.CentralBodies.Earth.Vgt.Axes.Item('Fixed');
fixed.ReferenceAxes.SetAxes(earthFixed);
fixed.FixedOrientation.AssignEulerAngles('e321', 45, 35, 0);

Create a new Fixed in Axes Vector

[MATLAB]

% IAgCrdnProvider vgtSat: Vector Geometry Tool Interface
% IAgCrdnAxes bodyAxes: axes component
VectFactory = vgtSat.Vectors.Factory;
fixedAxesVector = VectFactory.Create('FixedInAxes', '', 'eCrdnVectorTypeFixedInAxes');
fixedAxesVector.ReferenceAxes.SetAxes(bodyAxes);
fixedAxesVector.Direction.AssignXYZ(0, 0, 1);

Create a new Fixed in System Point

[MATLAB]

% IAgCrdnProvider vgtSat: Vector Geometry Tool Interface
PtFactory = vgtSat.Points.Factory;
fixedPt = PtFactory.Create('FixedPt', 'Point offset from Center', 'eCrdnPointTypeFixedInSystem');
fixedPt.Reference.SetPath('Satellite/Satellite1 RIC')
fixedPt.FixedPoint.AssignCartesian(.005, 0, .005);

Create a new Model Attachment Point

[MATLAB]

% IAgCrdnProvider vgtSat: Vector Geometry Tool Interface
PtFactory = vgtSat.Points.Factory;
modelPt = PtFactory.Create('ModelPt', 'Attach point defined in model', 'eCrdnPointTypeModelAttachment');
modelPt.PointableElementName = 'MainSensor-000000';

Create a new Orbit Parameter Set

[MATLAB]

% IAgCrdnProvider vgtSat: Vector Geometry Tool Interface
paraFactory = vgtSat.ParameterSets.Factory;
paraSetOribit = paraFactory.Create('orbitSun', 'Orbit', 'eCrdnParameterSetTypeOrbit');
paraSetOribit.OrbitingPoint = vgtSat.Points.Item('Center');
paraSetOribit.CentralBody = 'Sun';
paraSetOribit.UseCentralBodyGravitationalParameter = false;
paraSetOribit.GravitationalParameter = 398600; % km^3/sec^2

Create a new Projection Vector

[MATLAB]

% IAgCrdnProvider vgtSat: Vector Geometry Tool Interface
% IAgCrdnVectorDisplacement Sat2EarthCenter: vector component
VectFactory = vgtSat.Vectors.Factory;
projectionVector = VectFactory.Create('Projection', '', 'eCrdnVectorTypeProjection');
projectionVector.Source.SetVector(Sat2EarthCenter);
horizontalPlane = vgtSat.Planes.Item('LocalHorizontal');
projectionVector.ReferencePlane.SetPlane(horizontalPlane);

Create a new Quadrant Plane

[MATLAB]

% IAgCrdnProvider vgtSat: Vector Geometry Tool Interface
% IAgCrdnSystemAssembled icrf: system component
PlaneFactory = vgtSat.Planes.Factory;
yzQuad = PlaneFactory.Create('YZQuad', 'YZ Quadrant', 'eCrdnPlaneTypeQuadrant');
yzQuad.ReferenceSystem.SetSystem(icrf);
yzQuad.Quadrant = 'eCrdnQuadrantYZ';

Create a new Time Array

[MATLAB]

% IAgCrdnProvider vgtSat: Vector Geometry Tool Interface
% IAgCrdnEventIntervalListFixed custom: interval list component
timeArrayFactory = vgtSat.EventArrays.Factory;
timeArray = timeArrayFactory.CreateEventArrayStartStopTimes('StartTimes', 'Start Times of Custom Intervals');
timeArray.ReferenceIntervals = custom;
timeArray.StartStopOption = 'eCrdnStartStopOptionCountStartOnly';

Create a new Time Instant

[MATLAB]

% IAgStkObjectRoot root: STK Object Model Root
% IAgCrdnProvider vgtSat: Vector Geometry Tool Interface
% Change DateFormat dimension to epoch seconds to make the time easier to handle in
% MATLAB
root.UnitPreferences.Item('DateFormat').SetCurrentUnit('EpSec');
timeInstFactory = vgtSat.Events.Factory;
timeEpoch = timeInstFactory.CreateEventEpoch('FixedTime', 'Fixed Epoch Time');
timeEpoch.Epoch = 3600;

Create a new Time Interval

[MATLAB]

% IAgStkObjectRoot root: STK Object Model Root
% IAgCrdnProvider vgtSat: Vector Geometry Tool Interface
% Change DateFormat dimension to epoch seconds to make the time easier to handle in
% MATLAB
root.UnitPreferences.Item('DateFormat').SetCurrentUnit('EpSec');
timeIntFactory = vgtSat.EventIntervals.Factory;
timeInterval = timeIntFactory.CreateEventIntervalFixed('TimeInterval', 'Fixed time interval');
timeInterval.SetInterval(60, 120);

Create a new Time Interval List

[MATLAB]

% IAgCrdnProvider vgtSat: Vector Geometry Tool Interface
timeListFactory = vgtSat.EventIntervalLists.Factory;
custom = timeListFactory.Create('Custom', '', 'eCrdnEventIntervalListTypeFixed');
% 2(n) x 1 cell interval: cell of time values
custom.SetIntervals({'2 Feb 2020 00:00:00.000'; '2 Feb 2020 01:00:00.000';'5 Feb 2020 00:05:00.000'; '5 Feb 2020 01:00:00.000'})

Create a new Vector Magnitude Scalar

[MATLAB]

% IAgCrdnProvider vgtSat: Vector Geometry Tool Interface
% IAgCrdnVectorDisplacement Sat2EarthCenter: vector component
calcFactory = vgtSat.CalcScalars.Factory;
displScalar = calcFactory.CreateCalcScalarVectorMagnitude('VectorDisplacement', 'Vector Magnitude of Displacement Vector');
displScalar.InputVector = Sat2EarthCenter;

Get a Scalar component and evaluate at a time

[MATLAB]

% IAgCrdnProvider vgtSat: Vector Geometry Tool Interface
% IAgScenario scenario: Scenario object
deticLatitude = vgtSat.CalcScalars.Item('GroundTrajectory.Detic.LLA.Latitude');
result = deticLatitude.Evaluate(scenario.StartTime);
disp(['The value of detic latitude is ' num2str(result.Value)]);

Get Center point and Inertial System of Earth CB

[MATLAB]

% IAgStkObjectRoot root: STK Object Model root
centerPtEarth = root.CentralBodies.Earth.Vgt.Points.Item('Center');
icrf = root.CentralBodies.Earth.Vgt.Systems.Item('ICRF');

Get default VGT component on vehicle

[MATLAB]

% IAgSatellite satellite: Satellite object
vgtSat = satellite.Vgt;
% Get handle to the Center point on the satellite
centerPtSat = vgtSat.Points.Item('Center');
% Get handle to the Body Y Vector
bodyYSat = vgtSat.Vectors.Item('Body.Y');
% Get handle to the Body Axes
bodyAxes = vgtSat.Axes.Item('Body');
icrfAxes = vgtSat.Axes.Item('ICRF');

Get Times From Defined Time Instant and create an cell array

[MATLAB]

% IAgStkObjectRoot root: STK Object Model Root
% IAgCrdnProvider vgtSat: Vector Geometry Tool Interface
% Change DateFormat dimension to epoch seconds to make the time easier to handle in
% MATLAB
root.UnitPreferences.Item('DateFormat').SetCurrentUnit('EpSec');
satStart= vgtSat.Events.Item('AvailabilityStartTime');
start = satStart.FindOccurrence.Epoch;

satStop= vgtSat.Events.Item('AvailabilityStopTime');
stop = satStop.FindOccurrence.Epoch;
interval = {start 540 600 stop}';   % EpSec

Add Terrain for Analysis

[MATLAB]

% IAgStkObjectRoot root: STK Object Model Root
terrain = root.CurrentScenario.Terrain.Item('Earth').TerrainCollection.Add('C:\Program Files\AGI\STK_ODTK 13\Data\Resources\stktraining\samples\SRTM_Skopje.pdtt', 'ePDTTTerrainFile');
terrain.UseTerrain = true;

Change animation mode

[MATLAB]

% IAgStkObjectRoot root: STK Object Model Root
scenario = root.CurrentScenario;
root.AnimationOptions = 'eAniOptionStop';
root.Mode = 'eAniXRealtime';
scenario.Animation.AnimStepValue = 1;   % second
scenario.Animation.RefreshDelta = .03;  % second

Change scenario font

[MATLAB]

% IAgStkObjectRoot root: STK Object Model Root
scenario = root.CurrentScenario;
scenario.VO.MediumFont.Name = 'Arial';
scenario.VO.MediumFont.PtSize = 18;
scenario.VO.MediumFont.Bold = true;
scenario.VO.MediumFont.Italic = false;

Change scenario time period

[MATLAB]

% IAgStkObjectRoot root: STK Object Model Root
root.CurrentScenario.SetTimePeriod('30 Jul 2014 16:00:05.000', '31 Jul 2014 16:00:00.000');
root.CurrentScenario.Epoch = '30 Jul 2014 16:00:05.000';

Close an open Scenario

[MATLAB]

% IAgStkObjectRoot root: STK Object Model Root
if ~isempty(root.CurrentScenario)
    root.CloseScenario();
end

Close STK

[MATLAB]

% AgUiApplication uiApplication: STK Application
uiApplication.Quit;
clear uiApplication root

Create a new Scenario

[MATLAB]

% IAgStkObjectRoot root: STK Object Model Root
root.NewScenario('Example_Scenario');

Open a VDF

[MATLAB]

% IAgStkObjectRoot root: STK Object Model Root
root.LoadVDF('C:\Program Files\AGI\STK_ODTK 13\Data\ExampleScenarios\Intro_STK_Space_Systems.vdf', '');

Reset the scenario time

[MATLAB]

% IAgStkObjectRoot root: STK Object Model Root
root.Rewind;

Set unit preferences for Object Model

[MATLAB]

% IAgStkObjectRoot root: STK Object Model Root
root.UnitPreferences.Item('DateFormat').SetCurrentUnit('UTCG');
root.UnitPreferences.Item('Distance').SetCurrentUnit('km');

STK window layout settings

[MATLAB]

% AgUiApplication uiApplication: STK Application
% Loop through the available windows to close the Timeline and maximize the
% 3D window
timelineWindow = '';
for i=0:uiApplication.Windows.Count - 1
    window = uiApplication.Windows.Item(i);
    if (strcmp(window.Caption, '3D Graphics 1 - Earth'))
        window.WindowState = 'eWindowStateMaximized';
    elseif (strcmp(window.Caption, ''))
        timelineWindow = window;
    end
end
timelineWindow.Close();

Create instance of AgStkObjectRoot in STK Engine application

[MATLAB]

% Before instantiating AgStkObjectRoot an instance of AgSTKXApplication or an STK X control must be created
% This also requires a STKX license to be present
STKXApplication = actxserver('STKX13.Application');
rootEngine = actxserver('AgStkObjects13.AgStkObjectRoot');

Terminate STK Engine prior to Matlab exit

[MATLAB]

% IAgSTKXApplication STKXApplication: object returned by actxserver('STKX13.Application')

% Once this call is issued, you must no longer use STK Engine until Matlab is restarted
STKXApplication.Terminate();