C# 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

Area Target

Chain

Common

Access

Data Providers

Graphics

2D

3D

Object Coverage

Communications

Link Budget

Constellation

Coverage Definition

Advanced

Graphics

Facility

Figure of Merit

MTO

Analysis

Graphics

3D

Place

Planet

Graphics

Radar

Probability of Detection

Scenario

Graphics

Object Management

Scenario Management

Sensor

Graphics

3D

Star

Target

Vehicles

Aircraft

Common

Attitude

Graphics

3D

Propagators

Astrogator

Ballistic

GPS

Great Arc

HPOP

J2 Perturbation

J4 Perturbation

LOP

Realtime

SGP4

Simple Ascent

SPICE

Ground Vehicle

Launch Vehicle

Missile

Satellite

Ship

STK Plugins

Attributes

Graphics

Bounding Sphere

Box Triangulator

Camera

Convolution Filter

Display Condition

DisplayConditions

Ellipsoid Triangulator

Extruded Polyline Triangulator

GlobeOverlays

Imaging

Jpeg2000 Writer

Model Primitive

Overlay

Path Point

Picking

Position Interpolator

Primitives

Composite Primitive

Marker Batch Primitive

Model Primitive

Path Primitive

Point Batch Primitive

Polyline Primitive

Solid Primitive

Surface Mesh Primitive

Text Batch Primitive

Triangle Mesh Primitive

Projection

Scene Manager

ScreenOverlays

Surface Extent Triangulator

Surface Polygon Triangulator

Surface Shapes

Texture Matrix

Texture Screen Overlays

VGT

Angle

Axes

CalcScalar

Condition

Event

EventArray

EventInterval

EventIntervalCollection

EventIntervalList

ParameterSet

Plane

Point

System

Vector

2D Windows

3D Windows

Utilities

Connect

Conversions

Graphics

Units

Calculations

Conversions

Preferences

Create instance of AgStkObjectRoot in STK Engine application

[C#] Copy Code

// Before instantiating AgStkObjectRoot an instance of AgSTKXApplication or an STK X control must be created
AgStkObjectRoot root = new AgStkObjectRoot();


Get a reference to the AgStkObjectRoot using the running STK instance

[C#] Copy Code

// Get reference to running STK instance
AgUiApplication uiApplication = System.Runtime.InteropServices.Marshal.GetActiveObject("STK11.Application"as AgUiApplication;

// You can also specify STK 32 and 64 bit versions
// Get reference to running STK 32-bit instance
//AgUiApplication uiApplication = System.Runtime.InteropServices.Marshal.GetActiveObject("STK11_x86.Application") as AgUiApplication;
// Get reference to running STK 64-bit instance
//AgUiApplication uiApplication = System.Runtime.InteropServices.Marshal.GetActiveObject("STK11_x64.Application") as AgUiApplication;

// Get our IAgStkObjectRoot interface
IAgStkObjectRoot stkRoot = uiApplication.Personality2 as IAgStkObjectRoot;


Get a reference to the AgStkObjectRoot with display alerts turned off.

[C#] Copy Code

// Get reference to running STK instance
AgUiApplication uiApplication = System.Runtime.InteropServices.Marshal.GetActiveObject("STK11.Application"as AgUiApplication;

// You can also specify STK 32 and 64 bit versions
// Get reference to running STK 32-bit instance
//AgUiApplication uiApplication = System.Runtime.InteropServices.Marshal.GetActiveObject("STK11_x86.Application") as AgUiApplication;
// Get reference to running STK 64-bit instance
//AgUiApplication uiApplication = System.Runtime.InteropServices.Marshal.GetActiveObject("STK11_x64.Application") as AgUiApplication;

//Create a new instance of the application model root object.
AgUiApplication uiApplication2 = uiApplication.CreateApplication() as AgUiApplication;

//Set DisplayAlerts to false to suppress certain alerts and messages.
//This is useful when automating tasks.
uiApplication2.DisplayAlerts = false;

// Get our IAgStkObjectRoot interface with display alerts turned off
IAgStkObjectRoot stkRoot = uiApplication2.Personality2 as IAgStkObjectRoot;


Start STK and get a reference to IAgStkObjectRoot

[C#] Copy Code

// Create an instance of STK
AgUiApplication uiApplication = new AgUiApplication();
uiApplication.LoadPersonality("STK");
uiApplication.Visible = true;

// Get our IAgStkObjectRoot interface
IAgStkObjectRoot stkRoot = uiApplication.Personality2 as IAgStkObjectRoot;


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

[C#] Copy Code
// IAgStkObjectRoot root: STK Object Model Root

// Create the AreaTarget on the current scenario central body (use
// NewOnCentralBody to specify explicitly the central body)
IAgAreaTarget areaTarget = root.CurrentScenario.Children.New(AgESTKObjectType.eAreaTarget, "MyAreaTarget"as IAgAreaTarget;


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

[C#] Copy Code
// 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 = AgEAreaType.ePattern;
IAgAreaTypePatternCollection patterns = areaTarget.AreaTypeData as IAgAreaTypePatternCollection;
patterns.Add(48.89718.637);
patterns.Add(46.53413.919);
patterns.Add(44.17321.476);
root.EndUpdate();


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

[C#] Copy Code
// IAgStkObjectRoot root: STK Object Model Root
// IAgAreaTarget areaTarget: AreaTarget object

// By using the CommonTasks interface,
// make an array of lattitude and longitude boundary points
Array boundary = new object[,]
    {
        { 48.89718.637 },
        { 46.53413.919 },
        { 44.17321.476 }
    };

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


List all points in an area target

[C#] Copy Code
// IAgAreaTarget areaTarget: AreaTarget object

if (areaTarget.AreaType == AgEAreaType.ePattern)
{
    // Get IAgAreaTypePatternCollection interface from AreaTypeData
    IAgAreaTypePatternCollection patternPoints = areaTarget.AreaTypeData as IAgAreaTypePatternCollection;

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

    Console.WriteLine("All points in Area Target");
    for (int i = 0; i < areaTargetPoints.GetLength(0); ++i)
    {
        Console.WriteLine("  Latitude {0} Longitude: {1}",
            Convert.ToDouble(areaTargetPoints.GetValue(i, 0)),
            Convert.ToDouble(areaTargetPoints.GetValue(i, 1)));
    }
}


Set an elliptical area target

[C#] Copy Code
// 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 = AgEAreaType.eEllipse;
IAgAreaTypeEllipse ellipse = areaTarget.AreaTypeData as IAgAreaTypeEllipse;
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)

[C#] Copy Code
// IAgStkObjectRoot root: STK Object Model Root
// IAgAreaTarget areaTarget: AreaTarget object

// By using the CommonTasks interface
areaTarget.CommonTasks.SetAreaTypeEllipse(85.2580.7544);


Configure the chain compute time period.

[C#] Copy Code
// IAgChain chain: Chain object

chain.SetTimePeriodType(AgEChTimePeriodType.eUserSpecifiedTimePeriod);
IAgChUserSpecifiedTimePeriod userSpecifiedTimePeriod = chain.TimePeriod as IAgChUserSpecifiedTimePeriod;
userSpecifiedTimePeriod.TimeInterval.SetExplicitInterval("1 May 2015 04:00:00.000""1 May 2015 05:00:00.000");


Create a chain (on the current scenario central body)

[C#] Copy Code
// IAgStkObjectRoot root: STK Object Model Root

// Create the Chain on the current scenario central body (use
// NewOnCentralBody to specify explicitly the central body)
IAgChain chain = root.CurrentScenario.Children.New(AgESTKObjectType.eChain, "MyChain"as IAgChain;


Define and compute a chain (advance)

[C#] Copy Code
// IAgChain chain: Chain object

// Remove all previous accesses
chain.ClearAccess();

// Add some objects to chain
chain.Objects.Add("Facility/fac1");
chain.Objects.Add("Satellite/sat1");
chain.Objects.Add("Satellite/sat2");
chain.Objects.Add("Aircraft/air1");

// Configure chain parameters
chain.AutoRecompute = false;
chain.EnableLightTimeDelay = false;
chain.TimeConvergence = 0.001;
chain.DataSaveMode = AgEDataSaveMode.eSaveAccesses;

// Specify our own time period
chain.SetTimePeriodType(AgEChTimePeriodType.eUserSpecifiedTimePeriod);

// Get chain time period interface
IAgChUserSpecifiedTimePeriod chainUserTimePeriod = chain.TimePeriod as IAgChUserSpecifiedTimePeriod;
chainUserTimePeriod.SetTimePeriod("1 Jul 2005 12:00:00""2 Jul 2005 12:00:00");

// Compute the chain
chain.ComputeAccess();


Define and compute a chain (basic)

[C#] Copy Code
// IAgChain chain: Chain object

// Add some objects to chain (using STK path)
chain.Objects.Add("Facility/fac1");
chain.Objects.Add("Satellite/sat1");
chain.Objects.Add("Satellite/sat2");
chain.Objects.Add("Aircraft/air1");

// Compute the chain
chain.ComputeAccess();


Prints the strand intervals of chain object

[C#] Copy Code
// IAgChain chain: Chain Object

IAgStkObject chainAsStkObject = chain as IAgStkObject;

// Compute the chain access if not done already.
chain.ComputeAccess();

// Considered Start and Stop time
Console.WriteLine("Chain considered start time: {0}", chainAsStkObject.Vgt.Events["ConsideredStartTime"].FindOccurrence().Epoch);
Console.WriteLine("Chain considered stop time: {0}", chainAsStkObject.Vgt.Events["ConsideredStopTime"].FindOccurrence().Epoch);

IAgCrdnEventIntervalCollection objectParticipationIntervals = chainAsStkObject.Vgt.EventIntervalCollections["StrandAccessIntervals"];
IAgCrdnIntervalsVectorResult intervalListResult = objectParticipationIntervals.FindIntervalCollection();

for (int i = 0; i < intervalListResult.IntervalCollections.Count; ++i)
{
    if (intervalListResult.IsValid)
    {
        Console.WriteLine("Link Name: {0}", objectParticipationIntervals.Labels.GetValue(i));
        Console.WriteLine("--------------");
        for (int j = 0; j < intervalListResult.IntervalCollections[i].Count; ++j)
        {
            object startTime = intervalListResult.IntervalCollections[i][j].Start;
            object stopTime = intervalListResult.IntervalCollections[i][j].Stop;
            Console.WriteLine("Start: {0}, Stop: {1}", startTime, stopTime);
        }
    }
}


Delete a STK Object

[C#] Copy Code
// IAgStkObject stkObject: STK Object to be removed

stkObject.Unload();


Export a STK Object to a file

[C#] Copy Code
// IAgStkObject stkObject: STK Object to be exported
// String outputPath: Output path

string fileNameWithoutExtension = Path.Combine(outputPath, "MySatellite1");
stkObject.Export(fileNameWithoutExtension);


Import an existing STK Object file into an object collection

[C#] Copy Code
// IAgStkObjectCollection col: STK Object Collection
// String stkObjectLocation: Path of STK Object external file

col.ImportObject(stkObjectLocation);


Rename a STK Object

[C#] Copy Code
// IAgStkObject stkObject: STK Object to be renamed

stkObject.InstanceName = "NewObjectName";


Set/Get the STK Object description

[C#] Copy Code
// IAgStkObject stkobject: STK Object

// Set STK Object description
stkobject.LongDescription = "This is a very very very long description";
stkobject.ShortDescription = "This is a short description";

// Get STK Object description
string longDescription = stkobject.LongDescription;
string shortDescription = stkobject.ShortDescription;


Add an access constraint to an STK Object

[C#] Copy Code
// IAgStkObject stkobject: STK Object

IAgAccessConstraintCollection accessConstraints = stkobject.AccessConstraints;

// Add constraints
accessConstraints.AddConstraint(AgEAccessConstraints.eCstrSunElevationAngle);


Add and configure a lighting condition access constraint

[C#] Copy Code
// IAgAccessConstraintCollection accessConstraints: Access Constraint collection

// Condition constraint
IAgAccessCnstrCondition light = accessConstraints.AddConstraint(AgEAccessConstraints.eCstrLighting) as IAgAccessCnstrCondition;
light.Condition = AgECnstrLighting.eDirectSun;


Add and configure a LOS sun exclusion access constraint

[C#] Copy Code
// IAgAccessConstraintCollection accessConstraints: Access Constraint collection

// Angle constraint
IAgAccessCnstrAngle cnstrAngle = accessConstraints.AddConstraint(AgEAccessConstraints.eCstrLOSSunExclusion) as IAgAccessCnstrAngle;
cnstrAngle.Angle = 176.0;


Add and configure a lunar elevation angle access constraint

[C#] Copy Code
// IAgAccessConstraintCollection accessConstraints: Access Constraint collection

IAgAccessCnstrMinMax minmax = accessConstraints.AddConstraint(AgEAccessConstraints.eCstrLunarElevationAngle) as IAgAccessCnstrMinMax;
minmax.EnableMin = true;
minmax.Min = 11.1;
minmax.EnableMax = true;
minmax.Max = 88.8;


Add and configure a sun elevation angle access constraint

[C#] Copy Code
// IAgAccessConstraintCollection accessConstraints: Access Constraint collection

IAgAccessCnstrMinMax minmax = accessConstraints.AddConstraint(AgEAccessConstraints.eCstrSunElevationAngle) as IAgAccessCnstrMinMax;
minmax.EnableMin = true;
minmax.Min = 22.2;
minmax.EnableMax = true;
minmax.Max = 77.7;


Add and configure a third body obstruction access constraint

[C#] Copy Code
// IAgAccessConstraintCollection accessconstraints: Access Constraint collection

// Get IAgAccessCnstrThirdBody interface
IAgAccessCnstrThirdBody thirdBodyConstraint = accessconstraints.AddConstraint(AgEAccessConstraints.eCstrThirdBodyObstruction) as IAgAccessCnstrThirdBody;

// AvailableObstructions returns a one dimensional array of obstruction paths
Array availableArray = thirdBodyConstraint.AvailableObstructions;

// In this example add all available obstructions
Console.WriteLine("Available obstructions");
foreach (string available in availableArray)
{
    Console.WriteLine(available);
    thirdBodyConstraint.AddObstruction(available);
}

// AssignedObstructions returns a one dimensional array of obstruction paths
Array assignedArray = thirdBodyConstraint.AssignedObstructions;

Console.WriteLine("Assigned obstructions");
foreach (string assigned in assignedArray)
{
    Console.WriteLine(assigned);
}


Add and configure an altitude access constraint

[C#] Copy Code
// IAgAccessConstraintCollection accessConstraints: Access Constraint collection

// Attitude constraint
IAgAccessCnstrMinMax altitude = accessConstraints.AddConstraint(AgEAccessConstraints.eCstrAltitude) as IAgAccessCnstrMinMax;
altitude.EnableMin = true;
altitude.Min = 20.5;


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

[C#] Copy Code
// IAgStkObject stkobject: STK Object

IAgAccessConstraintCollection accessConstraints = stkobject.AccessConstraints;

// Add constraints
// Only the eCstrApparentTime, eCstrDuration, eCstrGMT, eCstrIntervals, eCstrLocalTime constraint
// types can be added multiple times to the constraint collection.
accessConstraints.AddConstraint(AgEAccessConstraints.eCstrLocalTime);
accessConstraints.AddConstraint(AgEAccessConstraints.eCstrLocalTime);


Compute an access and get constraint data from data provider

[C#] Copy Code
// IAgStkObjectRoot root: STK Object Model root

// Compute Access between the facility and the satellite
IAgStkObject sat1 = root.GetObjectFromPath("Satellite/Satellite1");
IAgStkObject fac1 = root.GetObjectFromPath("Facility/Facility1");
IAgStkAccess access = sat1.GetAccessToObject(fac1);
access.ComputeAccess();

// Get the access intervals
IAgIntervalCollection accessIntervals = access.ComputedAccessIntervalTimes;

// Set unit preferences - change to get your preferred units
root.UnitPreferences.SetCurrentUnit("Distance""km");
root.UnitPreferences.SetCurrentUnit("Angle""deg");
root.UnitPreferences.SetCurrentUnit("Time""sec");
root.UnitPreferences.SetCurrentUnit("DateFormat""UTCG");

// Extract the access intervals and the range information for each access interval
Array dataPrvElements = new object[]
    {
        "Time""FromAngularRate""FromRange"
    };

IAgDataPrvTimeVar dp = access.DataProviders["Constraint Data"as IAgDataPrvTimeVar;

for (int index0 = 0; index0 < accessIntervals.Count; ++index0)
{
    object startTime = null, stopTime = null;

    accessIntervals.GetInterval(index0, out startTime, out stopTime);

    Console.WriteLine("Access Interval #{0} - Start={1} Stop={2}", index0, startTime, stopTime);

    IAgDrResult result = dp.ExecElements(startTime, stopTime, 60ref dataPrvElements);

    Array timeValues = result.DataSets[0].GetValues();
    Array fromAngularRateValues = result.DataSets[1].GetValues();
    Array fromRangeValues = result.DataSets[2].GetValues();

    for (int index1 = 0; index1 < timeValues.GetLength(0); ++index1)
    {
        Console.WriteLine("{0}: FromAngularRate={1} FromRange={2}",
            timeValues.GetValue(index1),
            fromAngularRateValues.GetValue(index1),
            fromRangeValues.GetValue(index1));
    }

    Console.WriteLine();
}


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

[C#] Copy Code
// IAgStkObject stkObject1: STK Object
// IAgStkObject stkObject2: STK Object

// Get access by STK Object
IAgStkAccess access = stkObject1.GetAccessToObject(stkObject2);

// Compute access
access.ComputeAccess();


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

[C#] Copy Code
// IAgStkObject stkObject: STK Object

// Get access by object path
IAgStkAccess access = stkObject.GetAccess("Facility/fac1");

// Compute access
access.ComputeAccess();


Compute an access for one point

[C#] Copy Code
// IAgStkObject facility: Facility object

IAgOnePtAccess onePtAccess = facility.CreateOnePointAccess("Satellite/Satellite1");

// Configure properties (if necessary)
onePtAccess.StartTime = "1 Jan 2012 12:00:00.000";
onePtAccess.StopTime = "1 Jan 2012 13:00:00.000";
onePtAccess.StepSize = 120;
onePtAccess.SummaryOption = AgEOnePtAccessSummary.eOnePtAccessSummaryDetailed;

// Compute results
IAgOnePtAccessResultCollection results = onePtAccess.Compute();

// Print results
for (int i = 0; i < results.Count; i++)
{
    IAgOnePtAccessResult result = results[i];

    Console.WriteLine("Time: {0}, HasAccess: {1}", result.Time, result.AccessSatisfied);

    for (int j = 0; j < result.Constraints.Count; j++)
    {
        IAgOnePtAccessConstraint constraint = result.Constraints[j];
        Console.WriteLine("Constraint: {0}, Object {1}, Status {2}, Value {3}",
            constraint.Constraint,
            constraint.ObjectPath,
            constraint.Status,
            constraint.Value);
    }
}


Compute and extract access interval times

[C#] Copy Code
// IAgStkAccess access: Access calculation

// Get and display the Computed Access Intervals
IAgIntervalCollection intervalCollection = access.ComputedAccessIntervalTimes;

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


Configure the access analysis time period to specified time instants.

[C#] Copy Code
// IAgStkObjectRoot stkRoot: STK Object Model root

IAgStkObject uav = stkRoot.GetObjectFromPath("/Aircraft/UAV");
IAgStkObject sensor = stkRoot.GetObjectFromPath("/Aircraft/UAV/Sensor/UAVSensor");
IAgStkObject coloradoSprings = stkRoot.GetObjectFromPath("/Place/ColoradoSprings");

// For this code snippet, let's use the time interval when the UAV reached min and max altitude values.
// Note, this assumes time at min happens before time at max.
IAgCrdnEvent timeOfAltMin = uav.Vgt.Events["GroundTrajectory.Detic.LLA.Altitude.TimeOfMin"];
IAgCrdnEvent timeOfAltMax = uav.Vgt.Events["GroundTrajectory.Detic.LLA.Altitude.TimeOfMax"];

// Set the access time period with the times we figured out above.
IAgStkAccess access = sensor.GetAccessToObject(coloradoSprings);
access.AccessTimePeriod = AgEAccessTimeType.eUserSpecAccessTime;
IAgAccessTimePeriod accessTimePeriod = access.AccessTimePeriodData as IAgAccessTimePeriod;

accessTimePeriod.AccessInterval.State = AgECrdnSmartIntervalState.eCrdnSmartIntervalStateStartStop;

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

IAgCrdnEventSmartEpoch 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.

[C#] Copy Code
// IAgStkObjectRoot stkRoot: STK Object Model root

IAgStkObject satellite = stkRoot.GetObjectFromPath("/Satellite/GEO");
IAgStkObject otherObject = stkRoot.GetObjectFromPath("/Aircraft/UAV/Sensor/UAVSensor");
IAgStkAccess access = satellite.GetAccessToObject(otherObject);

access.AccessTimePeriod = AgEAccessTimeType.eUserSpecAccessTime;
IAgAccessTimePeriod accessTimePeriod = access.AccessTimePeriodData as IAgAccessTimePeriod;

if (otherObject.Vgt.EventIntervals.Contains("AvailabilityTimeSpan"))
{
    IAgCrdnEventInterval availabilityTimeSpan = otherObject.Vgt.EventIntervals["AvailabilityTimeSpan"];
    accessTimePeriod.AccessInterval.SetImplicitInterval(availabilityTimeSpan);
}


Enumerate the available constraints collection

[C#] Copy Code
// IAgAccessConstraintCollection accessConstraints: Access Constraint collection

// The AvailableConstraints method returns a rectangular two-dimensional array of available constraints.
// A row of the array consists of two elements where the first element is a symbolic name of the constraint,
// and the second is a corresponding enumeration value.

Array arAvailable = accessConstraints.AvailableConstraints();
for (int i = 0; i < arAvailable.GetLength(0); i++)
{
    string availName = (string)arAvailable.GetValue(i, 0);
    AgEAccessConstraints eAccessConstraint = (AgEAccessConstraints)(int)arAvailable.GetValue(i, 1);
    Console.WriteLine("\tConstraint {0}: {1} ({2})", i, availName, eAccessConstraint);
}


GetAccessBetweenObjectsByPath using the output of GetExistingAccesses

[C#] Copy Code
// IAgStkObjectRoot stkRoot: STK Object Model root

IAgScenario scenario = stkRoot.CurrentScenario as IAgScenario;
Array accesses = scenario.GetExistingAccesses();

int numAccesses = accesses.GetLength(0);  // number of accesses

string object1 = accesses.GetValue(00).ToString();    // e.g. "Facility/Fac1"
string object2 = accesses.GetValue(01).ToString();    // e.g. "Satellite/Sat1"
bool computed = (bool)accesses.GetValue(02);          // e.g. true  (if access has been computed)

IAgStkAccess access = scenario.GetAccessBetweenObjectsByPath(object1, object2);


List all exclusion zones of an access constraint

[C#] Copy Code
// IAgAccessConstraintCollection accessconstraints: Access Constraint collection

IAgAccessCnstrExclZonesCollection excZones = accessconstraints.GetActiveConstraint(AgEAccessConstraints.eCstrExclusionZone) as IAgAccessCnstrExclZonesCollection;

if (excZones != null)
{
    // ToArray returns a two dimensional array
    // The second dimension is an array of minLon, minLat, maxLon, maxLat values
    Array zones = excZones.ToArray(0, -1);

    for (int i = 0; i < zones.GetUpperBound(0); i++)
    {
        Console.WriteLine("MinLon: {0}, MinLat: {1}, MaxLon: {2}, MaxLat {3}", zones.GetValue(i, 0), zones.GetValue(i, 1), zones.GetValue(i, 2), zones.GetValue(i, 3));
    }
}


Remove an access constraint from a STK Object

[C#] Copy Code
// IAgStkObject stkobject: STK Object

IAgAccessConstraintCollection accessConstraints = stkobject.AccessConstraints;

// Remove constraints
accessConstraints.RemoveConstraint(AgEAccessConstraints.eCstrSunElevationAngle);


Coarse grain approach to retrieving a fixed data provider

[C#] Copy Code
// IAgStkObjectRoot root: STK Object Model root
// IAgStkObject facility: STK Object that contains fixed data provider

IAgDataPrvFixed dp = facility.DataProviders.GetDataPrvFixedFromPath("Terrain Info//LocalHorizontal");
IAgDrResult result = dp.Exec();


Coarse grain approach to retrieving a interval data provider

[C#] Copy Code
// IAgStkObject facility: STK Object

IAgDataPrvInterval dp = facility.DataProviders.GetDataPrvIntervalFromPath("Lighting Times//Sunlight");
IAgDrResult result = dp.Exec("1 Jan 2012 12:00:00.000""1 Jan 2012 12:00:20.000");


Coarse grain approach to retrieving a time var data provider

[C#] Copy Code
// IAgStkObject facility: STK Object

IAgDataPrvTimeVar dp = facility.DataProviders.GetDataPrvTimeVarFromPath("Lighting AER");
IAgDrResult result = dp.Exec(
    "1 Jan 2012 12:00:00.000",
    "1 Jan 2012 12:00:20.000",
    60.0);


Coarse grain approach to retrieving data provider information

[C#] Copy Code
// IAgStkObject facility: Facility STK Object

// The path separator is //
IAgDataProviderInfo dp = facility.DataProviders.GetDataPrvInfoFromPath("Lighting Times//Sunlight");
string dpiName              = dp.Name;
AgEDataProviderType dpiType = dp.Type;
bool isGroup                = dp.IsGroup();


Execute a non time dependent data provider (for instance facility position)

[C#] Copy Code
// IAgStkObject facility: STK Object

IAgDataPrvFixed dpInfo = facility.DataProviders["Cartesian Position"as IAgDataPrvFixed;
IAgDrResult resInfo = dpInfo.Exec();


Execute a non time dependent data provider (for instance facility position) and request only the specified elements

[C#] Copy Code
// IAgStkObject facility: STK Object

Array elems = new object[]
              {
                  "x""z"
              };

IAgDataPrvFixed dpInfo = facility.DataProviders["Cartesian Position"as IAgDataPrvFixed;

// ExecElements expects a one dimensional array of element names
IAgDrResult resInfo = dpInfo.ExecElements(ref elems);


Execute a time dependent data provider and request all elements for the specified time interval

[C#] Copy Code
// IAgStkObject facility: STK Object

IAgDataPrvTimeVar dpInfo = facility.DataProviders["Lighting AER"as IAgDataPrvTimeVar;
IAgDrResult resInfo = dpInfo.Exec(
    "1 Jan 2012 12:00:00.000",
    "1 Jan 2012 12:00:20.000",
    60.0);


Execute a time dependent data provider and returning all elements for a single time

[C#] Copy Code
// IAgStkObject satellite: STK Object

IAgDataPrvTimeVar dp = satellite.DataProviders["Precision Passes"as IAgDataPrvTimeVar;
IAgDrResult resInfo = dp.ExecSingle("1 Jan 2012 12:00:00.000");


Execute a time dependent data provider and returning the specified elements at the specified time

[C#] Copy Code
// IAgStkObject satellite: STK Object

Array times = new object[]
              {
                  "1 Jan 2012 12:00:00.000""1 Jan 2012 12:00:20.000",
                  "1 Jan 2012 12:00:40.000"
              };
Array elems = new object[]
              {
                  "Time",
                  "Precision Pass Number"
              };

IAgDataPrvTimeVar dp = satellite.DataProviders["Precision Passes"as IAgDataPrvTimeVar;

// ExecSingleElementsArray expects each safe array parameter to be one dimensional,
// all arrays must have the same length
IAgDrTimeArrayElements resInfo = dp.ExecSingleElementsArray(ref times, ref elems);


Execute a time dependent data provider and returning the specified elements for a single time

[C#] Copy Code
// IAgStkObject satellite: STK Object

Array elems = new object[]
              {
                  "Time",
                  "Precision Pass Number"
              };

IAgDataPrvTimeVar dp = satellite.DataProviders["Precision Passes"as IAgDataPrvTimeVar;

// ExecSingleElements expects as the second parameter a one dimensional array of element names
IAgDrResult resInfo = dp.ExecSingleElements("1 Jan 2012 12:00:00.000"ref elems);


Execute a time dependent data provider which uses preData and returning the specified elements

[C#] Copy Code
// IAgStkObject satObj: Satellite STK Object

Array elems = new object[]
"Range""Radial Rate" };
IAgDataPrvTimeVar RICdp = satObj.DataProviders["Relative Motion"as IAgDataPrvTimeVar;
(RICdp as IAgDataProvider).PreData = "Satellite/Satellite123";
IAgDrResult result = RICdp.ExecElements("26 Jan 2015 17:00:00.000""27 Jan 2015 17:00:00.000"120ref elems);
IAgDrDataSetCollection datasets = result.DataSets;

if (result.DataSets.Count > 0)
{
    System.Array arrayRange = datasets[0].GetValues();
    System.Array arrayRadialRate = datasets[1].GetValues();
}


Execute a time dependent group data provider which uses preData and returning the specified elements

[C#] Copy Code
// IAgStkObject satObj: Satellite STK Object

Array elems = new object[]
"Time""x""y""z" };
IAgDataProviderGroup dpVectorChoose = satObj.DataProviders["Vector Choose Axes"as IAgDataProviderGroup;
IAgDataProvider groupPosition = dpVectorChoose.Group["Position"as IAgDataProvider;
groupPosition.PreData = "Satellite/Sat2 Body";
IAgDataPrvTimeVar timeVarDP = groupPosition as IAgDataPrvTimeVar;
IAgDrResult result = timeVarDP.ExecElements("26 Jan 2015 17:00:00.000""27 Jan 2015 17:00:00.000"120ref elems);
IAgDrDataSetCollection datasets = result.DataSets;

if (result.DataSets.Count > 0)
{
    System.Array arrayTime = datasets[0].GetValues();
    System.Array arrayX = datasets[1].GetValues();
    System.Array arrayY = datasets[2].GetValues();
    System.Array arrayZ = datasets[2].GetValues();
}


Execute an interval data provider (for instance access times) and returning all elements

[C#] Copy Code
// IAgStkObject satellite: Satellite STK Object
// IAgStkObject areatarget: Area Target STK Object

IAgStkAccess Access = satellite.GetAccessToObject(areatarget) as IAgStkAccess;
Access.ComputeAccess();

IAgDataPrvInterval dpInfo = Access.DataProviders["Access Data"as IAgDataPrvInterval;

IAgDrResult resInfo = dpInfo.Exec(
    "1 Jan 2012 12:00:00.000",
    "2 Jan 2012 12:00:00.000");


Execute an interval data provider (for instance access times) and returning only the specified elements

[C#] Copy Code
// IAgStkObject satellite: Satellite STK Object
// IAgStkObject areatarget: Area Target STK Object

IAgStkAccess access = satellite.GetAccessToObject(areatarget) as IAgStkAccess;
access.ComputeAccess();

IAgDataPrvInterval dp = access.DataProviders["Access Data"as IAgDataPrvInterval;

Array elems = new object[]
              {
                  "Start Time",
                  "Stop Time",
                  "Access Number",
                  "From Pass Number",
                  "To Pass Number",
                  "From Start Alt",
                  "From Stop Alt"
              };

// ExecElements expects the third parameter to be a one dimensional array of element names
IAgDrResult resInfo = dp.ExecElements(
    "1 Jan 2012 12:00:00.000",
    "2 Jan 2012 12:00:00.000",
    ref elems);


Execute an object coverage data provider and dump its result

[C#] Copy Code
// IAgStkObjectRoot root: STK Object

IAgStkObject aircraft = root.CurrentScenario.Children["aircraft340"];

IAgStkObjectCoverage objectCoverage = aircraft.ObjectCoverage;
objectCoverage.Clear();
objectCoverage.Assets.Add("Constellation/gps_const");
objectCoverage.Compute();

IAgDataPrvTimeVar provider = objectCoverage.DataProviders["FOM by Time"as IAgDataPrvTimeVar;

IAgDrResult result = provider.Exec("1 Jan 2012 12:00:00.00""1 Jan 2012 13:00:00.00"1);

foreach (IAgDrSubSection section in result.Sections)
{
    foreach (IAgDrInterval interval in section.Intervals)
    {
        Array arBoundaries = new object[]
                             {
                                 1.02.03.04.05.0
                             };

        // MultipleThresholdCrossings expects the second parameter
        // to be a one demensional array of boundary index values
        Array arRanges = interval.MultipleThresholdCrossings("FOM Value"ref arBoundaries);

        for (int iRange = 0; iRange < arRanges.GetLength(0); iRange++)
        {
            Console.Write("\nRange: {0}\n", iRange);

            Array arTimeSpans = arRanges.GetValue(iRange) as Array;
            for (int iSpan = 0; iSpan < arTimeSpans.GetLength(0); iSpan++)
            {
                string strStart = arTimeSpans.GetValue(iSpan, 0).ToString();
                string strStop = arTimeSpans.GetValue(iSpan, 1).ToString();

                Console.Write("Start: {0} Stop: {1}\n", strStart, strStop);
            }
        }
    }
}


Extract data from IAgDrDataSetCollection (generic)

[C#] Copy Code
// IAgDrDataSetCollection datasets: Data provider data sets

foreach (String name in datasets.ElementNames)
{
    //If the data set collection spans multiple intervals then the GetDataSetByName method will only
    //get the first intervals dataset.  See the Extract data from IAgDrDataSetCollection across
    //multiple intervals code snippet to see how to access all of the data sets in the result.
    IAgDrDataSet dataset = datasets.GetDataSetByName(name);

    Array datasetValues = dataset.GetValues();

    Console.WriteLine("{0}", dataset.ElementName);

    foreach (object value in datasetValues)
    {
        Console.WriteLine("\t{0}", value.ToString());
    }
}


Extract data from IAgDrDataSetCollection across multiple intervals.

[C#] Copy Code
// IAgDrDataSetCollection datasets: Data provider data sets

foreach (IAgDrDataSet set in datasets)
{
    Console.WriteLine("{0}", set.ElementName);
    foreach (object value in set.GetValues())
    {
        Console.WriteLine("\t{0}", value.ToString());
    }
}


Extract data from IAgDrIntervalCollection (generic)

[C#] Copy Code
// IAgDrIntervalCollection intervals: Data provider intervals

// Enumerate IAgDrIntervalCollection collection
foreach (IAgDrInterval interval in intervals)
{
    Console.WriteLine("{0} - {1}", interval.StartTime, interval.StopTime);

    foreach (IAgDrDataSet dataset in interval.DataSets)
    {
        Array values = dataset.GetValues();

        Console.WriteLine("{0}", dataset.ElementName);

        foreach (object value in values)
        {
            Console.WriteLine("\t{0}", value.ToString());
        }
    }
}


Extract data from IAgDrResult based on its category (generic)

[C#] Copy Code
// IAgDrResult result: Data provider result

// Look at the Category property to find out which interface to use
switch (result.Category)
{
    case AgEDrCategories.eDrCatDataSetList:
        IAgDrDataSetCollection datasets = result.DataSets;
        // See IAgDrDataSetCollection inteface
        break;
    case AgEDrCategories.eDrCatIntervalList:
        IAgDrIntervalCollection intervals = result.Intervals;
        // See IAgDrIntervalCollection interface
        break;
    case AgEDrCategories.eDrCatMessage:
        IAgDrTextMessage message = result.Message;
        // See IAgDrTextMessage interface
        break;
    case AgEDrCategories.eDrCatSubSectionList:
        IAgDrSubSectionCollection section = result.Sections;
        // See IAgDrSubSectionCollection interface
        break;
}
        }


Extract data from IAgDrSubSectionCollection (generic)

[C#] Copy Code
// IAgDrSubSectionCollection subSection: Subsection collection

foreach (IAgDrSubSection section in subSection)
{
    Console.WriteLine(section.Title);

    foreach (IAgDrInterval interval in section.Intervals)
    {
        Console.WriteLine("\tTime {0} - {1}", interval.StartTime, interval.StopTime);

        foreach (IAgDrDataSet dataset in interval.DataSets)
        {
            Array values = dataset.GetValues();

            Console.WriteLine("\t{0}", dataset.ElementName);

            foreach (object value in values)
            {
                Console.WriteLine("\t\t{0}", value.ToString());
            }
        }
    }
}


Extract data from IAgDrTextMessage (generic)

[C#] Copy Code
// IAgDrTextMessage message: 

foreach (object messagei in message.Messages)
{
    Console.WriteLine(messagei);
}


Set STK Object Display to always on

[C#] Copy Code
// IAgStkObject stkObject: STK Object

IAgDisplayTm display = stkObject as IAgDisplayTm;
display.SetDisplayStatusType(AgEDisplayTimesType.eAlwaysOn);


Set STK Object Display to use during access mode

[C#] Copy Code
// IAgStkObject stkObject: STK Object

// Attempt to cast STK Object to the IAgDisplayTm interface
IAgDisplayTm display = stkObject as IAgDisplayTm;
if (display != null)
{
    // Configure during access
    if (display.IsDisplayStatusTypeSupported(AgEDisplayTimesType.eDuringAccess))
    {
        display.SetDisplayStatusType(AgEDisplayTimesType.eDuringAccess);

        IAgDuringAccess duringAccess = display.DisplayTimesData as IAgDuringAccess;

        // Add subsequent existing stk objects to access diplay ...
        duringAccess.AccessObjects.Add("Satellite/satellite1");
        duringAccess.AccessObjects.Add("Star/star1");
    }
}


Set STK Object Display to use intervals mode

[C#] Copy Code
// IAgStkObject stkObject: STK Object

// Attempt to cast STK Object to the IAgDisplayTm interface
IAgDisplayTm display = stkObject as IAgDisplayTm;
if (display != null)
{
    // Configure display intervals
    if (display.IsDisplayStatusTypeSupported(AgEDisplayTimesType.eUseIntervals))
    {
        display.SetDisplayStatusType(AgEDisplayTimesType.eUseIntervals);

        // Get IAgIntervalCollection interface
        IAgIntervalCollection intervalCollection = display.DisplayTimesData as IAgIntervalCollection;
        intervalCollection.RemoveAll();

        // Add subsequent intervals...
        intervalCollection.Add(
            "1 Jan 2012 12:00:00.00",
            "1 Jan 2012 13:00:00.000");
    }
}


Set scenario display to hide and show STK Objects in a specified 2D window

[C#] Copy Code
// IAgScenario scenario: Scenario object

IAgScGraphics gfx = scenario.Graphics;

// Individually
gfx.HideObject("Facility/facility1""all");
gfx.ShowObject("Facility/facility1""1");

// In Batches
// HideObjects and ShowObjects expects as the first parameter a one dimensional array of object paths
Array objects = new object[]
                {
                    "Facility/facility1",
                    "Facility/facility2"
                };
gfx.HideObjects(ref objects, "1");
gfx.ShowObjects(ref objects, "all");


Configure 3D data display

[C#] Copy Code
// IAgVODataDisplayCollection datadisplaycol: Data Display Collection

// Add existing data display
// See AvailableData property for available data display
IAgVODataDisplayElement displayElement = datadisplaycol.Add("Solar Intensity");

// Configure data display as needed
displayElement.TitleText = "Sol. Intensity";
displayElement.IsVisible = true;
displayElement.Location = AgEVOLocation.e3DWindow;
displayElement.FontColor = Color.White;
displayElement.FontSize = AgEVOFontSize.eSmall;
displayElement.UseBackground = true;
displayElement.BgColor = Color.Orange;
displayElement.UseAutoSizeWidth = false;
displayElement.UseAutoSizeHeight = false;
displayElement.BgHeight = 55;
displayElement.BgWidth = 260;
displayElement.BackgroundTranslucency = 0.5;
displayElement.UseBackgroundTexture = false;
displayElement.UseBackgroundBorder = true;
displayElement.BackgroundBorderColor = Color.White;


Configure 3D model articulations

[C#] Copy Code
// IAgVOModel model: VO Model from an STK Object

// Configure articulation
IAgVOModelArtic modelArticulation = model.Articulation;
modelArticulation.EnableDefaultSave = false;
modelArticulation.SaveArticFileOnSave = true;

// Set our articulation and transformations
// For this sample, these articulations exist for a default satellite model
int levelOfDetail = 0;
string articulation = "Satellite";
string transformation = "Size";


// Get the current transition value
double currentTransVal = modelArticulation.GetTransValue(levelOfDetail, articulation, transformation);

// Change the value
double newTransVal = currentTransVal * 0.50;

// Set our new transition value
modelArticulation.SetTransValue(levelOfDetail, articulation, transformation, newTransVal);


Configure 3D model file

[C#] Copy Code
// IAgVOModel model: VO model

// Set new ModelFile.Filename
model.ModelType = AgEModelType.eModelFile;
IAgVOModelFile modelFile = model.ModelData as IAgVOModelFile;
modelFile.Filename = @"\STKData\VO\Models\Space\alexis.mdl";

// Configure basic settings
model.Visible = true;
model.ScaleValue = 4.800;


Configure 3D model level of detail

[C#] Copy Code
// IAgVOModel model: VO Model from an STK Object

// Configure level of details
IAgVODetailThreshold detail = model.DetailThreshold;
detail.EnableDetailThreshold = true;

// (assuming unit preferences set to km)
detail.All = 2.51189;
detail.ModelLabel = 158489;
detail.MarkerLabel = 2.51189e+006;
detail.Marker = 2.511e+007;
detail.Point = 1e+012;


Configure 3D vector

[C#] Copy Code
// IAgVOVector vector: VO Vector

// See AvailableCrdns for supported elements
vector.RefCrdns.Add(AgEGeometricElemType.eVectorElem, ((IAgCrdn)m_Root.CentralBodies["Earth"].Vgt.Vectors["Moon"]).QualifiedPath);
vector.RefCrdns.Add(AgEGeometricElemType.eAxesElem, ((IAgCrdn)m_Root.CentralBodies["Moon"].Vgt.Vectors["Position"]).QualifiedPath);
vector.RefCrdns.Add(AgEGeometricElemType.eVectorElem, ((IAgCrdn)m_Root.CentralBodies["Sun"].Vgt.Vectors["Velocity(Barycenter)"]).QualifiedPath);

// Draw on Central Body
IAgVORefCrdnVector body = vector.RefCrdns.GetCrdnByName(AgEGeometricElemType.eAxesElem, ((IAgCrdn)m_Root.CentralBodies["Earth"].Vgt.Vectors["Moon"]).QualifiedPath) as IAgVORefCrdnVector;
((IAgVORefCrdn)body).Color = Color.Yellow;
body.DrawAtCB = true;
body.Axes = "CentralBody/Earth Fixed Axes";
body.ArrowType = AgEArrowType.e3D;

vector.ScaleRelativeToModel = true;
vector.AngleSizeScale = 4.5;
vector.ArrowPtSize = 11.0;


List all 3D model articulations

[C#] Copy Code
// IAgSatellite satellite: Satellite object
// IAgVOModel model: VO Model from an STK Object

// Enumerating through the transformation collection is helpful if you do not
// know what tranformations exist or their value ranges

IAgVOModelArtic modelArticulation = model.Articulation;

for (int lod = 0; lod < modelArticulation.LODCount; lod++)
{
    // Get all articulations
    // GetAvailableArticulations returns a one dimensional array of articulation names
    Array articulations = modelArticulation.GetAvailableArticulations(lod);

    // Enumerate through available articulations
    for (int articulation = 0; articulation < articulations.Length; articulation++)
    {
        // We need the articulation string to call the GetAvailableTransformations function
        String articulationString = articulations.GetValue(articulation) as String;

        // Get all transformations
        IAgVOModelTransCollection transformations = modelArticulation.GetAvailableTransformations(lod, articulationString);

        // Enumerate through available transformations
        foreach (IAgVOModelTrans trans in transformations)
        {
            Console.WriteLine("Name: {0}, Current {1}, Max {2}, Min {3}", trans.Name, trans.Value, trans.Max, trans.Min);
        }
    }
}


Sets the interval of the object coverage to the sunlight times of an object

[C#] Copy Code
// IAgStkObjectRoot root: STK Object Root

// For this example, set the access times to use the light intervals of the area target.
IAgStkObject uavAircraft = root.GetObjectFromPath("Aircraft/UAV/Sensor/UAV_Camera");
IAgStkObject airspaceAreaTarget = root.GetObjectFromPath("AreaTarget/Airspace");

IAgCrdnEvent firstSunlightEpoch = airspaceAreaTarget.Vgt.Events["LightingIntervals.Sunlight.First.Start"];
IAgCrdnEvent lastSunlightEpoch = airspaceAreaTarget.Vgt.Events["LightingIntervals.Sunlight.First.Stop"];

uavAircraft.ObjectCoverage.UseObjectTimes = false;
IAgCrdnEventSmartEpoch startEpoch = uavAircraft.ObjectCoverage.AccessInterval.GetStartEpoch();
startEpoch.SetImplicitTime(firstSunlightEpoch);

IAgCrdnEventSmartEpoch stopEpoch = uavAircraft.ObjectCoverage.AccessInterval.GetStopEpoch();
stopEpoch.SetImplicitTime(lastSunlightEpoch);

uavAircraft.ObjectCoverage.AccessInterval.SetStartAndStopEpochs(startEpoch, stopEpoch);


Compute a link budget for a Transmtiter and Receiver pair, using complex models

[C#] Copy Code
// IAgTransmitter geoTransmitter: Transmitter object
// IAgReceiver facilityReceiver: Receiver object
// IAgAntenna facilityDish: Antenna object
// IAgRFEnvironment scenarioRFEnv: Scenario RF Environment

IAgStkObject xmtrAsStkObject = geoTransmitter as IAgStkObject;
IAgStkObject rcvrAsStkObject = facilityReceiver as IAgStkObject;

//Enable the rain loss computation on the scenario RF environment
scenarioRFEnv.PropagationChannel.EnableRainLoss = true;

//Set the transmitter to the complex model
geoTransmitter.SetModel("Complex Transmitter Model");
IAgTransmitterModelComplex complexTrans = geoTransmitter.Model as IAgTransmitterModelComplex;

//Set the complex transmitter model's frequency to 3.2 GHz
complexTrans.Frequency = 3.2;

//Set the complex transmitter model's Power to 50 dBW
complexTrans.Power = 50.0;

//Set the complex transmitter's embedded antenna model to helix
complexTrans.AntennaControl.SetEmbeddedModel("Helix");

//Set the beamwidth of the parablic antenna to 2 degrees
IAgAntennaModelHelix helix = complexTrans.AntennaControl.EmbeddedModel as IAgAntennaModelHelix;
helix.NumberOfTurns = 30.0;

//Orient the complex transmitter embedded antenna's boresight to point directly at the receiver's location
complexTrans.AntennaControl.EmbeddedModelOrientation.AssignAzEl(287.283.4, AgEAzElAboutBoresight.eAzElAboutBoresightRotate);

//Set the receiver to the complex model
facilityReceiver.SetModel("Complex Receiver Model");
IAgReceiverModelComplex complexRcvr = facilityReceiver.Model as IAgReceiverModelComplex;

//Configure the complex receiver to use the antenna object on the same parent facility, by linking
complexRcvr.AntennaControl.ReferenceType = AgEAntennaControlRefType.eAntennaControlRefTypeLink;
complexRcvr.AntennaControl.LinkedAntennaObject = "Antenna/FacilityDish";

//Enable rain loss computation on the receiver
complexRcvr.UseRain = true;
complexRcvr.RainOutagePercent = 0.001;

//Enable the receiver system noise temperature computation.
complexRcvr.SystemNoiseTemperature.ComputeType = AgENoiseTempComputeType.eNoiseTempComputeTypeCalculate;

//Enable the antenna noise temperature computation
complexRcvr.SystemNoiseTemperature.AntennaNoiseTemperature.ComputeType = AgENoiseTempComputeType.eNoiseTempComputeTypeCalculate;
complexRcvr.SystemNoiseTemperature.AntennaNoiseTemperature.UseRain = true;

//Orient the antenna object's boresight to point directly at the transmitter's location
facilityDish.Orientation.AssignAzEl(202.641.2, AgEAzElAboutBoresight.eAzElAboutBoresightRotate);

//Set the antenna object's model to parabolic
facilityDish.SetModel("Parabolic");

//Set the antenan object's design frequency to match the transmitter's 3.2 GHz
facilityDish.Model.DesignFrequency = 3.2;

//Set the antenna object's parabolic model diameter to 5 m.
IAgAntennaModelParabolic parabolic = facilityDish.Model as IAgAntennaModelParabolic;
parabolic.InputType = AgEAntennaModelInputType.eAntennaModelInputTypeDiameter;
parabolic.Diameter = 5.0;

//Create an access object for the access between the transmitter and recevier objects
IAgStkAccess linkAccess = xmtrAsStkObject.GetAccessToObject(rcvrAsStkObject);

//Compute access
linkAccess.ComputeAccess();

// Get the access intervals
IAgIntervalCollection accessIntervals = linkAccess.ComputedAccessIntervalTimes;

// Extract the access intervals and the range information for each access interval
Array dataPrvElements = new object[] { "Time""Xmtr Gain""Rcvr Gain""Eb/No""BER" };

IAgDataPrvTimeVar dp = linkAccess.DataProviders["Link Information"as IAgDataPrvTimeVar;

for (int index0 = 0; index0 < accessIntervals.Count; ++index0)
{
    object startTime = null, stopTime = null;

    accessIntervals.GetInterval(index0, out startTime, out stopTime);

    IAgDrResult result = dp.ExecElements(startTime, stopTime, 60ref dataPrvElements);

    Array timeValues = result.DataSets[0].GetValues();
    Array xmtrGain = result.DataSets[1].GetValues();
    Array rcvrGain = result.DataSets[2].GetValues();
    Array ebno = result.DataSets[3].GetValues();
    Array ber = result.DataSets[4].GetValues();

    for (int index1 = 0; index1 < timeValues.GetLength(0); ++index1)
    {
        string time = (string)timeValues.GetValue(index1);
        double xmtrGainVal = (double)xmtrGain.GetValue(index1);
        double rcvrGainVal = (double)rcvrGain.GetValue(index1);
        double ebnoVal = (double)ebno.GetValue(index1);
        double berVal = (double)ber.GetValue(index1);
        Console.WriteLine("{0}: Xmtr Gain = {1} Rcvr Gain = {2} Eb/No={3} BER={4}", time, xmtrGainVal, rcvrGainVal, ebnoVal, berVal);
    }

    Console.WriteLine();
}



Compute a link budget for a Transmtiter and Receiver pair, using simple models

[C#] Copy Code
// IAgTransmitter geoTransmitter: Transmitter object
// IAgReceiver facilityReceiver: Receiver object

IAgStkObject xmtrAsStkObject = geoTransmitter as IAgStkObject;
IAgStkObject rcvrAsStkObject = facilityReceiver as IAgStkObject;

//Set the transmitter to the simple model
geoTransmitter.SetModel("Simple Transmitter Model");
IAgTransmitterModelSimple simpleTrans = geoTransmitter.Model as IAgTransmitterModelSimple;

//Set the simple transmitter model's frequency to 3.2 GHz
simpleTrans.Frequency = 3.2;

//Set the simple transmitter model's EIRP to 60 dBW
simpleTrans.Eirp = 60.0;

//Set the receiver to the simple model
facilityReceiver.SetModel("Simple Receiver Model");
IAgReceiverModelSimple simpleRcvr = facilityReceiver.Model as IAgReceiverModelSimple;

//Set the simple receiver model's G/T to 60 dB/K
simpleRcvr.GOverT = 60.0;

//Create an access object for the access between the transmitter and recevier objects
IAgStkAccess linkAccess = xmtrAsStkObject.GetAccessToObject(rcvrAsStkObject);

//Compute access
linkAccess.ComputeAccess();

// Get the access intervals
IAgIntervalCollection accessIntervals = linkAccess.ComputedAccessIntervalTimes;

// Extract the access intervals and the range information for each access interval
Array dataPrvElements = new object[] { "Time""Eb/No""BER" };

IAgDataPrvTimeVar dp = linkAccess.DataProviders["Link Information"as IAgDataPrvTimeVar;

for (int index0 = 0; index0 < accessIntervals.Count; ++index0)
{
    object startTime = null, stopTime = null;
    accessIntervals.GetInterval(index0, out startTime, out stopTime);

    IAgDrResult result = dp.ExecElements(startTime, stopTime, 60ref dataPrvElements);

    Array timeValues = result.DataSets[0].GetValues();
    Array ebno = result.DataSets[1].GetValues();
    Array ber = result.DataSets[2].GetValues();

    for (int index1 = 0; index1 < timeValues.GetLength(0); ++index1)
    {
        string time = (string)timeValues.GetValue(index1);
        double ebnoVal = (double)ebno.GetValue(index1);
        double berVal = (double)ber.GetValue(index1);
        Console.WriteLine("{0}: Eb/No={1} BER={2}", time, ebnoVal, berVal);
    }

    Console.WriteLine();
}



Add a STK Object to constellation using IAgStkObject interface

[C#] Copy Code
// IAgConstellation constellation: Constellation object
// IAgStkObject alos: Satellite Object that is to be added to constellation

// Add object to constellation
constellation.Objects.AddObject(alos);


Add a STK Object to constellation using STK Object Path

[C#] Copy Code
// IAgConstellation constellation: Constellation object

// Add object to constellation
constellation.Objects.Add("Satellite/Cameo");


Compute a coverage definition access

[C#] Copy Code
// IAgCoverageDefinition coverageDefinition: Coverage Definition

// Set AutoRecomputer for Accesses
coverageDefinition.Advanced.AutoRecompute = false;

// Compute
coverageDefinition.ComputeAccesses();

// Export to File
coverageDefinition.ExportAccessesAsText("MyAccess.txt");
coverageDefinition.ReloadAccesses();

// Clear accesses if necessary
//coverageDefinition.ClearAccesses();


Create a coverage definition (on the current scenario central body)

[C#] Copy Code
// IAgStkObjectRoot root: STK Object Model Root

// Create the CoverageDefinition
IAgCoverageDefinition cd = root.CurrentScenario.Children.New(AgESTKObjectType.eCoverageDefinition, "cd1"as IAgCoverageDefinition;


Define a coverage definition assets

[C#] Copy Code
// IAgCoverageDefinition coverageDefinition: Coverage definition object

IAgCvAssetListCollection assetCollection = coverageDefinition.AssetList;
string assetName = "Satellite/sat1";
string subAssetName = "Facility/North";

// Remove asset collection if necessary
assetCollection.RemoveAll();

IAgCvAssetListElement satAsset1 = null;

// AvailableAssets returns a one dimensional array of assets
if (Array.IndexOf(assetCollection.AvailableAssets, assetName) != -1)
{
    // Add assets to coverageDefintion
    if (assetCollection.CanAssignAsset(assetName))
    {
        satAsset1 = assetCollection.Add(assetName);

        // Configure asset element
        satAsset1.Required = true;
        satAsset1.Grouping = AgECvAssetGrouping.eGrouped;
    }

    // Add subassets to assets
    if (satAsset1.ContainsSubAssets())
    {
        IAgCvAssetListCollection subAssetCollection = satAsset1.SubAssetList;
        if (subAssetCollection.CanAssignAsset(subAssetName))
        {
            assetCollection.Add(subAssetName);
        }
    }
}


Define a coverage definition by points

[C#] Copy Code
// IAgCoverageDefinition coverageDefinition: Coverage Definition
// String regionFilePath: Path of region file

// Get the IAgCvGrid interface
IAgCvGrid cvGrid = coverageDefinition.Grid;

// Define custom region
cvGrid.BoundsType = AgECvBounds.eBoundsCustomRegions;
IAgCvBoundsCustomRegions oBoundsCustom = cvGrid.Bounds as IAgCvBoundsCustomRegions;
oBoundsCustom.RegionFiles.Add(regionFilePath);
oBoundsCustom.AreaTargets.Add("AreaTarget/AreaTarget1");

// Create an Array of LLA points
// Array should contain Lat, Lon, Alt values
Array points = new object[,]
{
    { 6.9346423789e+01, -5.0260748372e+010.0000000000e+00 },
    { 3.9613371741e+01, -6.6285429903e+010.0000000000e+00 },
    { 3.9880319688e+01, -7.3881767479e+010.0000000000e+00 },
    { 4.0700636942e+01, -1.1224999998e+020.0000000000e+00 }
};

// SetPointsLLA expects a two dimensional array of LLA points
coverageDefinition.PointDefinition.SetPointsLLA(ref points);


Define a custom grid using area targets

[C#] Copy Code
// IAgCoverageDefinition coverageDefinition: Coverage Definition

// Get the IAgCvGrid interface
IAgCvGrid cvGrid = coverageDefinition.Grid;

// Set bound region type to use custom regions
cvGrid.BoundsType = AgECvBounds.eBoundsCustomRegions;

// Get IAgCvBoundsCustomRegions interface
IAgCvBoundsCustomRegions boundRegion = cvGrid.Bounds as IAgCvBoundsCustomRegions;

// Add custom regions
boundRegion.AreaTargets.Add("AreaTarget/AreaTarget1");
boundRegion.AreaTargets.Add("AreaTarget/AreaTarget2");


Define a grid resolution by latitude and longitude

[C#] Copy Code
// IAgCoverageDefinition coverageDefinition: Coverage definition object

// Get the IAgCvGrid interface
IAgCvGrid grid = coverageDefinition.Grid;

// Set resolution type
grid.ResolutionType = AgECvResolution.eResolutionLatLon;

// Get the resolution interface
IAgCvResolution resolution = grid.Resolution;
IAgCvResolutionLatLon latLonResolution = resolution as IAgCvResolutionLatLon;

// Assign LatLon used to define grid resolution
// Uses Angle Dimension
latLonResolution.LatLon = 3.0;


Define and configure grid constraint options

[C#] Copy Code
// IAgCoverageDefinition coverageDefinition: Coverage definition object

IAgCvPointDefinition pointDefinition = coverageDefinition.PointDefinition;

// Set facility as object seed instance
pointDefinition.GridClass = AgECvGridClass.eGridClassFacility;
pointDefinition.UseGridSeed = true;
pointDefinition.SeedInstance = "Facility/North";

// Configure Altitude
pointDefinition.AltitudeMethod = AgECvAltitudeMethod.eAltitude;
pointDefinition.Altitude = 0.0;
coverageDefinition.PointDefinition.GroundAltitudeMethod = AgECvGroundAltitudeMethod.eCvGroundAltitudeMethodUsePointAlt;


Set the coverage analysis time to the asset object time periods.

[C#] Copy Code
// IAgStkObjectRoot stkRoot: STK Object Root
// IAgCoverageDefinition coverage: An instance of the coverage definition object

string currentDateFormat = stkRoot.UnitPreferences.GetCurrentUnitAbbrv("DateFormat");

// For this example, we will set the coverage analysis time to the times the asset is available.
// Note, this doesn't handle subassets. To do that, you'll just have to iterate through the subasset list.
IAgDate minStartTime = null;
IAgDate maxStartTime = null;

foreach (IAgCvAssetListElement cvAsset in coverage.AssetList)
{
    IAgStkObject subAsset = stkRoot.GetObjectFromPath(cvAsset.ObjectName);
    if (subAsset.Vgt.EventIntervals.Contains("AvailabilityTimeSpan"))
    {
        IAgCrdnEventIntervalResult availableTimeSpan = subAsset.Vgt.EventIntervals["AvailabilityTimeSpan"].FindInterval();
        IAgDate startDate = stkRoot.ConversionUtility.NewDate(currentDateFormat, availableTimeSpan.Interval.Start.ToString());
        if (!(minStartTime != null) || startDate.OLEDate < minStartTime.OLEDate)
        {
            minStartTime = startDate;
        }

        IAgDate stopTime = stkRoot.ConversionUtility.NewDate(currentDateFormat, availableTimeSpan.Interval.Stop.ToString());
        if (!(maxStartTime != null) || stopTime.OLEDate > maxStartTime.OLEDate)
        {
            maxStartTime = stopTime;
        }
    }
}

if (minStartTime != null && maxStartTime != null)
{
    // Now, that we have the minimum start time and the maximum stop time of the asset list, we can explicitly set the coverage analysis time.
    coverage.Interval.AnalysisInterval.SetExplicitInterval(minStartTime.Format(currentDateFormat), maxStartTime.Format(currentDateFormat));
}

Console.WriteLine(
    "Coverage Analysis Interval, StartTime = {0}, StopTime = {1}",
    coverage.Interval.AnalysisInterval.FindStartTime(),
    coverage.Interval.AnalysisInterval.FindStopTime());


Configure a coverage definition adaptive sampling

[C#] Copy Code
// IAgCoverageDefinition coverageDefinition: Coverage definition object

// Get the Sampling interface
IAgCvAdvanced advanced = coverageDefinition.Advanced;
IAgAccessSampling sampling = advanced.Sampling;

// Set the Sampling Method
sampling.SetType(AgESamplingMethod.eSamplingMethodAdaptive);
IAgSamplingMethodAdaptive adaptive = sampling.Strategy as IAgSamplingMethodAdaptive;

// Set properties on the Adaptive sampling method interface
adaptive.MaxTimeStep = 180.0;
adaptive.MinTimeStep = 1.0;


Configure a coverage definition fixed step sampling

[C#] Copy Code
// IAgCoverageDefinition coverageDefinition: Coverage definition object

// Get the Sampling interface
IAgCvAdvanced advanced = coverageDefinition.Advanced;
IAgAccessSampling sampling = advanced.Sampling;

// Set the Sampling Method
sampling.SetType(AgESamplingMethod.eSamplingMethodFixedStep);
IAgSamplingMethodFixedStep fixedStep = sampling.Strategy as IAgSamplingMethodFixedStep;

// Set properties on the Fixed Stop sampling method interface
fixedStep.FixedTimeStep = 360.0;
fixedStep.TimeBound = 5.0;


Configure a coverage definition graphics

[C#] Copy Code
// IAgCvGraphics cvGraphics: Coverage definition

// Configure animation
IAgCvGfxAnimation cvAnimation = cvGraphics.Animation;
cvAnimation.IsSatisfactionVisible = true;
cvAnimation.Color = Color.Green;

// Configure progress
IAgCvGfxProgress cvProgress = cvGraphics.Progress;
cvProgress.IsVisible = true;
cvProgress.Color = Color.Red;

// Configure static
IAgCvGfxStatic cvStatic = cvGraphics.Static;
cvStatic.Color = Color.Blue;
cvStatic.MarkerStyle = "Star";


Create a facility (on current scenario central body)

[C#] Copy Code
// IAgStkObjectRoot root: STK Object Model root

// Create a facility on current scenario central body
IAgFacility facility = root.CurrentScenario.Children.New(AgESTKObjectType.eFacility, "MyFacility"as IAgFacility;


Create a facility from facility database

[C#] Copy Code
// IAgStkObjectRoot root: STK Object Model root

// Get STK database location using Connect
IAgExecCmdResult result = root.ExecuteCommand("GetDirectory / Database Facility");
string facDataDir = result[0];
string filelocation = Path.Combine(facDataDir, @"stkFacility.fd");

// Import object from database using Connect
string command = "ImportFromDB * Facility \"" + filelocation + "\" Class Facility SiteName Weilheim";
root.ExecuteCommand(command);

IAgFacility facility = root.GetObjectFromPath("Facility/Weilheim"as IAgFacility;


Create a facility on Earth at lat/lon/alt

[C#] Copy Code
// IAgStkObjectRoot root: STK Object Model root

IAgFacility facility = root.CurrentScenario.Children.NewOnCentralBody(AgESTKObjectType.eFacility, "MyFacility""Earth"as IAgFacility;

// Assuming unit preferences are set to radians for latitude and longitude and km for distance
facility.Position.AssignPlanetodetic(0.4506, -1.40114);


Create a facility on specified central body at lat/lon/alt

[C#] Copy Code
// IAgStkObjectRoot root: STK Object Model root

IAgFacility facObject = root.CurrentScenario.Children.NewOnCentralBody(AgESTKObjectType.eFacility, "Facility1""Mars"as IAgFacility;

// Assuming unit preferences are set to radians for latitude and longitude and km for distance
facObject.Position.AssignPlanetodetic(-5.42450.19020);


Move a facility while use terrain option is set true

[C#] Copy Code
// IAgFacility fac: Facility object

// Set altitude automatically by using terrain data
fac.UseTerrain = true;

// Set the position ignores the altitude value in AssignGeodetic
fac.Position.AssignGeodetic(29.98, -90.259);

// Ignores the altitude value in AssignGeocentric
fac.Position.AssignGeocentric(32.12, -110.93787);

// Ignores the radius value in AssignSpherical
fac.Position.AssignSpherical(40.65, -73.787);


Configure access duration figure of merit

[C#] Copy Code
// IAgFigureOfMerit fom: Figure of Merit properties

// Set figure of merit defintion to eFmAccessDuration
fom.SetDefinitionType(AgEFmDefinitionType.eFmAccessDuration);

// Get IAgFmDefCompute interface
IAgFmDefCompute defComp = fom.Definition as IAgFmDefCompute;

if (defComp.IsComputeTypeSupported(AgEFmCompute.ePercentAbove))
{
    // Set Compute type to supported compute option
    defComp.SetComputeType(AgEFmCompute.ePercentAbove);

    // Get compute option compute interface
    IAgFmDefDataPercentLevel fomData = defComp.Compute as IAgFmDefDataPercentLevel;
    fomData.PercentLevel = .25;
}


Configure coverage time figure of merit

[C#] Copy Code
// IAgFigureOfMerit fom: Figure of Merit properties

// Set figure of merit defintion to eFmCoverageTime
fom.SetDefinitionType(AgEFmDefinitionType.eFmCoverageTime);

// Get IAgFmDefCompute interface
IAgFmDefCompute defComp = fom.Definition as IAgFmDefCompute;

if (defComp.IsComputeTypeSupported(AgEFmCompute.eTotalTimeAbove))
{
    // Set Compute type to supported compute option
    defComp.SetComputeType(AgEFmCompute.eTotalTimeAbove);

    // Get compute option compute interface
    IAgFmDefDataMinAssets fomData = defComp.Compute as IAgFmDefDataMinAssets;
    fomData.MinAssets = 15;
}


Configure figure of merit Age Of Data definition

[C#] Copy Code
// IAgFigureOfMerit fom: Figure of Merit properties

// Get the IAgFmDefAgeOfData interface
fom.SetDefinitionType(AgEFmDefinitionType.eFmAgeOfData);
IAgFmDefAgeOfData ageOfData = fom.Definition as IAgFmDefAgeOfData;

// Set the minimum number of assets for computing
ageOfData.MinAssets = 2;


Configure figure of merit contours

[C#] Copy Code
// IAgFmGfxContours contours: Figure of Merit properties

contours.IsVisible = true;
contours.ContourType = AgEFmGfxContourType.eSmoothFill;
contours.ColorMethod = AgEFmGfxColorMethod.eExplicit;

// Add level ranges (batch)
contours.LevelAttributes.AddLevelRange(25351);
IAgFmGfxLevelAttributesElement firstLevel = contours.LevelAttributes[0];
firstLevel.Color = Color.Blue;

// Add one level (individually)
IAgFmGfxLevelAttributesElement level = contours.LevelAttributes.AddLevel(55);
level.Color = Color.Red;


Configure figure of merit definition altitude access constraint

[C#] Copy Code
// IAgFigureOfMerit fom: Figure of Merit properties

// Set access constraint defintion to altitude
fom.SetAccessConstraintDefinition(AgEFmConstraintName.eFmAltitude);

// Get IAgFmDefAccessConstraint interface
IAgFmDefAccessConstraint defAccessCnstr = fom.Definition as IAgFmDefAccessConstraint;

// Confiure access constraint properties
defAccessCnstr.SetComputeType(AgEFmCompute.eMaximum);
defAccessCnstr.AcrossAssets = AgEFmAcrossAssets.eFmMinimum;
defAccessCnstr.TimeStep = 60.0;


Configure figure of merit Scalar Calculation definition

[C#] Copy Code
// IAgFigureOfMerit fom: Figure of Merit properties

// Set the Scalar Calculation definition.
IAgFmDefScalarCalculation scalarCalculation = fom.SetScalarCalculationDefinition("CentralBody/Earth ElapsedTimeFromStart");


Configure figure of merit Scalar Calculation definition using VGT

[C#] Copy Code
// IAgFigureOfMerit fom: Figure of Merit properties
// IAgStkObjectRoot stkRoot: STK Object Model root

// Get the qualified path of a Scalar Calculation (e.g.
IAgCrdnProvider provider = stkRoot.VgtRoot.GetProvider("CentralBody/Sun");
IAgCrdnCalcScalar calcScalar = provider.CalcScalars[0];
string calcScalarQualifiedPath = (calcScalar as IAgCrdn).QualifiedPath;

// Set the Scalar Calculation definition using the qualified path
IAgFmDefScalarCalculation scalarCalculation = fom.SetScalarCalculationDefinition(calcScalarQualifiedPath);


Configure figure of merit System Response Time

[C#] Copy Code
// IAgFigureOfMerit fom: Figure of Merit properties

fom.SetDefinitionType(AgEFmDefinitionType.eFmSystemResponseTime);
IAgFmDefSystemResponseTime systemResponseTime = fom.Definition as IAgFmDefSystemResponseTime;

systemResponseTime.CommandStationPath = @"/Application/STK/Scenario/CodeSnippetScenario/Facility/Facility1";


Configure figure of merit System Response Time reset

[C#] Copy Code
// IAgFigureOfMerit fom: Figure of Merit properties

fom.SetDefinitionType(AgEFmDefinitionType.eFmSystemResponseTime);
IAgFmDefSystemResponseTime systemResponseTime = fom.Definition as IAgFmDefSystemResponseTime;

systemResponseTime.CommandStationPath = "NONE";


Create a figure of merit on a coverage definition

[C#] Copy Code
// IAgCoverageDefinition covdef: Coverage Definition object

// Get the coverage definition as a IAgStkObject interface
IAgStkObject covdefObject = covdef as IAgStkObject;

// Create the figure of merit
IAgFigureOfMerit fom = covdefObject.Children.New(AgESTKObjectType.eFigureOfMerit, "MyFigureOfMerit"as IAgFigureOfMerit;


Inspect grid by selecting a point

[C#] Copy Code
// IAgFigureOfMerit fom: Figure of Merit properties

IAgFmGridInspector gridInspector = fom.GridInspector;
gridInspector.SelectPoint(-13.864, -51.088);

IAgDataPrvTimeVar pointFom = gridInspector.PointFOM as IAgDataPrvTimeVar;
IAgDrResult pointFomResult = pointFom.ExecSingle("1 Jan 2012 12:00:00.00");

IAgDataPrvInterval pointSatisfaction = gridInspector.PointSatisfaction as IAgDataPrvInterval;
IAgDrResult pointSatisfactionResult = pointSatisfaction.Exec("1 Jan 2012 12:00:00.00""2 Jan 2012 12:00:00.00");

IAgDataPrvTimeVar regionFom = gridInspector.RegionFOM as IAgDataPrvTimeVar;
IAgDrResult regionFomResult = regionFom.ExecSingle("1 Jan 2012 12:00:00.00");

IAgDataPrvInterval regionSatisfaction = gridInspector.RegionSatisfaction as IAgDataPrvInterval;
IAgDrResult regionSatisfactionResult = regionSatisfaction.Exec("1 Jan 2012 12:00:00.00""2 Jan 2012 12:00:00.00");


Set the figure of merit definition to access constraint by enumeration

[C#] Copy Code
// IAgFigureOfMerit fom: Figure of Merit properties

IAgFmDefAccessConstraint acd = fom.SetAccessConstraintDefinition(AgEFmConstraintName.eFmAzimuthRate);


Set the figure of merit definition to access constraint by name

[C#] Copy Code
// IAgFigureOfMerit fom: Figure of Merit properties

IAgFmDefAccessConstraint defAccessCnstr = fom.SetAccessConstraintDefinitionName("AzimuthRate");

// Confiure access constraint properties
defAccessCnstr.SetComputeType(AgEFmCompute.eMaximum);
defAccessCnstr.AcrossAssets = AgEFmAcrossAssets.eFmMinimum;
defAccessCnstr.TimeStep = 60.0;


Add MTO track

[C#] Copy Code
// IAgMto mto: MTO object

IAgMtoTrackCollection trackCollection = mto.Tracks;

Array time = new object[]
             {
                 "1 Jan 2012 12:10:00.000""1 Jan 2012 12:20:00.000"
             };
Array latitude = new object[]
                 {
                     27.97, -26.51
                 };
Array longitude = new object[]
                  {
                      -80.01119.42
                  };
Array altitude = new object[]
                 {
                     20.144.2
                 };

// AddTrack expects each safe array parameter to be two dimensional,
// all arrays must have the same length
IAgMtoTrack track = trackCollection.AddTrack(1ref time, ref latitude, ref longitude, ref altitude);


Configure MTO

[C#] Copy Code
// IAgStkObjectRoot root: STK Object Model root
// IAgMto mto: Mto Object

IAgScenario scenario = root.CurrentScenario as IAgScenario;
scenario.SetTimePeriod("1 Feb 2008 12:00:00.000""2 Feb 2008 12:00:00.000");

// Number of tracks and points to add
double trackCount = 10;
double pointCount = 20;

// Initial values from which we will interpolate
double lat0 = 40.04;
double lon0 = -75.595;
double alt0 = 0;

root.BeginUpdate(); // Call BeginUpdate for STK engine to delay updates

for (int i = 0; i < trackCount; ++i)
{
    IAgMtoTrack track = mto.Tracks.Add(i);
    IAgDate date = root.ConversionUtility.NewDate("UTCG", scenario.StartTime as string);

    // Interpolate mto points
    for (int j = 0; j < pointCount; ++j)
    {
        double lat = lat0 + 1 * i;
        double lon = lon0 + 0.1 * j;
        double alt = alt0;

        date = date.Add("sec"120);

        track.Points.AddPoint(date.Format("UTCG"), lat, lon, alt);
    }
}

root.EndUpdate();


Create a MTO (on current scenario central body)

[C#] Copy Code
// IAgStkObjectRoot root: STK Object Model root

// Create the MTO
IAgMto mto = root.CurrentScenario.Children.New(AgESTKObjectType.eMTO,  "mto1"as IAgMto;


Extend MTO track

[C#] Copy Code
// IAgMtoTrackPointCollection trackPointCollection: Track point collection

Array time = new object[]
             {
                 "1 Jan 2012 12:20:00.000""1 Jan 2012 12:30:00.000"
             };
Array latitude = new object[]
                 {
                     -18.3519.55
                 };
Array longitude = new object[]
                  {
                      -42.1083.21
                  };
Array altitude = new object[]
                 {
                     30.5215.81
                 };

// Extend expects each parameter to be a two dimensional array,
// all arrays must have the same length
trackPointCollection.Extend(ref time, ref latitude, ref longitude, ref altitude);


Load MTO track points from file

[C#] Copy Code
// IAgMtoTrack track: MTO track object
// String filePath: Path of ephemeris file

// LoadPoints expects the path an Ephemeris file path
track.Points.LoadPoints(filePath);


Remove MTO track

[C#] Copy Code
// IAgMto mto: MTO object

IAgMtoTrackCollection trackCollection = mto.Tracks;

// Build tracksToRemove Array
Array tracksToRemove = new object[]
                       {
                           trackCollection[0], trackCollection[1]
                       };

// RemoveTracks expects a one dimensional array of IAgMtoTrack objects
trackCollection.RemoveTracks(ref tracksToRemove);


Remove MTO tracks by ids

[C#] Copy Code
// IAgMto mto: MTO object

IAgMtoTrackCollection trackCollection = mto.Tracks;

// RemoveTracksById expects a one dimensional array of mto track ids
Array tracks = new object[]
               {
                   14
               };
trackCollection.RemoveTracksById(ref tracks);


Compute MTO field of view

[C#] Copy Code
// IAgMto mto: MTO object

IAgMtoAnalysisFieldOfView fov = mto.Analysis.FieldOfView;
fov.Sensor = "Satellite/J2Satellite/Sensor/Sensor1";

// AreTracksInFOV expects a one dimensional array of mto track ids
Array tracks = new object[]
               {
                   14
               };

bool tracksInView = fov.AreTracksInFOV(AgEMtoTrackEval.eMtoTrackEvalAny, ref tracks, "1 Jan 2012 12:00:00.000");


Compute MTO ranges

[C#] Copy Code
// IAgMto mto: MTO object

IAgMtoAnalysisRange range = mto.Analysis.Range;
range.StkObjectPath = "Satellite/J2Satellite";

// ComputeRanges expects a one dimensional array of mto track ids
// ComputeRanges returns a two dimensional array of track id, visibility, and range
Array tracks = new object[]
               {
                   14
               };

Array result = range.ComputeRanges(AgEMtoRangeMode.eMtoRangeModeEach, ref tracks, "1 Jan 2012 12:00:00.000");

// Print results
for (int i = 0; i < result.GetLength(0); i++)
{
    Console.WriteLine("Track #: {0}, Visible: {1}, Range: {2}", result.GetValue(i, 0), result.GetValue(i, 1), result.GetValue(i, 2));
}


Compute visibility with MTO tracks

[C#] Copy Code
// IAgStkObjectRoot root: STK Object Model root
// IAgMto mto: MTO object to use for visibility analysis

// Are all the tracks visible from the other STK Object at the specified time?

IAgMtoAnalysisVisibility mtoVisibility = mto.Analysis.Visibility;
mtoVisibility.UseTerrain = false// Set to true to use terrain instead of line of sight.
mtoVisibility.Entirety = AgEMtoEntirety.eMtoEntiretyPartial; // Only applies if MTO is static (i.e. non time dependent).

mtoVisibility.StkObjectPath = "Satellite/J2Satellite";
bool allTracksAreVisible = mtoVisibility.AreAllTracksVisible("1 Jan 2012 14:02:00.000");


Determine if all the specified tracks (i.e. a subset of the MTO tracks) are visible from the other STK Object at the specified time?

[C#] Copy Code
// IAgStkObjectRoot root: STK Object Model root
// IAgMto mto: MTO object to use for visibility analysis

IAgMtoAnalysisVisibility mtoVisibility = mto.Analysis.Visibility;
mtoVisibility.UseTerrain = false// Set to true to use terrain instead of line of sight.
mtoVisibility.Entirety = AgEMtoEntirety.eMtoEntiretyPartial; // Only applies if MTO is static (i.e. non time dependent).

mtoVisibility.StkObjectPath = "Satellite/J2Satellite";

Array tracksOfInterest = new object[]
                         {
                             127
                         };

// AreTracksVisible expects as the second parameter a one dimensional array of mto track ids
bool areTracksAreVisible = mtoVisibility.AreTracksVisible(AgEMtoTrackEval.eMtoTrackEvalAll, ref tracksOfInterest, "1 Jan 2012 12:02:00.000");


Determine if any track is visible from other STK Object at the specified time

[C#] Copy Code
// IAgStkObjectRoot root: STK Object Model root
// IAgMto mto: MTO object to use for visibility analysis

IAgMtoAnalysisVisibility mtoVisibility = mto.Analysis.Visibility;
mtoVisibility.UseTerrain = false// Set to true to use terrain instead of line of sight.
mtoVisibility.Entirety = AgEMtoEntirety.eMtoEntiretyPartial; // Only applies if MTO is static (i.e. non time dependent).

mtoVisibility.StkObjectPath = "Satellite/J2Satellite";
bool anyTrackIsVisible = mtoVisibility.IsAnyTrackVisible("1 Jan 2012 14:02:00.000");


Determine which tracks are visible from the other STK Object at the specified time

[C#] Copy Code
// IAgMto mto: MTO object to use for visibility analysis

IAgMtoAnalysisVisibility mtoVisibility = mto.Analysis.Visibility;
mtoVisibility.UseTerrain = false// Set to true to use terrain instead of line of sight.
mtoVisibility.Entirety = AgEMtoEntirety.eMtoEntiretyPartial; // Only applies if MTO is static (i.e. non time dependent).

mtoVisibility.StkObjectPath = "Satellite/J2Satellite";

// ComputeAllTracks returns a two dimensional array whose elements are trackid and visibility
Array trackVisibilityArray = mtoVisibility.ComputeAllTracks(AgEMtoVisibilityMode.eVisibilityModeEach, "1 Jan 2012 12:00:00.000");

// Ouput results
Console.WriteLine("ComputeAllTracks:");
for (int i = 0; i < trackVisibilityArray.GetLength(0); ++i)
{
    Console.WriteLine("   Track {0} visibility: {1}",
        Convert.ToInt32(trackVisibilityArray.GetValue(i, 0)),
        Convert.ToInt32(trackVisibilityArray.GetValue(i, 1)));
}


Which tracks of the specified subset of tracks are visible from the other STK Object at the specified time?

[C#] Copy Code
// IAgStkObjectRoot root: STK Object Model root
// IAgMto mto: MTO object to use for visibility analysis

IAgMtoAnalysisVisibility mtoVisibility = mto.Analysis.Visibility;
mtoVisibility.UseTerrain = false// Set to true to use terrain instead of line of sight.
mtoVisibility.Entirety = AgEMtoEntirety.eMtoEntiretyPartial; // Only applies if MTO is static (i.e. non time dependent).

Array tracksOfInterest = new object[]
                         {
                             127
                         };

mtoVisibility.StkObjectPath = "Satellite/J2Satellite";

// ComputeTracks expects as the second parameter a one dimensional array of mto track ids
// ComputeTracks returns a two dimensional array whose values are track id and visiblity
Array trackVisibilityArray = mtoVisibility.ComputeTracks(AgEMtoVisibilityMode.eVisibilityModeEach, ref tracksOfInterest, "1 Jan 2012 12:05:00.000");

// Output results
Console.WriteLine("ComputeTracks:");
for (int i = 0; i < trackVisibilityArray.GetLength(0); ++i)
{
    Console.WriteLine("   Track {0} visibility: {1}",
        Convert.ToInt32(trackVisibilityArray.GetValue(i, 0)),
        Convert.ToInt32(trackVisibilityArray.GetValue(i, 1)));
}


Configure MTO graphics

[C#] Copy Code
// IAgMto mto: Mto object

IAgMtoVOTrackCollection tracks = mto.VO.Tracks;
foreach (IAgMtoVOTrack element in tracks)
{
    element.Marker.PixelSize = 12;
    element.Marker.OrientationMode = AgEVOMarkerOrientation.eVOMarkerOrientationAngle;
    element.Marker.XOrigin = AgEVOMarkerOriginType.eRight;
    element.Marker.YOrigin = AgEVOMarkerOriginType.eBottom;
    element.Marker.Angle = 1.23;

    element.Marker.MarkerType = AgEMarkerType.eImageFile;
    element.Marker.SetMarkerImageFile(@"STKData\VO\Markers\Fire.ppm");

    element.Model.IsVisible = true;
    element.Model.Filename = @"STKData\VO\Models\Land\ariane-lp.mdl";
    element.Model.InitialBearing = 3.0;
    element.Model.ScaleValue = 2.0;
    element.Model.ZPointsNadir = true;

    element.Label.Enable = true;
    element.Label.X = 33.5;
    element.Label.Y = 82.2;
    element.Label.Z = 100.0;
    element.Label.OffsetFrame = AgEOffsetFrameType.eOffsetFrameCartesian;
}


Configure MTO track marker

[C#] Copy Code
// IAgMtoVOTrack track: Mto VO track properties

IAgMtoVOMarker marker = track.Marker;
marker.PixelSize = 12;
marker.OrientationMode = AgEVOMarkerOrientation.eVOMarkerOrientationAngle;
marker.XOrigin = AgEVOMarkerOriginType.eRight;
marker.YOrigin = AgEVOMarkerOriginType.eBottom;
marker.Angle = 1.23;
marker.MarkerType = AgEMarkerType.eImageFile;
marker.SetMarkerImageFile(@"STKData\VO\Markers\Fire.ppm");


Configure MTO track model

[C#] Copy Code
// IAgMtoVOTrack track: Mto VO track properties

IAgMtoVOModel model = track.Model;
model.IsVisible = true;
model.Filename = @"STKData\VO\Models\Land\ariane-lp.mdl";
model.InitialBearing = 3.0;
model.ScaleValue = 2.0;
model.ZPointsNadir = true;


Create a place (on current scenario central body)

[C#] Copy Code
// IAgStkObjectRoot root: STK Object Model root

// Create a place on current scenario central body
IAgPlace place = root.CurrentScenario.Children.New(AgESTKObjectType.ePlace, "MyPlace"as IAgPlace;


Create a place from facility database

[C#] Copy Code
// IAgStkObjectRoot root: STK Object Model root

// Get STK database location using Connect
IAgExecCmdResult result = root.ExecuteCommand("GetDirectory / Database Facility");
string facDataDir = result[0];
string filelocation = Path.Combine(facDataDir, "stkFacility.fd");

// Import object from database using Connect
string command = "ImportFromDB * Facility \"" + filelocation + "\" Class Place SiteName Weilheim";
root.ExecuteCommand(command);

IAgPlace place = root.GetObjectFromPath("Place/Weilheim"as IAgPlace;


Create a place on Earth at lat/lon/alt

[C#] Copy Code
// IAgStkObjectRoot root: STK Object Model root

IAgPlace place = root.CurrentScenario.Children.NewOnCentralBody(AgESTKObjectType.ePlace, "MyPlace""Earth"as IAgPlace;

// Assuming unit preferences are set to radians for latitude and longitude and km for distance
place.Position.AssignPlanetodetic(0.4506, -1.40114);


Create a place on specified central body at lat/lon/alt

[C#] Copy Code
// IAgStkObjectRoot root: STK Object Model root

IAgPlace placeObject = root.CurrentScenario.Children.NewOnCentralBody(AgESTKObjectType.ePlace, "Place1""Mars"as IAgPlace;

// Assuming unit preferences are set to radians for latitude and longitude and km for distance
placeObject.Position.AssignPlanetodetic(-5.42450.19020);


Move a place while use terrain option is set true

[C#] Copy Code
// IAgPlace place: Place object

// Set altitude automatically by using terrain data
place.UseTerrain = true;

// Set the position ignores the altitude value in AssignGeodetic
place.Position.AssignGeodetic(29.98, -90.259);

// Ignores the altitude value in AssignGeocentric
place.Position.AssignGeocentric(32.12, -110.93787);

// Ignores the radius value in AssignSpherical
place.Position.AssignSpherical(40.65, -73.787);


Configure a planet

[C#] Copy Code
// IAgPlanet planet: Planet

planet.PositionSource = AgEPlPositionSourceType.ePosCentralBody;

// Get IAgPlPosCentralBody interface
IAgPlPosCentralBody body = planet.PositionSourceData as IAgPlPosCentralBody;

body.AutoRename = false;
body.CentralBody = "Jupiter";

// AvailableEphemSourceTypes is a one dimensional array of AgEEphemSourceType values
if (Array.IndexOf(body.AvailableEphemSourceTypes, (int)AgEEphemSourceType.eEphemAnalytic) != -1)
{
    body.EphemSource = AgEEphemSourceType.eEphemAnalytic;
}


Configure a planet position by ephemeris source file(using common tasks)

[C#] Copy Code
// IAgPlanet planet: Planet
// String planetEphemeris: Planet Ephemeris file

// Position source files traditionally have .pe extensions
planet.CommonTasks.SetPositionSourceFile(planetEphemeris);


Configure a planet graphics

[C#] Copy Code
// IAgPlGraphics graphics: Planet graphics

graphics.Inherit = false;

graphics.Color = Color.Red;
graphics.MarkerStyle = "Circle";
graphics.LineStyle = AgELineStyle.eMDashDot;
graphics.LineWidth = AgELineWidth.e4;

graphics.InertialPositionVisible = false;
graphics.SubPlanetPointVisible = false;
graphics.PositionLabelVisible = false;
graphics.SubPlanetLabelVisible = false;
graphics.OrbitVisible = true;
graphics.OrbitDisplay = AgEPlOrbitDisplayType.eOrbitDisplayTime;
IAgPlOrbitDisplayTime displayTime = graphics.OrbitDisplayData as IAgPlOrbitDisplayTime;
displayTime.Time = 10000.00;


Compute the probability of detection of a target for a monostatic search/track radar

[C#] Copy Code
// IAgRadar radar: Radar object
// IAgAircraft targetAircraft: Aircraft object
// IAgRFEnvironment scenarioRFEnv: Scenario RF Environment

IAgStkObject rdrAsStkObject = radar as IAgStkObject;
IAgStkObject tgtAsStkObject = targetAircraft as IAgStkObject;

//Enable the rain loss computation on the scenario RF environment
scenarioRFEnv.PropagationChannel.EnableRainLoss = true;

//Configure the radar object as a monostatic model.
radar.SetModel("Monostatic");
IAgRadarModelMonostatic monostaticModel = radar.Model as IAgRadarModelMonostatic;

//Orient the radar antenna in the direction of the target
radar.Model.AntennaControl.EmbeddedModelOrientation.AssignAzEl(50.936.8, AgEAzElAboutBoresight.eAzElAboutBoresightRotate);

//Set the radar antenna model to parabolic
radar.Model.AntennaControl.SetEmbeddedModel("Parabolic");
IAgAntennaModelParabolic parabolic = radar.Model.AntennaControl.EmbeddedModel as IAgAntennaModelParabolic;

//Give the parabolic antenna a 2 deg beamwidth;
parabolic.InputType = AgEAntennaModelInputType.eAntennaModelInputTypeBeamwidth;
parabolic.Beamwidth = 2.0;

//Put the monostatic radar model in Search/Track mode
monostaticModel.SetMode("Search Track");
IAgRadarModeMonostaticSearchTrack searchTrackMode = monostaticModel.Mode as IAgRadarModeMonostaticSearchTrack;

//Set the waveform type to fixed prf
searchTrackMode.SetWaveformType(AgERadarWaveformSearchTrackType.eRadarWaveformSearchTrackTypeFixedPRF);
IAgRadarWaveformMonostaticSearchTrackFixedPRF fixedPrf = searchTrackMode.Waveform as IAgRadarWaveformMonostaticSearchTrackFixedPRF;
fixedPrf.PulseDefinition.Prf = 0.002//2 kHz

//Set the pulse width to 1e-8 sec
fixedPrf.PulseDefinition.PulseWidth = 1.0e-8//sec

//Set the number of pulses
fixedPrf.PulseDefinition.NumberOfPulses = 25;

//Set the pulse integration strategy to goal SNR
fixedPrf.PulseIntegrationType = AgERadarPulseIntegrationType.eRadarPulseIntegrationTypeGoalSNR;
IAgRadarPulseIntegrationGoalSNR pulseIntGoalSNR = fixedPrf.PulseIntegration as IAgRadarPulseIntegrationGoalSNR;
pulseIntGoalSNR.SNR = 40.0//dB

//Set the transmit frequency
monostaticModel.Transmitter.FrequencySpecification = AgERadarFrequencySpec.eRadarFrequencySpecFrequency;
monostaticModel.Transmitter.Frequency = 2.1//GHz

//Set the transmit power
monostaticModel.Transmitter.Power = 50.0//dBW

//Enable rain loss computation on the receiver
monostaticModel.Receiver.UseRain = true;
monostaticModel.Receiver.RainOutagePercent = 0.001;

//Enable the receiver system noise temperature computation.
monostaticModel.Receiver.SystemNoiseTemperature.ComputeType = AgENoiseTempComputeType.eNoiseTempComputeTypeCalculate;

//Enable the antenna noise temperature computation
monostaticModel.Receiver.SystemNoiseTemperature.AntennaNoiseTemperature.ComputeType = AgENoiseTempComputeType.eNoiseTempComputeTypeCalculate;
monostaticModel.Receiver.SystemNoiseTemperature.AntennaNoiseTemperature.UseRain = true;

//Don't inherit the radar cross section settings from the scenario
targetAircraft.RadarCrossSection.Inherit = false;
IAgRadarCrossSectionModel rcs = targetAircraft.RadarCrossSection.Model as IAgRadarCrossSectionModel;

//Set the radar cross section compute strategy to constan value
rcs.FrequencyBands[0].SetComputeStrategy("Constant Value");
IAgRadarCrossSectionComputeStrategyConstantValue constValRcs =
    rcs.FrequencyBands[0].ComputeStrategy as IAgRadarCrossSectionComputeStrategyConstantValue;

//Set the constant radar cross section to 0.5 dBsm
constValRcs.ConstantValue = 0.5//dBsm

//Create an access object for the access between the radar and target
IAgStkAccess radarAccess = rdrAsStkObject.GetAccessToObject(tgtAsStkObject);

//Compute access
radarAccess.ComputeAccess();

// Get the access intervals
IAgIntervalCollection accessIntervals = radarAccess.ComputedAccessIntervalTimes;

// Extract the access intervals and the range information for each access interval
Array dataPrvElements = new object[] { "Time""S/T SNR1""S/T PDet1""S/T Integrated SNR""S/T Integrated PDet" };

IAgDataPrvTimeVar dp = radarAccess.DataProviders["Radar SearchTrack"as IAgDataPrvTimeVar;

for (int index0 = 0; index0 < accessIntervals.Count; ++index0)
{
    object startTime = null, stopTime = null;
    accessIntervals.GetInterval(index0, out startTime, out stopTime);

    IAgDrResult result = dp.ExecElements(startTime, stopTime, 60ref dataPrvElements);

    Array timeValues = result.DataSets.GetDataSetByName("Time").GetValues();
    Array snr1 = result.DataSets.GetDataSetByName("S/T SNR1").GetValues();
    Array pdet1 = result.DataSets.GetDataSetByName("S/T PDet1").GetValues();
    Array integSnr = result.DataSets.GetDataSetByName("S/T Integrated SNR").GetValues();
    Array integPdet = result.DataSets.GetDataSetByName("S/T Integrated PDet").GetValues();

    for (int index1 = 0; index1 < timeValues.GetLength(0); ++index1)
    {
        string time = (string)timeValues.GetValue(index1);
        double snr1Val = (double)snr1.GetValue(index1);
        double pdet1Val = (double)pdet1.GetValue(index1);
        double integSnrVal = (double)integSnr.GetValue(index1);
        double integPdetVal = (double)integPdet.GetValue(index1);
        Console.WriteLine("{0}: SNR1={1} PDet1={2} Integrated SNR={3} Integrated PDet={4}", time, snr1Val, pdet1Val, integSnrVal, integPdetVal);
    }

    Console.WriteLine();
}


Add analytical terrain to the scenario on Earth central body

[C#] Copy Code
// IAgStkObjectRoot root: STK Object Model root
// String terrainFile: Path of Terrain data file

// Retrieve the IAgScenario interface
IAgScenario scenario = root.CurrentScenario as IAgScenario;

IAgCentralBodyTerrainCollection terrainCollection = scenario.Terrain;
IAgTerrainCollection elementCollection = terrainCollection["Earth"].TerrainCollection;

// Add terrain data file to current scenario's terrain collection
// Terrain data files traditionally have .dte extensions
IAgTerrain terrain = elementCollection.Add(terrainFile, AgETerrainFileType.eMUSERasterFile);

// Set Scenario to use terrain data file
terrain.UseTerrain = true;


Configure scenario animation

[C#] Copy Code
// IAgScenario scenario: Scenario

IAgScAnimation animation = scenario.Animation;

animation.StartTime = "1 Jun 2004 12:00:00.00";
animation.EnableAnimCycleTime = true;
animation.AnimCycleType = AgEScEndLoopType.eEndTime;
animation.AnimCycleTime = "2 Jun 2004 12:00:00.00";
animation.AnimStepValue = 1000;
animation.RefreshDeltaType = AgEScRefreshDeltaType.eRefreshDelta;
animation.RefreshDelta = 0.02;


Configure scenario text font

[C#] Copy Code
// IAgScenario scenario: Scenario

IAgSc3dFont fonts = scenario.VO.LargeFont;

fonts.Bold = true;
fonts.Italic = true;
fonts.PtSize = AgESc3dPtSize.eSc3dFontSize36;

if (fonts.IsFontAvailable("Impact"))
{
    fonts.Name = "Impact";
}

// AvailableFonts returns a one dimensional array of font strings
Array allFonts = fonts.AvailableFonts;
int index = Array.IndexOf(allFonts, "Courier");
if (index != -1)
{
    fonts.Name = allFonts.GetValue(index) as string;
}


Add a new STK Object to the scenario

[C#] Copy Code
// IAgStkObjectRoot root: STK Object Model root

root.CurrentScenario.Children.New(AgESTKObjectType.eShip, "Ship1");


Import an existing STK Object file into the scenario

[C#] Copy Code
// IAgStkObjectRoot root: STK Object Model root
// String stkObjectLocation: Path of STK Object external file

root.CurrentScenario.Children.ImportObject(stkObjectLocation);


Retrieve the list of scenario's children of a given type

[C#] Copy Code
// IAgStkObjectRoot root: STK Object Model root
// AgESTKObjectType type: Object type in scenario that we want to list

IAgStkObjectElementCollection allChildrenOfType = root.CurrentScenario.Children.GetElements(type);

foreach (IAgStkObject o in allChildrenOfType)
{
    Console.WriteLine(o.InstanceName);
}


Close a scenario

[C#] Copy Code
// IAgStkObjectRoot root: STK Object Model root

root.CloseScenario();


Create a new scenario (closing the current scenario if necessary)

[C#] Copy Code
// IAgStkObjectRoot root: STK Object Model root

// Close current scenario
if (root.CurrentScenario != null)
{
    root.CloseScenario();
}
root.NewScenario("Scenario1");

// Get IAgScenario interface
IAgScenario scenario = root.CurrentScenario as IAgScenario;

// Set scenario start and stop times
scenario.SetTimePeriod("1 Jun 1999 12:00:00.00""2 Jun 1999 12:00:00.00");


Load a scenario (closing the current scenario if necessary)

[C#] Copy Code
// IAgStkObjectRoot root: STK Object Model root
// String scenarioLocation: Specified path of scenario

// close current scenario
if (root.CurrentScenario != null)
{
    root.CloseScenario();
}
root.LoadScenario(scenarioLocation);


Save a scenario

[C#] Copy Code
// IAgStkObjectRoot root: STK Object Model root

root.SaveScenario();


Save a scenario to a new location (Save as)

[C#] Copy Code
// IAgStkObjectRoot root: STK Object Model root
// String fileName: Specified path and file name of scenario

root.SaveScenarioAs(fileName);


Define a complex sensor

[C#] Copy Code
// IAgSensor sensor: Sensor object

IAgSnComplexConicPattern patterndata = sensor.CommonTasks.SetPatternComplexConic(10.070.020.0220.0);
patterndata.AngularResolution = 0.5;


Define a custom sensor

[C#] Copy Code
// IAgSensor sensor: Sensor object
// String sensorPatternPath: Path of Custom Sensor data file

// Set pattern type to Custom
IAgSnCustomPattern customPattern = sensor.CommonTasks.SetPatternCustom(sensorPatternPath);
customPattern.AngularResolution = 6.0;
customPattern.UseNativeResolution = false;


Define a half power sensor

[C#] Copy Code
// IAgSensor sensor: Sensor object

// Configure pattern
IAgSnHalfPowerPattern pattern = sensor.CommonTasks.SetPatternHalfPower(12.53.46.0);


Define a SAR sensor

[C#] Copy Code
// IAgSensor sensor: Sensor object

// Configure pattern
IAgSnSARPattern patterndata = sensor.CommonTasks.SetPatternSAR(10.060.040.030.0700.0);


Define a simple conic sensor

[C#] Copy Code
// IAgSensor sensor: Sensor object

IAgSnSimpleConicPattern patternData = sensor.CommonTasks.SetPatternSimpleConic(40.00.1);


Define and compute sensor swath

[C#] Copy Code
// IAgSensor sensor: Sensor object

// Configure swath display properties
IAgSwath swath = sensor.Swath;
swath.Enable = true;
swath.Color = Color.Red; // red
swath.LineStyle = AgELineStyle.eLMSDash;
swath.LineWidth = AgELineWidth.e2;

// New swath properties
swath.UseMaximumCone = true;
swath.CurvatureTolerance = 90.0;
swath.ScatteringTolerance = 70.0;
swath.MinimumStep = 5;
swath.MaximumStep = 10;

swath.AddTimeInterval("1 Jan 2012 12:00:00.000""1 Jan 2012 13:00:00.000");
swath.AddTimeInterval("1 Jan 2012 14:00:00.000""1 Jan 2012 15:00:00.000");


Define external sensor pointing

[C#] Copy Code
// IAgSensor sensor: Sensor object
// String externalSensorPointingPath: Path of sensor external file

// Sensor pointing data files traditionally have .sp extensions
sensor.SetPointingExternalFile(externalSensorPointingPath);

IAgSnPtExternal external = sensor.Pointing as IAgSnPtExternal;


Define fixed location

[C#] Copy Code
// IAgSensor sensor: Sensor object

// Set sensor's location to fixed
sensor.SetLocationType(AgESnLocation.eSnFixed);

// Configure sensor location
IAgPosition pos = sensor.LocationData as IAgPosition;
pos.AssignCartesian(595.20, -110.124.6);


Define fixed sensor pointing

[C#] Copy Code
// IAgSensor sensor: Sensor object

IAgSnPtFixed fixedSensor = sensor.CommonTasks.SetPointingFixedAzEl(4.5, -45.0, AgEAzElAboutBoresight.eAzElAboutBoresightRotate);


Define location from Vector Geometry Tool point

[C#] Copy Code
// IAgSensor sensor: Sensor object

// Set location type to VGT
sensor.SetLocationType(AgESnLocation.eSnLocationCrdnPoint);

// Get IAgLocationCrdnPoint interface
IAgLocationCrdnPoint vgtPoint = sensor.LocationData as IAgLocationCrdnPoint;

// point sensor to an already existing object
vgtPoint.PointPath = "Facility/Facility1 Center";


Define location on 3D model

[C#] Copy Code
// IAgSensor sensor: Sensor object

// Set pointing type to 3d model
sensor.SetPointingType(AgESnPointing.eSnPt3DModel);

// Point to model attach point (in this example: "SolarArrays-000000")
IAgSnPt3DModel model = sensor.CommonTasks.SetPointing3DModel("Solar_PanelsNode");


Define sensor to use azimuth elevation mask file

[C#] Copy Code
// IAgSensor sensor: Sensor object
// String maskFilePath: Path to external az-el data file

// Specify Mask file
sensor.SetAzElMaskFile(maskFilePath);

// Get Mask File interface
IAgSnAzElMaskFile maskFile = sensor.AzElMaskData as IAgSnAzElMaskFile;

// Configure MaskFile as needed
maskFile.BoresightAxis = AgESnAzElBsightAxisType.ePlus_MinusZ;


Define spinning sensor pointing

[C#] Copy Code
// IAgStkObjectRoot root: STK Object Model root
// IAgSensor sensor: Sensor object

// Set pattern type to Spinning
sensor.SetPointingType(AgESnPointing.eSnPtSpinning);
IAgSnPtSpinning spinning = sensor.Pointing as IAgSnPtSpinning;

// Configure sensor
spinning.SpinAxisAzimuth = 14.24;
spinning.SpinAxisElevation = 7.68;
spinning.SpinAxisConeAngle = 42.46;
spinning.ScanMode = AgESnScanMode.eSnContinuous;
spinning.SpinRate = 88.921;
spinning.OffsetAngle = 110.44;


Define spinning sensor pointing (using common tasks)

[C#] Copy Code
// IAgSensor sensor: Sensor object

// Configure sensor (using common taks)
sensor.CommonTasks.SetPointingSpinning(
    14.24,
    7.68,
    42.46,
    AgESnScanMode.eSnContinuous,
    88.921,
    110.44,
    1.20,
    3.50);


Define targeted sensor pointing

[C#] Copy Code
// IAgSensor sensor: Sensor object

IAgSnPtTargeted targetedSensor = sensor.CommonTasks.SetPointingTargetedTracking(
    AgETrackModeType.eTrackModeTransmit, AgEBoresightType.eBoresightLevel, "*/AreaTarget/AreaTarget1");


Configure sensor 3D projection

[C#] Copy Code
// IAgSnVO sensorVo: Sensor VO object

sensorVo.ProjectionType = AgESnVOProjectionType.eProjectionAllIntersections;
sensorVo.InheritFrom2D = AgESnVOInheritFrom2D.eSnVOInheritFrom2DExtentOnly;
sensorVo.SpaceProjection = 2000.0;


Configure basic properties

[C#] Copy Code
// IAgStar star: Star object

// Units depend on current unit preferences
star.LocationDeclination = -40.0;
star.LocationRightAscension = 120.0// in arcSec
star.Magnitude = -1.0;
star.Parallax = 0.0// in arcSec
star.ProperMotionDeclination = 1.5// in arcSec
star.ProperMotionRadialVelocity = 0.75// in meters
star.ProperMotionRightAscension = -0.5// in arcSec


Create a star (on current scenario central body)

[C#] Copy Code
// IAgStkObjectRoot root: STK Object Model root

// Create the Star
IAgStar star = root.CurrentScenario.Children.New(AgESTKObjectType.eStar, "MyStar"as IAgStar;


Create a star from a star database

[C#] Copy Code
// IAgStkObjectRoot root: STK Object Model root

// Import object from database using Connect
string command = "ImportFromDB * Star ScenarioCollection VisualMagnitude 0 1.0 RightAsc 200.0 230.0 Constellation ImportedFromStarDB";
root.ExecuteCommand(command);

IAgStar star = root.GetObjectFromPath("Star/Star-65474"as IAgStar;


Change a target position

[C#] Copy Code
// IAgTarget target: Target

IAgPosition pos = target.Position;
pos.AssignGeodetic(39.9515.58231.54);


Configure a target from azimuth mask file

[C#] Copy Code
// IAgTarget target: Target
// String maskfile: Path of maskfile

target.UseLocalTimeOffset = true;
target.LocalTimeOffset = 200.0;
target.UseTerrain = true;
// Note, if SetAzElMask is set to a type other than AgEAzElMaskType.eMaskFile,
// the second parameter is ignored.
target.SetAzElMask(AgEAzElMaskType.eMaskFile, maskfile);
target.TerrainNorm = AgETerrainNormType.eSlopeAzimuth;
target.AltRef = AgEAltRefType.eMSL;
target.HeightAboveGround = 1472.0;


Create a target (on the current scenario central body)

[C#] Copy Code
// IAgStkObjectRoot root: STK Object Model root

// Create the Target on the current scenario central body (use
// NewOnCentralBody to specify explicitly the central body)
IAgTarget areaTarget = root.CurrentScenario.Children.New(AgESTKObjectType.eAreaTarget, "MyAreaTarget"as IAgTarget;


Configure an aircraft route using the Great Arc propagator

[C#] Copy Code
// IAgAircraft aircraft: Aircraft object

// Set ship route to great arc
aircraft.SetRouteType(AgEVePropagatorType.ePropagatorGreatArc);

// Retrieve propagator interface
IAgVePropagatorGreatArc propagator = aircraft.Route as IAgVePropagatorGreatArc;
propagator.ArcGranularity = 51.333;

// Set Ref type to WayPtAltRefTerrain and retreive IAgVeWayPtAltitudeRefTerrain interface
propagator.SetAltitudeRefType(AgEVeAltitudeRef.eWayPtAltRefTerrain);
IAgVeWayPtAltitudeRefTerrain altRef = propagator.AltitudeRef as IAgVeWayPtAltitudeRefTerrain;
altRef.Granularity = 51.33;
altRef.InterpMethod = AgEVeWayPtInterpMethod.eWayPtEllipsoidHeight;

propagator.Method = AgEVeWayPtCompMethod.eDetermineTimeAccFromVel;

// Add waypoints
IAgVeWaypointsElement point1 = propagator.Waypoints.Add();
point1.Latitude = 39.7674;
point1.Longitude = -79.7292;
point1.Altitude = 3.0;
point1.Speed = 0.0772;

IAgVeWaypointsElement point2 = propagator.Waypoints.Add();
point2.Latitude = 38.3721;
point2.Longitude = -120.1160;
point2.Altitude = 3.0;
point2.Speed = 0.0772;

// Add more way points if necessary...

// Propagate
propagator.Propagate();


Set an aircraft to use Great Arc propagator

[C#] Copy Code
// IAgAircraft aircraft: Aircraft object

// Set ship route to great arc
aircraft.SetRouteType(AgEVePropagatorType.ePropagatorGreatArc);

// Retrieve propagator interface
IAgVePropagatorGreatArc propagator = aircraft.Route as IAgVePropagatorGreatArc;


Add ground ellipse element and data element

[C#] Copy Code
// IAgVeGroundEllipsesCollection ellipsesCollection: Ellipses collection

// Add ground ellipse
IAgVeGroundEllipseElement ellipse = ellipsesCollection.Add("MyEllipses");

// Add ellipse data element
IAgVeEllipseDataElement element = ellipse.EllipseData.Add();

// Configure element properties
element.Time = "1 Jan 2012 12:00:00.000";
element.Latitude = 35.2920;
element.Longitude = -93.7299;
element.SemiMajorAxis = 400.0;
element.SemiMinorAxis = 300.0;
element.Bearing = 35.71;


Export a vehicle attitude to an external file

[C#] Copy Code
// IAgScenario scenario: Current Scenario Object.
// IAgVeAttitudeExportTool attitudeExport: Attitude Export Tool

// Set and configure attitude coordinate axes
attitudeExport.SetCoordinateAxesType(AgEAttCoordinateAxes.eAttCoordinateAxesCustom);
IAgVeCoordinateAxesCustom customAxes = attitudeExport.CoordinateAxes as IAgVeCoordinateAxesCustom;
customAxes.ReferenceAxesName = "CentralBody/Sun J2000 Axes";

attitudeExport.VersionFormat = AgEExportToolVersionFormat.eExportToolVersionFormatCurrent;
attitudeExport.Include = AgEAttInclude.eAttIncludeQuaternionsAngularVelocity;

// Set the attitude file to use Scenario start and stop time
attitudeExport.TimePeriod.TimePeriodType = AgEExportToolTimePeriod.eExportToolTimePeriodSpecify;
attitudeExport.TimePeriod.Start = scenario.StartTime;
attitudeExport.TimePeriod.Stop = scenario.StopTime;

attitudeExport.StepSize.StepSizeType = AgEExportToolStepSize.eExportToolStepSizeSpecify;
attitudeExport.StepSize.Value = 3600;

// Save Attitude File
attitudeExport.Export("OMExternalFileAttitude.a");


Export a vehicle STK ephemeris to an external file

[C#] Copy Code
// IAgScenario scenario: Scenario object
// IAgVeEphemerisStkExportTool stkEphem: STK Ephemeris Export Tool
// String ephemFilePath: The fully qualified file path where the Ephemeris is to be exported to

// set export parameters
stkEphem.CoordinateSystem = AgEStkEphemCoordinateSystem.eStkEphemCoordinateSystemFixed;
stkEphem.IncludeInterp = true;
stkEphem.VersionFormat = AgEExportToolVersionFormat.eExportToolVersionFormatCurrent;
stkEphem.TimePeriod.TimePeriodType = AgEExportToolTimePeriod.eExportToolTimePeriodSpecify;

// Set the ephemeris to the Scenario start and stop times
stkEphem.TimePeriod.Start = scenario.StartTime;
stkEphem.TimePeriod.Stop = scenario.StopTime;

stkEphem.StepSize.StepSizeType = AgEExportToolStepSize.eExportToolStepSizeEphem;
stkEphem.Export(ephemFilePath);


Add attitude data based on a time-ordered set of Euler angles

[C#] Copy Code
// IAgSatellite satellite: Satellite object

// Set Attitude to Standard
satellite.SetAttitudeType(AgEVeAttitude.eAttitudeStandard);
// Get IAgVeOrbitAttitudeStandard interface
IAgVeOrbitAttitudeStandard standard = satellite.Attitude as IAgVeOrbitAttitudeStandard;

// Set Profile to Inertially Fixed
standard.Basic.SetProfileType(AgEVeProfile.eProfileInertiallyFixed);
// Get IAgVeProfileInertial interface
IAgVeProfileInertial interfix = standard.Basic.Profile as IAgVeProfileInertial;

interfix.Inertial.AssignEulerAngles(AgEEulerOrientationSequence.e123, 20.150.020.0);


Add attitude data based on a time-ordered set of quaternions

[C#] Copy Code
// IAgSatellite satellite: Satellite object

satellite.SetAttitudeType(AgEVeAttitude.eAttitudeStandard);
IAgVeOrbitAttitudeStandard standard = satellite.Attitude as IAgVeOrbitAttitudeStandard;
standard.Basic.SetProfileType(AgEVeProfile.eProfileInertiallyFixed);
IAgVeProfileInertial interfix = standard.Basic.Profile as IAgVeProfileInertial;

interfix.Inertial.AssignQuaternion(-0.34298, -0.470810.703450.40725);


Add attitude data based on a time-ordered set of quaternions interpreted relative to CBF

[C#] Copy Code
// IAgStkObjectRoot root: STK Object Model root
// IAgSatellite satellite: Satellite object
// Array cpfQuaternion: Array that contains CPF Quaternion data

satellite.SetAttitudeType(AgEVeAttitude.eAttitudeRealTime);
IAgVeAttitudeRealTime realtime = satellite.Attitude as IAgVeAttitudeRealTime;

for (int i = 0; i < cpfQuaternion.GetUpperBound(0); i++)
{
    realtime.AddCBFQuaternion(
        cpfQuaternion.GetValue(i, 0),
        (double)cpfQuaternion.GetValue(i, 1),
        (double)cpfQuaternion.GetValue(i, 2),
        (double)cpfQuaternion.GetValue(i, 3),
        (double)cpfQuaternion.GetValue(i, 4));
}


Configure real-time attitude

[C#] Copy Code
// IAgSatellite satellite: Satellite object

// set attitude type to real time
satellite.SetAttitudeType(AgEVeAttitude.eAttitudeRealTime);
IAgVeAttitudeRealTime realtime = satellite.Attitude as IAgVeAttitudeRealTime;

// Set our Attitude Look Ahead method to Extrapolate
realtime.LookAheadMethod = AgEVeLookAheadMethod.eExtrapolate;

// Duration
IAgVeDuration duration = realtime.Duration;
duration.LookAhead = 1600.0;
duration.LookBehind = 1600.0;

// BlockFactor
realtime.BlockFactor = 40;
realtime.DataReference.SetProfileType(AgEVeProfile.eProfileInertiallyFixed);


Set attitude profile type (if profile is supported)

[C#] Copy Code
// IAgSatellite satellite: Satellite object

IAgVeOrbitAttitudeStandard standard = satellite.Attitude as IAgVeOrbitAttitudeStandard;
if (standard.Basic.IsProfileTypeSupported(AgEVeProfile.eProfileSpinning))
{
    standard.Basic.SetProfileType(AgEVeProfile.eProfileSpinning);
}


Configure access intervals graphics

[C#] Copy Code
// IAgVeGfxAttributesAccess accessAttributes: Access Attributes graphics

accessAttributes.AccessObjects.Add("Satellite/sat1");

accessAttributes.DuringAccess.IsVisible = true;
accessAttributes.DuringAccess.Color = Color.Yellow;
accessAttributes.NoAccess.IsVisible = true;
accessAttributes.NoAccess.Color = Color.Red;


Configure basic graphics

[C#] Copy Code
// IAgVeGfxAttributesBasic basicAttributes: Basic Attributes graphics

// Change display
basicAttributes.IsVisible = true;
basicAttributes.Color = Color.Red;
basicAttributes.Line.Style = AgELineStyle.eDotted;
basicAttributes.Line.Width = AgELineWidth.e3;
basicAttributes.MarkerStyle = "Square";


Configure custom intervals graphics

[C#] Copy Code
// IAgVeGfxAttributesCustom customAttributes: Custom Attributes graphics

IAgVeGfxIntervalsCollection customIntervals = customAttributes.Intervals;

// Add intervals
customIntervals.Add("1 Jan 2012 12:00:00.000""1 Jan 2012 14:00:00.000");
customIntervals.Add("2 Jan 2012 01:00:00.000""2 Jan 2012 02:00:00.000");

// Deconflict intervals if necessary
customAttributes.Deconflict();


Configure elevation contours

[C#] Copy Code
// IAgVeGfxElevContours gfxContours: Gfx contours
// IAgVeVOElevContours voContours: VO contours

gfxContours.IsVisible = true;
gfxContours.IsFillVisible = true;
gfxContours.FillStyle = AgEFillStyle.eFillStyleHorizontalStripe;
gfxContours.NumOfDecimalDigits = 5;

// Add contour elevation level
IAgVeGfxElevationsElement elevation = gfxContours.Elevations.AddLevel(25.0);

// Configure contour elevation element
elevation.Color = Color.Red;
elevation.DistanceVisible = true;
elevation.LineStyle = AgELineStyle.eDotted;
elevation.LineWidth = AgELineWidth.e3;
elevation.UserTextVisible = true;
elevation.UserText = "My new elevation";

// Set contours to visible on scenario
voContours.IsVisible = true;
voContours.Fill = true;
voContours.FillTranslucency = 80.0;


Configure sunlight lighting graphics

[C#] Copy Code
// IAgVeGfxLighting lighting: Vehicle graphics lighting

IAgVeGfxLightingElement sunlight = lighting.Sunlight;

sunlight.Visible = true;
sunlight.Color = Color.Red;
sunlight.LineStyle = AgELineStyle.eDotted;
sunlight.LineWidth = AgELineWidth.e3;
sunlight.MarkerStyle = "Circle";


Set a vehicle's graphics to access intervals

[C#] Copy Code
// IAgGreatArcGraphics graphics: Great Arc graphics

if (graphics.IsAttributesTypeSupported(AgEVeGfxAttributes.eAttributesAccess))
{
    // Set graphics to access intervals
    graphics.SetAttributesType(AgEVeGfxAttributes.eAttributesAccess);

    // Get IAgVeGfxAttributesAccess interface
    IAgVeGfxAttributesAccess accessAttributes = graphics.Attributes as IAgVeGfxAttributesAccess;

    // adjust the access intervals graphics
}


Set a vehicle's graphics to basic

[C#] Copy Code
// IAgGreatArcGraphics graphics: Great Arc graphics

if (graphics.IsAttributesTypeSupported(AgEVeGfxAttributes.eAttributesBasic))
{
    // Set graphics to basic
    graphics.SetAttributesType(AgEVeGfxAttributes.eAttributesBasic);

    // Get IAgVeGfxAttributesBasic interface
    IAgVeGfxAttributesBasic basicAttributes = graphics.Attributes as IAgVeGfxAttributesBasic;

    // adjust the basic graphics
}


Set a vehicle's graphics to custom intervals

[C#] Copy Code
// IAgGreatArcGraphics graphics: Great Arc graphics

if (graphics.IsAttributesTypeSupported(AgEVeGfxAttributes.eAttributesCustom))
{
    // Set graphics to custom
    graphics.SetAttributesType(AgEVeGfxAttributes.eAttributesCustom);

    // Get IAgVeGfxAttributesCustom interface
    IAgVeGfxAttributesCustom customAttributes = graphics.Attributes as IAgVeGfxAttributesCustom;

    // adjust the custom intervals graphics
}


Configure 3D dropline graphics

[C#] Copy Code
// IAgVeVODropLinePathItem dropLine: Drop line

dropLine.IsVisible = true;
dropLine.Use2DColor = false;
dropLine.Color = Color.Red;
dropLine.LineStyle = AgELineStyle.eDashed;
dropLine.LineWidth = AgELineWidth.e4;
dropLine.Interval = 100.000// in sec


Configure 3D pass graphics

[C#] Copy Code
// IAgVeVOPass pass: Vehicle pass

// Set lead data type to fraction, retrieved IAgVeGfxLeadData implementation
pass.TrackData.PassData.GroundTrack.SetLeadDataType(AgELeadTrailData.eDataQuarter);

pass.TrackData.PassData.GroundTrack.SetTrailDataType(AgELeadTrailData.eDataHalf);
pass.TrackData.PassData.Orbit.SetLeadDataType(AgELeadTrailData.eDataQuarter);
pass.TrackData.PassData.Orbit.SetTrailSameAsLead();

pass.TickMarks.GroundTrack.IsVisible = true;
pass.TickMarks.GroundTrack.SetTickDataType(AgETickData.eTickDataRadial);
pass.TickMarks.Orbit.IsVisible = true;
pass.TickMarks.Orbit.SetTickDataType(AgETickData.eTickDataRadialAndCrossTrack);
pass.TickMarks.TimeBetweenTicks = 180;


Configure control from a propagate segment with Design Explorer Optimizer

[C#] Copy Code
// IAgVAMCSTargetSequence sequence: Target sequence object

string deoStr = "Design Explorer Optimizer";

// Retrieve sequence profile
if (Array.IndexOf(sequence.Profiles.AvailableProfiles, deoStr) != -1)
{
    // Add a propagate segment on the Target Sequence in order to provide a control
    IAgVAMCSPropagate propagate = sequence.Segments.Insert(AgEVASegmentType.eVASegmentTypePropagate, "MyPropagate""-"as IAgVAMCSPropagate;

    // Enable the propagate "StoppingConditions.Duration.TripValue" control
    IAgVAStoppingConditionElement durationControl = propagate.StoppingConditions["Duration"];
    durationControl.EnableControlParameter(AgEVAControlStoppingCondition.eVAControlStoppingConditionTripValue);

    IAgVAProfileDEOptimizer deo = sequence.Profiles.Add(deoStr) as IAgVAProfileDEOptimizer;

    // Retrieve result reference
    IAgVADEControlCollection controls = deo.ControlParameters;
    IAgVADEControl prop1Duration = controls.GetControlByPaths("MyPropagate""StoppingConditions.Duration.TripValue");

    // Configure IAgVADEControl properties
    prop1Duration.Enable = true;
    prop1Duration.Perturbation = 0.01;
    prop1Duration.LowerBound = 0;
    prop1Duration.UpperBound = 43200;
    prop1Duration.ScalingMethod = AgEVADEScalingMethod.eVADEScalingMethodCustom;
    prop1Duration.ScalingValue = 0.000055;
}


Configure initial state segment

[C#] Copy Code
// IAgVADriverMCS driver: Astrogrator driver object

// Add a new segment and cast the segment to the IAgVAMCSInitialState interface
IAgVAMCSSegment segment = driver.MainSequence.Insert(AgEVASegmentType.eVASegmentTypeInitialState, "Inner Orbit""-");
IAgVAMCSInitialState initState = segment as IAgVAMCSInitialState;

initState.CoordSystemName = "CentralBody/Earth Fixed";
initState.OrbitEpoch = "1 Jan 2012 12:00:00.000";

// Set element type and cast the Element property to the appropriate interface
// configure the element as necessary
initState.SetElementType(AgEVAElementType.eVAElementTypeCartesian);
IAgVAElementCartesian cartesian = initState.Element as IAgVAElementCartesian;
cartesian.Vx = 8051.21;
cartesian.Y = 55;
cartesian.Z = 0;
cartesian.Vx = 0.45;
cartesian.Vy = 8.10158;
cartesian.Vz = 3.51009;

// Configure fuel tank if necessary
initState.FuelTank.FuelDensity = 1001;
initState.FuelTank.FuelMass = 501;
initState.FuelTank.TankPressure = 5001;
initState.FuelTank.TankTemperature = 292;

// Configure spacecraft parameters
initState.SpacecraftParameters.Cd = 2.3;
initState.SpacecraftParameters.Ck = 1.1;
initState.SpacecraftParameters.Cr = 1.3;
initState.SpacecraftParameters.DragArea = 21;
initState.SpacecraftParameters.DryMass = 501;
initState.SpacecraftParameters.K1 = /*$k1$K1*/2;
initState.SpacecraftParameters.K2 = 3;
initState.SpacecraftParameters.RadiationPressureArea = 23.0;
initState.SpacecraftParameters.SolarRadiationPressureArea = 22.0;


Configure launch segment

[C#] Copy Code
// IAgVADriverMCS driver: Astrogrator driver object

// Add launch sequence and retrieve the
IAgVAMCSSegment segment = driver.MainSequence.Insert(AgEVASegmentType.eVASegmentTypeLaunch, "MyLaunch""-");
IAgVAMCSLaunch launch = segment as IAgVAMCSLaunch;

// Configure launch properties
launch.CentralBodyName = "Mars";
launch.Epoch = "1 Jan 2012 12:00:00.000";
launch.StepSize = 6;
launch.UsePreviousSegmentState = false;
launch.PreLaunchTime = 1;
launch.TimeOfFlight = 500;
launch.AscentType = AgEVAAscentType.eVAAscentTypeEllipseQuarticMotion;
launch.InitialAcceleration = 0.02;

// Configure display type
launch.SetDisplaySystemType(AgEVALaunchDisplaySystem.eVADisplaySystemGeocentric);
IAgVADisplaySystemGeocentric llr = (IAgVADisplaySystemGeocentric)launch.DisplaySystem;
llr.Latitude = 35.581;
llr.Longitude = -92.263;
llr.Radius = 1000;

// Configure launch type
launch.AscentType = AgEVAAscentType.eVAAscentTypeEllipseQuarticMotion;
launch.InitialAcceleration = 0.02;
launch.AscentType = AgEVAAscentType.eVAAscentTypeEllipseCubicMotion;

// Configure burnout type
IAgVABurnoutVelocity velocity = launch.BurnoutVelocity;
velocity.BurnoutOption = AgEVABurnoutOptions.eVABurnoutOptionsInertialVelocity;
velocity.InertialVelocity = 20.0;
velocity.InertialHorizontalFPA = 22;
velocity.InertialVelocityAzimuth = 55;
velocity.BurnoutOption = AgEVABurnoutOptions.eVABurnoutOptionsFixedVelocity;
velocity.FixedVelocity = 20;


Configure maneuver segment

[C#] Copy Code
// IAgVADriverMCS driver: Astrogrator driver object

// Add launch sequence and retrieve the IAgVAMCSManeuver interface
IAgVAMCSSegment segment = driver.MainSequence.Insert(AgEVASegmentType.eVASegmentTypeManeuver, "MyManeuver""-");
IAgVAMCSManeuver maneuver = segment as IAgVAMCSManeuver;

// Set Maneuver to Impulsive
maneuver.SetManeuverType(AgEVAManeuverType.eVAManeuverTypeImpulsive);
IAgVAManeuverImpulsive impulse = maneuver.Maneuver as IAgVAManeuverImpulsive;

// Set Impulsive attitude to VelocityVector
impulse.SetAttitudeControlType(AgEVAAttitudeControl.eVAAttitudeControlVelocityVector);
IAgVAAttitudeControlImpulsiveVelocityVector velVec = impulse.AttitudeControl as IAgVAAttitudeControlImpulsiveVelocityVector;
velVec.DeltaVMagnitude = 1.0;

impulse.SetPropulsionMethod(AgEVAPropulsionMethod.eVAPropulsionMethodThrusterSet, "Thruster Set");
impulse.UpdateMass = true;


Configure propagate segment

[C#] Copy Code
// IAgVADriverMCS driver: Astrogrator driver object

// Add a propagate segment to our sequence
IAgVAMCSSegment segment = driver.MainSequence.Insert(AgEVASegmentType.eVASegmentTypePropagate, "Propagate""-");
IAgVAMCSPropagate propagate = segment as IAgVAMCSPropagate;
propagate.PropagatorName = "Earth Point Mass";

// Configure propagtor advanced properties
propagate.MinPropagationTime = 0;
propagate.EnableMaxPropagationTime = true;
propagate.MaxPropagationTime = 72000000;
propagate.EnableWarningMessage = true;

// Configure stopping conditions
IAgVAStoppingCondition duration = propagate.StoppingConditions["Duration"].Properties as IAgVAStoppingCondition;
duration.Trip = 7200;
duration.Tolerance = 0.00001;

// Add any addition stopping conditions
IAgVAStoppingCondition lightning = propagate.StoppingConditions.Add("Lighting"as IAgVAStoppingCondition;


Configure result from a maneuver segment with Design Explorer Optimizer

[C#] Copy Code
// IAgVAMCSTargetSequence sequence: Target sequence object

// Add a maneuver segment on the Target Sequence in order to provide access result
IAgVAMCSManeuver maneuver = sequence.Segments.Insert(AgEVASegmentType.eVASegmentTypeManeuver, "MyManeuver""-"as IAgVAMCSManeuver;

// Add results the Access result to the manuever
((IAgVAMCSSegment)maneuver).Results.Add("Access/Access");

string deoStr = "Design Explorer Optimizer";

// Retrieve sequence profile
if (Array.IndexOf(sequence.Profiles.AvailableProfiles, deoStr) != -1)
{
    IAgVAProfileDEOptimizer deo = sequence.Profiles.Add(deoStr) as IAgVAProfileDEOptimizer;

    // Retrieve result reference
    IAgVADEResult altitudeResult = deo.Results.GetResultByPaths("MyManeuver""Access");

    // Configure VADEResult properties

    altitudeResult.Enable = true;
    altitudeResult.Goal = AgEVADEGoal.eVADEGoalMaximize;
    altitudeResult.Weight = 2.00000;
    altitudeResult.ScalingMethod = AgEVADEScalingMethod.eVADEScalingMethodInitialValue;
}


Configure sequence segment with scripting tool

[C#] Copy Code
// IAgVADriverMCS driver: Astrogrator driver object

// Add launch sequence and retrieve the
IAgVAMCSSegment segment = driver.MainSequence.Insert(AgEVASegmentType.eVASegmentTypeSequence, "MySequence""-");
IAgVAMCSSequence sequence = segment as IAgVAMCSSequence;

IAgVAScriptingTool scriptTool = sequence.ScriptingTool;
scriptTool.Enable = true;
scriptTool.LanguageType = AgEVALanguage.eVALanguageVBScript;
scriptTool.ScriptText(
@"
DeltaArg = dArg

REM  Set the optimizers desired results
DEOdArgUB = DeltaArg
DEOdArgLB = DeltaArg


REM  Initial guess tool:
REM  Assume transfer orbit is something like a circular orbit linking apoapse of initial orbit to apoapse of final orbit
REM  Constants:
mu = 398600
pi = 3.14159265358979

REM  Step 1:  propagate to apoapsis
Prop1Dur = Period_0/2

REM  Step 2:  conditions at end of initial orbit:
SMA_0 = 0.5*(RadApo_0 + RadPeri_0)
VelApo_0 = sqr( (RadPeri_0*mu) / (RadApo_0*SMA_0) )

REM  Step 3:  evaluate properties of the circular transfer orbit
Rcirc = RadApo_0
Vcirc = sqr(mu/Rcirc)
PeriodCirc = 2*pi*Sqr( Rcirc*Rcirc*Rcirc / mu)

REM  Step 4:  set first maneuver to enter transfer orbit
Burn1X = Vcirc - VelApo_0
Burn1Z = 0

REM  Step 5:  propagate along transfer orbit the desired change in argument of periapse
If DeltaArg >= 0 Then
 TransferDur = PeriodCirc*(DeltaArg/360)
Else
 TransferDur = PeriodCirc*(360+DeltaArg)/360
End If

REM Step 6:  set second maneuver to enter desired final orbit
Burn2X = -Burn1X
Burn2Z = 0
");

// Configure the script tool's segments

IAgVAScriptingSegment burn1X = scriptTool.SegmentProperties.Add("Burn1X");

if (Array.IndexOf(burn1X.AvailableObjectNames, "Optimize_Delta_w.Burn1") != -1)
{
    burn1X.ObjectName = "Optimize_Delta_w.Burn1";
    burn1X.Attribute = "ImpulsiveMnvr.Cartesian.X";
    burn1X.Unit = "km/sec";
}

IAgVAScriptingCalcObject period0 = scriptTool.CalcObjects.Add("Period_0");
period0.CalcObjectName = "Segments/Value At Segment";
IAgVAStateCalcValueAtSegment valAtSeg = period0.CalcObject as IAgVAStateCalcValueAtSegment;
valAtSeg.CalcObjectName = "Keplerian Elems/Orbit Period";


Configure target sequence segment

[C#] Copy Code
// IAgVADriverMCS driver: Astrogrator driver object

// First add a sequence target
IAgVAMCSSegment segment = driver.MainSequence.Insert(AgEVASegmentType.eVASegmentTypeTargetSequence, "Start Transfer""-");
IAgVAMCSTargetSequence targetSequence = segment as IAgVAMCSTargetSequence;

targetSequence.Action = AgEVATargetSeqAction.eVATargetSeqActionRunActiveProfiles;
targetSequence.WhenProfilesFinish = AgEVAProfilesFinish.eVAProfilesFinishRunToReturnAndContinue;
targetSequence.ContinueOnFailure = false;

// Add as many child segments to target
IAgVAMCSManeuver dv1 = targetSequence.Segments.Insert(AgEVASegmentType.eVASegmentTypeManeuver, "DV1""-"as IAgVAMCSManeuver;
IAgVAMCSManeuver dv2 = targetSequence.Segments.Insert(AgEVASegmentType.eVASegmentTypeManeuver, "DV2""-"as IAgVAMCSManeuver;

// Add more profiles if necessary
string profileName = "Change Maneuver Type";
if (Array.IndexOf(targetSequence.Profiles.AvailableProfiles, profileName) != -1)
{
    IAgVAProfile newProfile = targetSequence.Profiles.Add(profileName);
}

// Enable controls
dv1.EnableControlParameter(AgEVAControlManeuver.eVAControlManeuverImpulsiveCartesianX);
IAgVAProfileDifferentialCorrector dc = targetSequence.Profiles["Differential Corrector"as IAgVAProfileDifferentialCorrector;
IAgVADCControl controlParam = dc.ControlParameters.GetControlByPaths("DV1""ImpulsiveMnvr.Cartesian.X");
controlParam.Enable = true;
controlParam.MaxStep = 0.3;

// Enable results
((IAgVAMCSSegment)dv1).Results.Add("Epoch");
IAgVADCResult roaResult = dc.Results.GetResultByPaths("DV1""Epoch");
roaResult.Enable = true;

// Confiure the differential corrector
dc.MaxIterations = 50;
dc.EnableDisplayStatus = true;
dc.Mode = AgEVAProfileMode.eVAProfileModeIterate;
targetSequence.Action = AgEVATargetSeqAction.eVATargetSeqActionRunActiveProfiles;


Configure target sequence with Differential Corrector profile

[C#] Copy Code
// IAgVADriverMCS driver: Astrogrator driver object

IAgVAMCSTargetSequence startTransfer = driver.MainSequence["Start Transfer"as IAgVAMCSTargetSequence;

string dcString = "Differential Corrector";

if (Array.IndexOf(startTransfer.Profiles.AvailableProfiles, dcString) != -1)
{
    IAgVAProfileDifferentialCorrector dc = startTransfer.Profiles.Add(dcString) as IAgVAProfileDifferentialCorrector;

    // Configure differential corrector
    dc.ClearCorrectionsBeforeRun = true;
    dc.ConvergenceCriteria = AgEVAConvergenceCriteria.eVAConvervenceCriteriaEitherEqualityConstraintsOrControlParams;
    dc.EnableBPlaneNominal = false;
    dc.EnableBPlanePerturbations = false;
    dc.EnableDisplayStatus = true;
    dc.EnableHomotopy = true;
    dc.HomotopySteps = 2;
    dc.EnableHomotopy = false;
    dc.EnableLineSearch = true;
    dc.LineSearchLowerBound = 0.001;
    dc.LineSearchTolerance = 0.001;
    dc.LineSearchUpperBound = 5.0;
    dc.MaxLineSearchIterations = 5;
    dc.MaxIterations = 20;

    // Apply
    startTransfer.ApplyProfiles();
}


Configure the Astrogrator propagator

[C#] Copy Code
// IAgSatellite satellite: Satellite object

satellite.SetPropagatorType(AgEVePropagatorType.ePropagatorAstrogator);

IAgVADriverMCS driver = satellite.Propagator as IAgVADriverMCS;

// Remove if necessary
driver.MainSequence.RemoveAll();

// Configure properties as necessarily
driver.Options.DrawTrajectoryIn3D = true;
driver.Options.GraphicsUpdateRate = 0.90;
driver.Options.UpdateAnimationTimeForAllObjects = false;
driver.Options.StoppingConditionTimeTolerance = 0.00000005;
driver.Options.EnableLogging = true;


Configure update segment

[C#] Copy Code
// IAgVADriverMCS driver: Astrogrator driver object

// Add launch sequence and retrieve the
IAgVAMCSSegment segment = driver.MainSequence.Insert(AgEVASegmentType.eVASegmentTypeUpdate, "MyUpdate""-");
IAgVAMCSUpdate update = segment as IAgVAMCSUpdate;

// Specify the element to be changed, the action, and the value

// Add values
update.SetActionAndValue(AgEVAUpdateParam.eVAUpdateParamCd, AgEVAUpdateAction.eVAUpdateActionAddValue, 2);
update.SetActionAndValue(AgEVAUpdateParam.eVAUpdateParamFuelDensity, AgEVAUpdateAction.eVAUpdateActionAddValue, 1);

// Set to new value
update.SetActionAndValue(AgEVAUpdateParam.eVAUpdateParamTankPressure, AgEVAUpdateAction.eVAUpdateActionSetToNewValue, 6000);
update.SetActionAndValue(AgEVAUpdateParam.eVAUpdateParamTankTemp, AgEVAUpdateAction.eVAUpdateActionSetToNewValue, 5);

// Subtract values
update.SetActionAndValue(AgEVAUpdateParam.eVAUpdateParamSRPArea, AgEVAUpdateAction.eVAUpdateActionSubtractValue, 10);
update.SetActionAndValue(AgEVAUpdateParam.eVAUpdateParamSRPArea, AgEVAUpdateAction.eVAUpdateActionSubtractValue, 1);


Configure the Ballistic propagator

[C#] Copy Code
// IAgVePropagatorBallistic propagator: Ballistic propagator

propagator.Step = 30;
propagator.SetLaunchType(AgEVeLaunch.eLaunchLLA);

IAgVeLaunchLLA launch = propagator.Launch as IAgVeLaunchLLA;
launch.Lat = 30.338;
launch.Lon = 33.468;
launch.Alt = 1.5;

propagator.SetImpactLocationType(AgEVeImpactLocation.eImpactLocationPoint);

IAgVeImpactLocationPoint impactLocation = propagator.ImpactLocation as IAgVeImpactLocationPoint;
impactLocation.SetImpactType(AgEVeImpact.eImpactLLA);
impactLocation.SetLaunchControlType(AgEVeLaunchControl.eLaunchControlFixedDeltaV);

IAgVeImpactLLA impact = impactLocation.Impact as IAgVeImpactLLA;
impact.Lat = 25.474;
impact.Lon = 68.306;
impact.Alt = 0.0;

IAgVeLaunchControlFixedDeltaV fixedDeltaV = impactLocation.LaunchControl as IAgVeLaunchControlFixedDeltaV;
fixedDeltaV.DeltaV = 7.545;

propagator.Propagate();


Configure the GPS propagator with an almanac

[C#] Copy Code
// IAgVePropagatorGPS propagator: GPS propagator
// String almanacPath: Almanac path
// IAgStkObject scenario: Current scenario

// Configure properties
// Use the scenario's analysis interval
propagator.EphemerisInterval.SetImplicitInterval(scenario.Vgt.EventIntervals["AnalysisInterval"]);

// PRN must be set before configuring GPS almanac
propagator.PRN = Int32.Parse((string)propagator.AvailablePRNs.GetValue(0));

// Turn the Auto-update off
propagator.AutoUpdateEnabled = false;

// Specify a catalog
propagator.SpecifyCatalog.Filename = almanacPath;

// Configure the properties specific to the chosen almanac
switch (propagator.SpecifyCatalog.Properties.Type)
{
    case AgEVeGPSAlmanacType.eGPSAlmanacTypeSEM:
        {
            /* configure the SEM almanac */
            IAgVeGPSAlmanacPropertiesSEM sem = propagator.SpecifyCatalog.Properties as IAgVeGPSAlmanacPropertiesSEM;
            sem.ReferenceWeek = AgEGPSReferenceWeek.eGPSReferenceWeek22Aug1999;
            break;
        }
    case AgEVeGPSAlmanacType.eGPSAlmanacTypeSP3:
        {
            /* SP3 almanac contains no configurable properties */
            IAgVeGPSAlmanacPropertiesSP3 sp3 = propagator.SpecifyCatalog.Properties as IAgVeGPSAlmanacPropertiesSP3;
            break;
        }
    case AgEVeGPSAlmanacType.eGPSAlmanacTypeYUMA:
        {
            /* configure the YUMA almanac */
            IAgVeGPSAlmanacPropertiesYUMA yuma = propagator.SpecifyCatalog.Properties as IAgVeGPSAlmanacPropertiesYUMA;
            yuma.ReferenceWeek = AgEGPSReferenceWeek.eGPSReferenceWeek22Aug1999;
            break;
        }
}

// Propagate
propagator.Propagate();


Configure the Great Arc propagator with a list of waypoints

[C#] Copy Code
// IAgVePropagatorGreatArc propagator: Great arc propagator

// Array with waypoints to insert
object[,] waypoints = new object[,]
    {
        { 20.3619.410, -99.125"1 Jan 2012 12:00:00.000" },
        { 20.3019.421, -99.135"1 Jan 2012 13:00:00.000" },
        { 20.3019.434, -99.137"1 Jan 2012 14:00:00.000" }
    };

propagator.Method = AgEVeWayPtCompMethod.eDetermineVelFromTime;

// Remove any previous waypoints
propagator.Waypoints.RemoveAll();

// Insert the waypoints
for (int i = 0; i < waypoints.GetLength(0); i++)
{
    IAgVeWaypointsElement waypoint = propagator.Waypoints.Add();
    waypoint.Altitude = (double) waypoints[i, 0];
    waypoint.Latitude = waypoints[i, 1];
    waypoint.Longitude = waypoints[i, 2];
    waypoint.Time = waypoints[i, 3];
}

// Propagate ground vehicle
propagator.Propagate();


Configure the Great Arc propagator with a list of waypoints and velocity

[C#] Copy Code
// IAgVePropagatorGreatArc propagator: Great arc propagator

// Array with waypoints to insert
// Consists of: altitude, latitude, longitude, speed
double[,] waypoints = new double[,]
    {
        { 20.3619.410, -99.12510.5 },
        { 20.3019.421, -99.13512.5 },
        { 20.3019.434, -99.13715.0 }
    };

propagator.Method = AgEVeWayPtCompMethod.eDetermineTimeAccFromVel;

// Remove any previous waypoints
propagator.Waypoints.RemoveAll();

// Insert the waypoints
for (int i = 0; i < waypoints.GetLength(0); i++)
{
    IAgVeWaypointsElement waypoint = propagator.Waypoints.Add();
    waypoint.Altitude = waypoints[i, 0];
    waypoint.Latitude = waypoints[i, 1];
    waypoint.Longitude = waypoints[i, 2];
    waypoint.Speed = waypoints[i, 3];
}

// Propagate ground vehicle
propagator.Propagate();


List all waypoints in a Waypoint Collection

[C#] Copy Code
// IAgVePropagatorGreatArc propagator: Great arc propagator

// Array with waypoints to insert
object[,] waypoints = new object[,]
    {
        { 20.3619.410, -99.125"1 Jan 2012 12:00:00.000" },
        { 20.3019.421, -99.135"1 Jan 2012 13:00:00.000" },
        { 20.3019.434, -99.137"1 Jan 2012 14:00:00.000" }
    };

propagator.Method = AgEVeWayPtCompMethod.eDetermineVelFromTime;

// Remove any previous waypoints
propagator.Waypoints.RemoveAll();

// Insert the waypoints
for (int i = 0; i < waypoints.GetLength(0); i++)
{
    IAgVeWaypointsElement waypoint = propagator.Waypoints.Add();
    waypoint.Altitude = (double)waypoints[i, 0];
    waypoint.Latitude = waypoints[i, 1];
    waypoint.Longitude = waypoints[i, 2];
    waypoint.Time = waypoints[i, 3];
}

// List the waypoints after extracting them into an array
Array waypointArray = propagator.Waypoints.ToArray();
for (int j = 0; j < waypointArray.GetLength(0); ++j)
{
    Console.WriteLine("  Time: {0} Latitude: {1} Longitude: {2} Altitude: {3}",
        waypointArray.GetValue(j, 0),
        Convert.ToDouble(waypointArray.GetValue(j, 1)),
        Convert.ToDouble(waypointArray.GetValue(j, 2)),
        Convert.ToDouble(waypointArray.GetValue(j, 3)));
}


Set Waypoints (Derive Time and Acceleration from Velocity) and Propagate

[C#] Copy Code
// IAgVePropagatorGreatArc propagator: Great arc propagator

propagator.Method = AgEVeWayPtCompMethod.eDetermineTimeAccFromVel;

Array waypoints = Array.CreateInstance(typeof(object), 46);

// Point #1
waypoints.SetValue(0.000); // Lat
waypoints.SetValue(0.001); // Lon
waypoints.SetValue(3500002); // Alt
waypoints.SetValue(3503); // Vel
waypoints.SetValue(0.004); // Acc
waypoints.SetValue(0.005); // Turn radius

// Point #2
waypoints.SetValue(0.110); // Lat
waypoints.SetValue(0.111); // Lon
waypoints.SetValue(3510012); // Alt
waypoints.SetValue(3513); // Vel
waypoints.SetValue(0.014); // Acc
waypoints.SetValue(0.215); // Turn radius

// Point #3
waypoints.SetValue(0.220); // Lat
waypoints.SetValue(0.221); // Lon
waypoints.SetValue(3520022); // Alt
waypoints.SetValue(3523); // Vel
waypoints.SetValue(0.024); // Acc
waypoints.SetValue(0.025); // Turn radius

// Point #4
waypoints.SetValue(0.030); // Lat
waypoints.SetValue(0.031); // Lon
waypoints.SetValue(3520032); // Alt
waypoints.SetValue(3533); // Vel
waypoints.SetValue(0.034); // Acc
waypoints.SetValue(0.035); // Turn radius

propagator.SetPointsSpecifyVelocityAndPropagate(ref waypoints);

Assert.AreEqual(4, propagator.Waypoints.Count);


Set Waypoints (Derive Time from Velocity and Acceleration) and Propagate

[C#] Copy Code
// IAgVePropagatorGreatArc propagator: Great arc propagator

propagator.Method = AgEVeWayPtCompMethod.eDetermineTimeFromVelAcc;

Array waypoints = Array.CreateInstance(typeof(object), 45);
// Point #1
waypoints.SetValue(0.000); // Lat
waypoints.SetValue(0.001); // Lon
waypoints.SetValue(3500002); // Alt
waypoints.SetValue(3503); // Vel
waypoints.SetValue(0.004); // Turn radius
// Point #2
waypoints.SetValue(0.110); // Lat
waypoints.SetValue(0.111); // Lon
waypoints.SetValue(3510012); // Alt
waypoints.SetValue(3513); // Vel
waypoints.SetValue(0.214); // Turn radius
// Point #3
waypoints.SetValue(0.220); // Lat
waypoints.SetValue(0.221); // Lon
waypoints.SetValue(3520022); // Alt
waypoints.SetValue(3523); // Vel
waypoints.SetValue(0.024); // Turn radius
// Point #4
waypoints.SetValue(0.030); // Lat
waypoints.SetValue(0.031); // Lon
waypoints.SetValue(3520032); // Alt
waypoints.SetValue(3533); // Vel
waypoints.SetValue(0.034); // Turn radius

propagator.SetPointsSmoothRateAndPropagate(ref waypoints);

Assert.AreEqual(4, propagator.Waypoints.Count);


Set Waypoints (Derive Velocity from Time) and Propagate

[C#] Copy Code
// IAgVePropagatorGreatArc propagator: Great arc propagator

propagator.Method = AgEVeWayPtCompMethod.eDetermineVelFromTime;

Array waypoints = Array.CreateInstance(typeof(object), 45);
// Point #1
waypoints.SetValue("17 Jan 2013 17:00:00.000"00); // Time
waypoints.SetValue(0.001); // Lat
waypoints.SetValue(0.002); // Lon
waypoints.SetValue(3500003); // Alt
waypoints.SetValue(0.004); // Turn radius

// Point #2
waypoints.SetValue("17 Jan 2013 17:01:00.000"10); // Time
waypoints.SetValue(0.111); // Lat
waypoints.SetValue(0.112); // Lon
waypoints.SetValue(3510013); // Alt
waypoints.SetValue(0.214); // Turn radius

// Point #3
waypoints.SetValue("17 Jan 2013 17:02:00.000"20); // Time
waypoints.SetValue(0.221); // Lat
waypoints.SetValue(0.222); // Lon
waypoints.SetValue(3520023); // Alt
waypoints.SetValue(0.024); // Turn radius

// Point #4
waypoints.SetValue("17 Jan 2013 17:03:00.000"30); // Time
waypoints.SetValue(0.031); // Lat
waypoints.SetValue(0.032); // Lon
waypoints.SetValue(3520033); // Alt
waypoints.SetValue(0.034); // Turn radius

propagator.SetPointsSpecifyTimeAndPropagate(ref waypoints);

Assert.AreEqual(4, propagator.Waypoints.Count);


Sets the ephemeris start time to an explicit time, and then add waypoints relative to that time.

[C#] Copy Code
// IAgVePropagatorGreatArc propagator: Great Arc propagator

// Set the epoch time to tomorrow.
IAgCrdnEventSmartEpoch startEpoch = propagator.EphemerisInterval.GetStartEpoch();
startEpoch.SetExplicitTime("Tomorrow");
propagator.EphemerisInterval.SetStartEpoch(startEpoch);

// Waypoints time start from explicit start time that we set above.
Array waypointsAndTimes = new object[,]
{
    { 40.329, -76.36600.01540 },
    { 40.380, -76.35900.01540 },
    { 40.406, -76.32900.01540 },
    { 40.417, -76.31100.01540 },
};

propagator.SetPointsSmoothRateAndPropagate(ref waypointsAndTimes);

for (int i = 0; i < propagator.Waypoints.Count; ++i)
{
    Console.WriteLine("Waypoint {0}, Lat = {1}, Lon = {2}, Time = {3}",
        i,
        propagator.Waypoints[i].Latitude,
        propagator.Waypoints[i].Longitude,
        propagator.Waypoints[i].Time);
}


Configure the HPOP propagator

[C#] Copy Code
// IAgSatellite satellite: Satellite object

// Set satellite propagator to HPOP
satellite.SetPropagatorType(AgEVePropagatorType.ePropagatorHPOP);

// Get IAgVePropagatorLOP interface
IAgVePropagatorHPOP hpopProp = satellite.Propagator as IAgVePropagatorHPOP;

// Configure force model
IAgVeHPOPForceModel hpopForceModel = hpopProp.ForceModel;
hpopForceModel.CentralBodyGravity.File = @"STKData\CentralBodies\Earth\GGM02C.grv";
hpopForceModel.CentralBodyGravity.MaxDegree = 45;
hpopForceModel.CentralBodyGravity.MaxOrder = 10;
hpopForceModel.CentralBodyGravity.UseOceanTides = true;

hpopForceModel.Drag.Use = true;
IAgVeHPOPDragModelSpherical hpopDragModel = hpopForceModel.Drag.DragModel as IAgVeHPOPDragModelSpherical;
hpopDragModel.Cd = 1.890000;
hpopDragModel.AreaMassRatio = 0.05;
hpopForceModel.Drag.AtmosphericDensityModel = AgEAtmosphericDensityModel.eMSIS90;

hpopForceModel.ThirdBodyGravity.RemoveThirdBody("Moon");

// Propagate
hpopProp.Propagate();


Configure the J2 Perturbation propagator

[C#] Copy Code
// IAgSatellite satellite: Satellite object

// Set propagator to SGP4
satellite.SetPropagatorType(AgEVePropagatorType.ePropagatorJ2Perturbation);

// J2 Perturbation propagator
IAgVePropagatorJ2Perturbation j2prop = satellite.Propagator as IAgVePropagatorJ2Perturbation;

// Configure time period
j2prop.EphemerisInterval.SetExplicitInterval("1 Jan 2012 12:00:00.000""2 Jan 2012 12:00:00.000");
j2prop.Step = 60.0;

// Configure propagator initial state
IAgVeJxInitialState initial = j2prop.InitialState;
initial.Representation.Epoch = "1 Jan 2012 12:00:00.000";
initial.Representation.AssignCartesian(
    AgECoordinateSystem.eCoordinateSystemFixed,
    -1514.4,       // in km (assuming unit preferences set to km)
    -6790.1,       // in km
    -1.25,         // in km
    4.8151,        // in km/sec (assuming unit preferences set to km/sec)
    1.7710,        // in km/sec
    5.6414);       // in km/sec
initial.EllipseOptions = AgEVeEllipseOptions.eSecularlyPrecessing;

// Propagate
j2prop.Propagate();


Configure the J4 Perturbation propagator to a circular orbit

[C#] Copy Code
// IAgSatellite satellite: Satellite object
// Double incl: Inclination (default 45.0)
// Double altitude: Atitude (default 500 km)

satellite.SetPropagatorType(AgEVePropagatorType.ePropagatorJ4Perturbation);
IAgVePropagatorJ4Perturbation prop = satellite.Propagator as IAgVePropagatorJ4Perturbation;

IAgOrbitStateClassical keplerian = prop.InitialState.Representation.ConvertTo(AgEOrbitStateType.eOrbitStateClassical) as IAgOrbitStateClassical;

keplerian.SizeShapeType = AgEClassicalSizeShape.eSizeShapeAltitude;
IAgClassicalSizeShapeAltitude size = keplerian.SizeShape as IAgClassicalSizeShapeAltitude;

size.ApogeeAltitude = altitude;
size.PerigeeAltitude = altitude;

keplerian.Orientation.Inclination = incl;
keplerian.Orientation.ArgOfPerigee = 0;
keplerian.Orientation.AscNodeType = AgEOrientationAscNode.eAscNodeRAAN;
(keplerian.Orientation.AscNode as IAgOrientationAscNodeRAAN).Value = 0;

keplerian.LocationType = AgEClassicalLocation.eLocationTrueAnomaly;
(keplerian.Location as IAgClassicalLocationTrueAnomaly).Value = 0;

prop.InitialState.Representation.Assign(keplerian);
prop.Propagate();


Configure the J4 Perturbation propagator to a critically inclined orbit

[C#] Copy Code
// IAgSatellite satellite: Satellite object
// Double apogeeAlt: Apogee altitude (default 12000 km)
// Double perigeeAlt: Perigee altitude (default 400 km)
// Double ascNodeLon: Longitude of ascending node (default -100 deg

satellite.SetPropagatorType(AgEVePropagatorType.ePropagatorJ4Perturbation);
IAgVePropagatorJ4Perturbation prop = satellite.Propagator as IAgVePropagatorJ4Perturbation;

IAgOrbitStateClassical keplerian = prop.InitialState.Representation.ConvertTo(AgEOrbitStateType.eOrbitStateClassical) as IAgOrbitStateClassical;

keplerian.SizeShapeType = AgEClassicalSizeShape.eSizeShapeAltitude;
IAgClassicalSizeShapeAltitude size = keplerian.SizeShape as IAgClassicalSizeShapeAltitude;

size.ApogeeAltitude = apogeeAlt;
size.PerigeeAltitude = perigeeAlt;

keplerian.Orientation.Inclination = 63.434949;
keplerian.Orientation.ArgOfPerigee = 270.000000;
keplerian.Orientation.AscNodeType = AgEOrientationAscNode.eAscNodeLAN;
(keplerian.Orientation.AscNode as IAgOrientationAscNodeLAN).Value = ascNodeLon;

keplerian.LocationType = AgEClassicalLocation.eLocationTrueAnomaly;
(keplerian.Location as IAgClassicalLocationTrueAnomaly).Value = 90.000000;

prop.InitialState.Representation.Assign(keplerian);
prop.Propagate();


Configure the LOP propagator

[C#] Copy Code
// IAgSatellite satellite: Satellite object

// Set satellite propagator to LOP
satellite.SetPropagatorType(AgEVePropagatorType.ePropagatorLOP);

// Get IAgVePropagatorLOP interface
IAgVePropagatorLOP lopProp = satellite.Propagator as IAgVePropagatorLOP;

// Configure time period
lopProp.EphemerisInterval.SetExplicitInterval("1 Jan 2012 12:00:00.000""2 Jan 2012 12:00:00.000");
lopProp.Step = 86400;

// Configure propagator initial state
IAgOrbitState orbit = lopProp.InitialState.Representation;
orbit.Epoch = "1 Jan 2012 12:00:00.000";
orbit.AssignCartesian(
    AgECoordinateSystem.eCoordinateSystemFixed,
    -1120.32,          // in km (assuming unit preferences set to km)
    -9520.84,         // in km
    0.129,      // in km
    2.155,      // in km/sec (assuming unit preferences set to km/sec)
    -1.54416,      // in km/sec
    5.668412);     // in km/sec

// Configure force model
IAgVeLOPForceModel lopForceModel = lopProp.ForceModel;
lopForceModel.CentralBodyGravity.MaxDegree = 15;
lopForceModel.CentralBodyGravity.MaxOrder = 8;
lopForceModel.Drag.Use = true;
lopForceModel.Drag.Cd = 3.55;
lopForceModel.SolarRadiationPressure.Use = true;
lopForceModel.SolarRadiationPressure.Cp = 1.1250;
lopForceModel.SolarRadiationPressure.AtmosHeight = 125;
lopForceModel.PhysicalData.DragCrossSectionalArea = 0.001555512;
lopForceModel.PhysicalData.SRPCrossSectionalArea = 0.001810026;
lopForceModel.PhysicalData.SatelliteMass = 1505.001;

// Propagate
lopProp.Propagate();


Add realtime LLA positions

[C#] Copy Code
// IAgVePropagatorRealtime propagator: Realtime Propagator

IAgVeRealtimeLLAPoints points = propagator.PointBuilder.LLA;
points.Add("1 Jan 2012 12:00:00.000"39.693, -76.3990.0390.034580.012230.05402);


Add realtime LLA positions in batches

[C#] Copy Code
// IAgVePropagatorRealtime propagator: Realtime Propagator

// Add realtime LLA points in batches
Array times = new object[]
              {
                  "1 Jan 2012 12:00:00.000",
                  "1 Jan 2012 12:01:00.000",
                  "1 Jan 2012 12:02:00.000"
              };
Array lat = new object[]
            {
                39.69341.06139.925
            };
Array lon = new object[]
            {
                -76.399, -74.266, -78.578
            };
Array alt = new object[]
            {
                0.0390.04200.281
            };
Array latrate = new object[]
                {
                    0.034580.032150.03188
                };
Array lonrate = new object[]
                {
                    0.012230.011480.01075
                };
Array altrate = new object[]
                {
                    0.054020.052100.05075
                };

IAgVeRealtimeLLAPoints points = propagator.PointBuilder.LLA;

// AddBatch expects each parameter to be a one dimensional array and all of the same length
points.AddBatch(ref times, ref lat, ref lon, ref alt, ref latrate, ref lonrate, ref altrate);


Configure the Realtime propagator

[C#] Copy Code
// IAgStkObjectRoot root: STK Object Model root
// IAgVePropagatorRealtime propagator: Realtime propagator

// Set Realtime Propagator settings if they should be other than
// the defaults.
propagator.InterpolationOrder = 1;
propagator.TimeoutGap = 30.0;
propagator.TimeStep = 60.0;

// Since we want to use the Two Body Look Ahead Propagator, check
// to see that it is supported before we set the Realtime Propagator
// to use this look ahead type
if (propagator.IsLookAheadPropagatorSupported(AgELookAheadPropagator.eLookAheadTwoBody))
{
    // Set the look ahead type
    propagator.LookAheadPropagator = AgELookAheadPropagator.eLookAheadTwoBody;

    // Set the duration time to look ahead and look behind
    IAgVeDuration duration = propagator.Duration;
    duration.LookAhead = 3600.0;
    duration.LookBehind = 3600.0;

    // Apply the Realtime Propagator settings
    propagator.Propagate();
}


Configure the SGP4 propagator with file source

[C#] Copy Code
// IAgVePropagatorSGP4 propagator: An SGP4 propagator
// String tleFilePath: Path to the external TLE data file

// Configure propagator's TLE file path
propagator.CommonTasks.AddSegsFromFile("2215", tleFilePath);

// Propagate
propagator.Propagate();


Configure the SGP4 propagator with online source

[C#] Copy Code
// IAgVePropagatorSGP4 propagator: An SGP4 propagator

// Configure time period
propagator.EphemerisInterval.SetExplicitInterval("1 Jan 2012 12:00:00.000""2 Jan 2012 12:00:00.000");
propagator.Step = 60.0;

// Add segments
propagator.CommonTasks.AddSegsFromOnlineSource("25544");

// Propagate
propagator.Propagate();


Set SGP4 to auto-update from file source

[C#] Copy Code
// IAgVePropagatorSGP4 propagator: SGP4 satellite propagator
// String fileUpdateSource: File update source

propagator.AutoUpdateEnabled = true;
propagator.AutoUpdate.SelectedSource = AgEVeSGP4AutoUpdateSource.eSGP4AutoUpdateSourceFile;
propagator.AutoUpdate.FileSource.Filename = fileUpdateSource;

// Preview TLEs (optional)
// Preview() returns a one dimension string of tles
Array tles = propagator.AutoUpdate.FileSource.Preview();

Regex rx = new Regex(@"^(?<ssc>[-]?\d+) (?<orbitepoch>[-]?\d+[.]?\d+) (?<revnumber>[-]?\d+)$");
foreach (object line in tles)
{
    Match m = rx.Match(line.ToString());
    Console.WriteLine("SCC: {0}, orbit epoch: {1}, rev number: {2}", m.Groups["ssc"], m.Groups["orbitepoch"], m.Groups["revnumber"]);
}

// Propagate
propagator.Propagate();


Set SGP4 to auto-update from online source

[C#] Copy Code
// IAgVePropagatorSGP4 propagator: SGP4 satellite propagator

propagator.AutoUpdateEnabled = true;
propagator.AutoUpdate.SelectedSource = AgEVeSGP4AutoUpdateSource.eSGP4AutoUpdateSourceOnline;

// Preview TLEs (optional)
// Preview() returns a one dimension string of tles
Array tles = propagator.AutoUpdate.FileSource.Preview();

Regex rx = new Regex(@"^(?<ssc>[-]?\d+) (?<orbitepoch>[-]?\d+[.]?\d+) (?<revnumber>[-]?\d+)$");
foreach (object line in tles)
{
    Match m = rx.Match(line.ToString());
    Console.WriteLine("SCC: {0}, orbit epoch: {1}, rev number: {2}", m.Groups["ssc"], m.Groups["orbitepoch"], m.Groups["revnumber"]);
}

// Propagate
propagator.Propagate();


Configure the Simple Ascent propagator

[C#] Copy Code
// IAgVePropagatorSimpleAscent propagator: The Simple Ascent Propagator

// Configure time period
propagator.EphemerisInterval.SetExplicitInterval("1 Jan 2012 12:00:00.000""2 Jan 2012 12:00:00.000");
propagator.Step = 60.0;

// Set the initial state
propagator.InitialState.Launch.AssignGeodetic(38.3721, -77.640225.0);
propagator.InitialState.Burnout.AssignGeodetic(48.1395, -82.514525.0);
propagator.InitialState.BurnoutVel = 7.7258;

// Propagate
propagator.Propagate();


Configure the SPICE propagator

[C#] Copy Code
// IAgVePropagatorSPICE propagator: The SPICE propagator
// String spiceFile: Path of SPICE file

// Set the SPICE file
propagator.Spice = spiceFile;

// Configure time period
propagator.EphemerisInterval.SetExplicitInterval("1 Jan 2012 12:00:00.000""2 Jan 2012 12:00:00.000");
propagator.Step = 60.0;
propagator.BodyName = "-200000";

// Propagate
propagator.Propagate();


Create a ground vehicle (on current scenario central body)

[C#] Copy Code
// IAgStkObjectRoot root: STK Object Model Root

// Create the ground vehicle
IAgGroundVehicle launchVehicle = root.CurrentScenario.Children.New(AgESTKObjectType.eGroundVehicle,  "MyGroundVehicle"as IAgGroundVehicle;


Get the ground vehicle Attitude Export tool

[C#] Copy Code
// IAgGroundVehicle groundVehicle: GroundVehicle whose attitude we want to export

IAgVeAttitudeExportTool attExTool = groundVehicle.ExportTools.GetAttitudeExportTool();


Get the ground vehicle Propagator Definition Export tool

[C#] Copy Code
// IAgGroundVehicle groundVehicle: GroundVehicle whose propagator definition we want to export

IAgVePropDefExportTool attExTool = groundVehicle.ExportTools.GetPropDefExportTool();


Get the ground vehicle STK Ephemeris Export tool

[C#] Copy Code
// IAgGroundVehicle groundVehicle: GroundVehicle whose ephemeris we want to export

IAgVeEphemerisStkExportTool stkEphem = groundVehicle.ExportTools.GetEphemerisStkExportTool();


Set ground vehicle to use Great Arc propagator

[C#] Copy Code
// IAgGroundVehicle groundVehicle: Ground Vehicle object

// Set ground vehicle route to great arc
groundVehicle.SetRouteType(AgEVePropagatorType.ePropagatorGreatArc);

// Retrieve propagator interface if necessary
IAgVePropagatorGreatArc propagator = groundVehicle.Route as IAgVePropagatorGreatArc;


Set ground vehicle to use Realtime propagator

[C#] Copy Code
// IAgGroundVehicle groundVehicle: Ground Vehicle object

// Set ground vehicle route to STK External propagator
groundVehicle.SetRouteType(AgEVePropagatorType.ePropagatorRealtime);

// Retrieve propagator interface if necessary
IAgVePropagatorRealtime propagator = groundVehicle.Route as IAgVePropagatorRealtime;


Set ground vehicle to use STK External propagator

[C#] Copy Code
// IAgGroundVehicle groundVehicle: Ground Vehicle object

// Set groundVehicle route to STK External propagator
groundVehicle.SetRouteType(AgEVePropagatorType.ePropagatorStkExternal);

// Retrieve propagator interface if necessary
IAgVePropagatorStkExternal propagator = groundVehicle.Route as IAgVePropagatorStkExternal;


Create a launch vehicle (on current scenario central body)

[C#] Copy Code
// IAgStkObjectRoot root: STK Object Model Root

// Create the Launch vehicle
IAgLaunchVehicle launchVehicle = root.CurrentScenario.Children.New(AgESTKObjectType.eLaunchVehicle,  "MyLaunchVehicle"as IAgLaunchVehicle;


Determine if trajectory type is supported

[C#] Copy Code
// IAgLaunchVehicle launchVehicle: Launch vehicle

bool supported = launchVehicle.IsTrajectoryTypeSupported(AgEVePropagatorType.ePropagatorRealtime);


Define missile trajectory

[C#] Copy Code
// IAgMissile missile: Chain object

// Set missile trajectory type
missile.SetTrajectoryType(AgEVePropagatorType.ePropagatorBallistic);

// Retrieve the Propagator interface
IAgVePropagatorBallistic trajectory = missile.Trajectory as IAgVePropagatorBallistic;

// Set propagator settings if they should be other than defaults
trajectory.EphemerisInterval.SetExplicitInterval("1 Jan 2012 12:00:00.000""2 Jan 2012 12:00:00.000");
trajectory.Step = 60.0;

// Set flight parameters
trajectory.SetLaunchType(AgEVeLaunch.eLaunchLLA);
IAgVeLaunchLLA launch = trajectory.Launch as IAgVeLaunchLLA;
launch.Lat = 0.0;
launch.Lon = 0.0;
launch.Alt = 0.0;

// Set impact location type
trajectory.SetImpactLocationType(AgEVeImpactLocation.eImpactLocationPoint);

// Retrieve the impact point interface
IAgVeImpactLocationPoint impactLocation = trajectory.ImpactLocation as IAgVeImpactLocationPoint;
impactLocation.SetLaunchControlType(AgEVeLaunchControl.eLaunchControlFixedTimeOfFlight);

// Retrieve the launch flight interface
IAgVeLaunchControlFixedTimeOfFlight launchControl = impactLocation.LaunchControl as IAgVeLaunchControlFixedTimeOfFlight;
launchControl.TimeOfFlight = 9000.0;

// Configure missile Impact parameters
impactLocation.SetImpactType(AgEVeImpact.eImpactLLA);
IAgVeImpactLLA impact = impactLocation.Impact as IAgVeImpactLLA;
impact.Lat = 12.0;
impact.Lon = 5.0;
impact.Alt = 0.0;

// Propagate Missile
trajectory.Propagate();


Create a satellite (on current scenario central body)

[C#] Copy Code
// IAgStkObjectRoot root: STK Object Model root

// Create the Satellite
IAgSatellite satellite = root.CurrentScenario.Children.New(AgESTKObjectType.eSatellite, "MySatellite"as IAgSatellite;


Create a satellite from an external ephemeris file (.e)

[C#] Copy Code
// IAgStkObjectRoot root: STK Object Model root
// String ephemerisFilePath: Path to external ephemeris data file

IAgSatellite satellite = root.CurrentScenario.Children.New(AgESTKObjectType.eSatellite, "MySatellite"as IAgSatellite;

// Configure propagator's external file path
satellite.SetPropagatorType(AgEVePropagatorType.ePropagatorStkExternal);
IAgVePropagatorStkExternal ext = satellite.Propagator as IAgVePropagatorStkExternal;
ext.Filename = ephemerisFilePath;

// Propagate
ext.Propagate();


Create a satellite from the satellite database

[C#] Copy Code
// IAgStkObjectRoot root: STK Object Model root

// Get STK database location using Connect
IAgExecCmdResult result = root.ExecuteCommand("GetDirectory / Database Satellite");
string satDataDir = result[0];
string filelocation = "\"" + Path.Combine(satDataDir, @"stkAllTLE.sd") + "\"";
string commonname = "\"hst\"";

// Import object from database using Connect
string command = String.Format("ImportFromDB * Satellite {0} Constellation ImportedFromSatDB Propagate On CommonName {1}", filelocation, commonname);
root.ExecuteCommand(command);


Set the satellite to use the GPS propagator

[C#] Copy Code
// IAgSatellite satellite: Satellite object

// Set propagator to GPS
satellite.SetPropagatorType(AgEVePropagatorType.ePropagatorGPS);

// Get the GPS propagator
IAgVePropagatorGPS propagator = satellite.Propagator as IAgVePropagatorGPS;


Set the satellite to use the HPOP propagator

[C#] Copy Code
// IAgSatellite satellite: Satellite object

// Set satellite propagator to HPOP
satellite.SetPropagatorType(AgEVePropagatorType.ePropagatorHPOP);

// Get the HPOP propagator
IAgVePropagatorHPOP propagator = satellite.Propagator as IAgVePropagatorHPOP;


Set the satellite to use the J2 propagator

[C#] Copy Code
// IAgSatellite satellite: Satellite object

// Set propagator to J2 Perturbation
satellite.SetPropagatorType(AgEVePropagatorType.ePropagatorJ2Perturbation);

// Get the J2 Perturbation propagator
IAgVePropagatorJ2Perturbation propagator = satellite.Propagator as IAgVePropagatorJ2Perturbation;


Set the satellite to use the LOP propagator

[C#] Copy Code
// IAgSatellite satellite: Satellite object

// Set satellite propagator to LOP
satellite.SetPropagatorType(AgEVePropagatorType.ePropagatorLOP);

// Get the LOP propagator
IAgVePropagatorLOP propagator = satellite.Propagator as IAgVePropagatorLOP;


Set the satellite to use the SGP4 propagator

[C#] Copy Code
// IAgSatellite satellite: Satellite object

// Set propagator to SGP4
satellite.SetPropagatorType(AgEVePropagatorType.ePropagatorSGP4);

// Get the SGP4 propagator
IAgVePropagatorSGP4 propagator = satellite.Propagator as IAgVePropagatorSGP4;


Set the satellite to use the SPICE propagator

[C#] Copy Code
// IAgSatellite satellite: Satellite object

// Set propagator to SPICE
satellite.SetPropagatorType(AgEVePropagatorType.ePropagatorSPICE);

// Get the SPICE propagator
IAgVePropagatorSPICE propagator = satellite.Propagator as IAgVePropagatorSPICE;



Set the satellite to use the STK External propagator

[C#] Copy Code
// IAgSatellite satellite: Satellite object

// Set propagator to STK External
satellite.SetPropagatorType(AgEVePropagatorType.ePropagatorStkExternal);

// Get the STK External propagator
IAgVePropagatorStkExternal propagator = satellite.Propagator as IAgVePropagatorStkExternal;


Create a ship (on current scenario central body)

[C#] Copy Code
// IAgStkObjectRoot root: STK Object Model Root

// Create the Ship
IAgShip ship = root.CurrentScenario.Children.New(AgESTKObjectType.eShip, "MyShip"as IAgShip;


Set ship to use Great Arc propagator

[C#] Copy Code
// IAgShip ship: Ship object

// Set ship route to great arc
ship.SetRouteType(AgEVePropagatorType.ePropagatorGreatArc);

// Retrieve propagator interface if necessary
IAgVePropagatorGreatArc propagator = ship.Route as IAgVePropagatorGreatArc;


Set ship to use Realtime propagator

[C#] Copy Code
// IAgShip ship: Ship object

// Set ship route to STK External propagator
ship.SetRouteType(AgEVePropagatorType.ePropagatorRealtime);

// Retrieve propagator interface if necessary
IAgVePropagatorRealtime propagator = ship.Route as IAgVePropagatorRealtime;


Set ship to use STK External propagator

[C#] Copy Code
// IAgShip ship: Ship object

// Set ship route to STK External propagator
ship.SetRouteType(AgEVePropagatorType.ePropagatorStkExternal);

// Retrieve propagator interface if necessary
IAgVePropagatorStkExternal propagator = ship.Route as IAgVePropagatorStkExternal;


Add an Attribute that provides a combobox of values from which the user can choose.

[C#] Copy Code

//Add the following code to your plugin
public object Choice { get; set; }
public object[] Choices = new object[4] { "0""1""2""3" };


public object GetPluginConfig(AGI.Attr.AgAttrBuilder pAttrBuilder)
{
    if (m_AgAttrScope == null)
    {
        m_AgAttrScope = pAttrBuilder.NewScope();
        pAttrBuilder.AddChoicesDispatchProperty(m_AgAttrScope, "Choice""A property""Choice", Choices);
    }

    return m_AgAttrScope;
}


Add an Attribute that provides a combobox of values populated by a function from which the user can choose.

[C#] Copy Code

//Add the following code to your plugin
public object Choice { get; set; }
public object[] Choices
{
    get
    {
        return new object[4] { "0""1""2""3" };
    }
}


public object GetPluginConfig(AGI.Attr.AgAttrBuilder pAttrBuilder)
{
    if (m_AgAttrScope == null)
    {
        m_AgAttrScope = pAttrBuilder.NewScope();
        pAttrBuilder.AddChoicesFuncDispatchProperty(m_AgAttrScope, "Choice""A property""Choice""Choices");
    }

    return m_AgAttrScope;
}


Shows the format of the Center parameter when creating a bounding sphere.

[C#] Copy Code
// IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Array center = new object[]
{
    1247.87,
    -4739.74,
    4067.77
};

IAgStkGraphicsBoundingSphere boundingSphere = sceneManager.Initializers.BoundingSphere.Initialize(ref center, 100);


Shows the format of the Size parameter when computing using a box triangulator.

[C#] Copy Code
// IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Array size = new object[]
{
    1000,
    1000,
    2000
};

IAgStkGraphicsSolidTriangulatorResult result = sceneManager.Initializers.BoxTriangulator.Compute(ref size);


Change view mode to use Earth's fixed frame

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root

scene.Camera.ViewCentralBody("Earth", root.VgtRoot.WellKnownAxes.Earth.Fixed);


Shows the format of the Camera's Position property.

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene

Array position = new object[]
{
    31378.1,
    0,
    0
};

scene.Camera.Position = position;


Shows the format of the Camera's ReferencePoint property.

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene

Array point = new object[]
{
    31378.1,
    0,
    0
};

scene.Camera.ReferencePoint = point;


Shows the format of the Camera's UpVector property.

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene

Array upVector = new object[]
{
    0,
    0,
    1
};

scene.Camera.UpVector = upVector;


Shows the format of the Extent parameter when zooming to a cartographic extent on a central body.

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene

Array extent = new object[]
{
    90,
    30,
    -77,
    39
};

scene.Camera.ViewExtent(
    "Earth",
    ref extent);


Shows the format of the Offset and UpAxis parameters when setting the camera's reference point with an offset.

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// IAgCrdnPoint point: A valid VGT point object.
// IAgCrdnAxes axes: A valid VGT axes object.

Array offset = new object[]
{
    50.0,
    50.0,
    -50.0
};

Array upAxis = new object[]
{
    0,
    0,
    1
};

scene.Camera.ViewOffsetWithUpAxis(
    axes,
    point,
    ref offset,
    ref upAxis);


Shows the format of the Position parameter when converting a cartogaphic position to a pixel coordinate.

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene

Array position = new object[]
{
    0.627,
    -1.644,
    0
};

Array windowPos = scene.Camera.CartographicToWindow(
    "Earth",
    ref position);


Shows the format of the Position parameter when converting a pixel coordinate to a cartographic position.

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene

Array position = new object[]
{
    150,
    116
};

Array cartographicPos = scene.Camera.WindowToCartographic(
    "Earth",
    ref position);


Take a snapshot of the camera's view

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;

//
// The snapshot can be saved to a file, texture, image, or the clipboard
//
IAgStkGraphicsRendererTexture2D texture = scene.Camera.Snapshot.SaveToTexture();

IAgStkGraphicsTextureScreenOverlay textureScreenOverlay = manager.Initializers.TextureScreenOverlay.InitializeWithXYTexture(00, texture);
IAgStkGraphicsOverlay overlay = (IAgStkGraphicsOverlay)textureScreenOverlay;
overlay.BorderSize = 2;
overlay.BorderColor = Color.White;
overlay.Scale = 0.2;
overlay.Origin = AgEStkGraphicsScreenOverlayOrigin.eStkGraphicsScreenOverlayOriginCenter;
IAgStkGraphicsScreenOverlayCollectionBase screenOverlayManager = (IAgStkGraphicsScreenOverlayCollectionBase)manager.ScreenOverlays;
screenOverlayManager.Add((IAgStkGraphicsScreenOverlay)overlay);


Shows the format of the ConvolutionFilter's Kernel property.

[C#] Copy Code
// IAgStkGraphicsConvolutionFilter convolutionFilter: A valid convolution filter

Array kernel = new object[] {
    111,
    111,
    111
};

convolutionFilter.Kernel = kernel;


Shows the format of the Kernel parameter when creating a convolution filter.

[C#] Copy Code
// IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Array kernel = new object[] {
    111,
    111,
    111
};

IAgStkGraphicsConvolutionFilter convolutionFilter = sceneManager.Initializers.ConvolutionFilter.InitializeWithKernel(ref kernel);


Shows the format of the distance to position display condition's Position property.

[C#] Copy Code
// IAgStkGraphicsDistanceToPositionDisplayCondition condition: A distance to position display condition

Array position = new object[]
{
    6700,
    0,
    0
};

condition.Position = position;


Shows the format of the Position parameter when creating a distance to position display condition.

[C#] Copy Code
// IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Array position = new object[]
{
    6700,
    0,
    0
};

IAgStkGraphicsDistanceToPositionDisplayCondition condition = sceneManager.Initializers.DistanceToPositionDisplayCondition.InitializeWithDistances(
    ref position,
    0,
    10000);


Draw a primitive based on a time interval

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root
// String globeOverlayFile: Location of the globe overlay file

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;

IAgStkGraphicsGeospatialImageGlobeOverlay overlay = manager.Initializers.GeospatialImageGlobeOverlay.InitializeWithString(globeOverlayFile);

IAgDate start = root.ConversionUtility.NewDate("UTCG""30 May 2008 14:30:00.000");
IAgDate end = root.ConversionUtility.NewDate("UTCG""30 May 2008 15:00:00.000");

((IAgScenario)root.CurrentScenario).Animation.StartTime = double.Parse(start.Subtract("sec"3600).Format("epSec"));

IAgStkGraphicsTimeIntervalDisplayCondition condition =
    manager.Initializers.TimeIntervalDisplayCondition.InitializeWithTimes(start, end);
((IAgStkGraphicsGlobeOverlay)overlay).DisplayCondition = condition as IAgStkGraphicsDisplayCondition;

scene.CentralBodies.Earth.Imagery.Add((IAgStkGraphicsGlobeImageOverlay)overlay);


Draw a primitive based on multiple conditions

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root
// String modelFile: Location of the model file
// IAgCrdnAxesFixed axes: An axes used to orient the model

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;
Array position = new object[] {29.98, -90.250.0 };

IAgStkGraphicsModelPrimitive model = manager.Initializers.ModelPrimitive.InitializeWithStringUri(
    modelFile);
model.SetPositionCartographic("Earth"ref position);
model.Scale = Math.Pow(101.5);

IAgDate start1 = root.ConversionUtility.NewDate("UTCG""30 May 2008 14:00:00.000");
IAgDate end1 = root.ConversionUtility.NewDate("UTCG""30 May 2008 14:30:00.000");
((IAgAnimation)root).CurrentTime = double.Parse(start1.Format("epSec"));
IAgDate start2 = root.ConversionUtility.NewDate("UTCG""30 May 2008 15:00:00.000");
IAgDate end2 = root.ConversionUtility.NewDate("UTCG""30 May 2008 15:30:00.000");

IAgStkGraphicsTimeIntervalDisplayCondition time1 = manager.Initializers.TimeIntervalDisplayCondition.InitializeWithTimes(start1, end1);
IAgStkGraphicsTimeIntervalDisplayCondition time2 = manager.Initializers.TimeIntervalDisplayCondition.InitializeWithTimes(start2, end2);
IAgStkGraphicsCompositeDisplayCondition composite = manager.Initializers.CompositeDisplayCondition.Initialize();

composite.Add((IAgStkGraphicsDisplayCondition)time1);
composite.Add((IAgStkGraphicsDisplayCondition)time2);
composite.LogicOperation = AgEStkGraphicsBinaryLogicOperation.eStkGraphicsBinaryLogicOperationOr;
((IAgStkGraphicsPrimitive)model).DisplayCondition = composite as IAgStkGraphicsDisplayCondition;

IAgCrdnAxesFindInAxesResult result = root.VgtRoot.WellKnownAxes.Earth.Fixed.FindInAxes(((IAgScenario)root.CurrentScenario).Epoch, ((IAgCrdnAxes)axes));
model.Orientation = result.Orientation;

manager.Primitives.Add((IAgStkGraphicsPrimitive)model);


Draw a primitive based on viewer altitude

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;
Array extent = new object[]
{
    -9429,
    -8933
};

IAgStkGraphicsSurfaceTriangulatorResult triangles = manager.Initializers.SurfaceExtentTriangulator.ComputeSimple("Earth"ref extent);

IAgStkGraphicsPolylinePrimitive line = manager.Initializers.PolylinePrimitive.Initialize();
Array boundaryPositions = triangles.BoundaryPositions;
line.Set(ref boundaryPositions);
((IAgStkGraphicsPrimitive)line).Color = Color.White;

IAgStkGraphicsAltitudeDisplayCondition condition = manager.Initializers.AltitudeDisplayCondition.InitializeWithAltitudes(5000002500000);
((IAgStkGraphicsPrimitive)line).DisplayCondition = condition as IAgStkGraphicsDisplayCondition;

manager.Primitives.Add((IAgStkGraphicsPrimitive)line);


Draw a primitive based on viewer distance

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root
// String modelFile: Location of the model file

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;
IAgStkGraphicsModelPrimitive model = manager.Initializers.ModelPrimitive.InitializeWithStringUri(
    modelFile);
Array position = new object[3] { 29.98, -90.258000.0 };
model.SetPositionCartographic("Earth"ref position);
model.Scale = Math.Pow(103);

IAgStkGraphicsDistanceDisplayCondition condition =
    manager.Initializers.DistanceDisplayCondition.InitializeWithDistances(200040000);
((IAgStkGraphicsPrimitive)model).DisplayCondition = condition as IAgStkGraphicsDisplayCondition;

manager.Primitives.Add((IAgStkGraphicsPrimitive)model);


Draw a screen overlay based on viewer distance

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root
// IAgStkGraphicsModelPrimitive model: A model
// IAgStkGraphicsScreenOverlay overlay: A overlay

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;
IAgStkGraphicsScreenOverlayCollectionBase overlayManager = (IAgStkGraphicsScreenOverlayCollectionBase)manager.ScreenOverlays.Overlays;

IAgStkGraphicsDistanceToPrimitiveDisplayCondition condition =
    manager.Initializers.DistanceToPrimitiveDisplayCondition.InitializeWithDistances(
    (IAgStkGraphicsPrimitive)model, 040000);
((IAgStkGraphicsOverlay)overlay).DisplayCondition = (IAgStkGraphicsDisplayCondition)condition;

manager.Primitives.Add((IAgStkGraphicsPrimitive)model);
overlayManager.Add(overlay);


Shows the format of the TimeInterval parameter when creating a time interval display condition.

[C#] Copy Code
// IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Array timeInterval = new object[]
{
    "1 Jan 2012 12:00:00.000",
    "1 Jan 2012 14:00:00.000"
};

sceneManager.Initializers.TimeIntervalDisplayCondition.InitializeWithTimeInterval(ref timeInterval);


Shows the format of the Radii parameter when computing using an ellipsoid triangulator.

[C#] Copy Code
// IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Array radii = new object[]
{
    2000,
    1000,
    1000
};

IAgStkGraphicsSolidTriangulatorResult result = sceneManager.Initializers.EllipsoidTriangulator.ComputeSimple(ref radii);


Shows the format of the BottomPositions and TopPositions parameters when computing using an extruded polyline triangulator with cartographic positions.

[C#] Copy Code
// IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Array bottomPositions = new object[]
{
    00200000,
    0.10.1200000,
    00.1200000,
    00200000
};

Array topPositions = new object[]
{
    0.10.1900000,
    0.20.2900000,
    0.10.2900000,
    0.10.1900000
};

IAgStkGraphicsExtrudedPolylineTriangulatorResult result = sceneManager.Initializers.ExtrudedPolylineTriangulator.ComputeCartographic(
    "Earth",
    ref bottomPositions,
    ref topPositions);


Shows the format of the BottomPositions and TopPositions parameters when computing using an extruded polyline triangulator.

[C#] Copy Code
// IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Array bottomPositions = new object[]
{
    6578.1400,
    6512.79653.458652.476,
    6545.27656.7180,
    6578.1400
};

Array topPositions = new object[]
{
    7205.81722.992722.36,
    6991.681417.281437.63,
    7097.631438.76722.36,
    7205.81722.992722.36
};

IAgStkGraphicsExtrudedPolylineTriangulatorResult result = sceneManager.Initializers.ExtrudedPolylineTriangulator.Compute(
    "Earth",
    ref bottomPositions,
    ref topPositions);


Shows the format of the Positions parameter when computing using an extruded polyline triangulator with altitudes and cartographic positions.

[C#] Copy Code
// IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Array positions = new object[]
{
    00200000,
    0.10.1200000,
    00.1200000,
    00200000
};

IAgStkGraphicsExtrudedPolylineTriangulatorResult result = sceneManager.Initializers.ExtrudedPolylineTriangulator.ComputeCartographicWithAltitudes(
    "Earth",
    ref positions,
    0,
    100);


Shows the format of the Positions parameter when computing using an extruded polyline triangulator with altitudes.

[C#] Copy Code
// IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Array positions = new object[]
{
    6578.1400,
    6512.79653.458652.476,
    6545.27656.7180,
    6578.1400
};

IAgStkGraphicsExtrudedPolylineTriangulatorResult result = sceneManager.Initializers.ExtrudedPolylineTriangulator.ComputeWithAltitudes(
    "Earth",
    ref positions,
    0,
    100);


Shows the format of the Positions parameter when computing using an extruded polyline triangulator with cartographic positions.

[C#] Copy Code
// IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Array positions = new object[]
{
    0, -0.007915000,
    -0.0078045000,
    00.007915000,
    0045000,
    0, -0.007915000
};

IAgStkGraphicsExtrudedPolylineTriangulatorResult result = sceneManager.Initializers.ExtrudedPolylineTriangulator.ComputeSingleConstantAltitudeCartographic(
    "Earth",
    ref positions,
    30000);


Shows the format of the Positions parameter when computing using an extruded polyline triangulator.

[C#] Copy Code
// IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Array positions = new object[]
{
    6392.94, -50.50530,
    6422.940, -49.7669,
    6392.9450.50530,
    6422.94049.7669,
    6392.94, -50.50530
};

IAgStkGraphicsExtrudedPolylineTriangulatorResult result = sceneManager.Initializers.ExtrudedPolylineTriangulator.ComputeSingleConstantAltitude(
    "Earth",
    ref positions,
    30000);


Add custom imagery to the globe

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;

IAgStkGraphicsCustomImageGlobeOverlayPluginActivator activator =
    manager.Initializers.CustomImageGlobeOverlayPluginActivator.Initialize();
IAgStkGraphicsCustomImageGlobeOverlayPluginProxy proxy =
    activator.CreateFromDisplayName("OpenStreetMapPlugin.CSharp");

IAgStkGraphicsCustomImageGlobeOverlay overlay = proxy.CustomImageGlobeOverlay;
scene.CentralBodies.Earth.Imagery.Add((IAgStkGraphicsGlobeImageOverlay)overlay);


Add jp2 imagery to the globe

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root
// String globeOverlayFile: The globe overlay file

//
// Either jp2 or pdttx can be used here
//
IAgStkGraphicsGlobeImageOverlay overlay = scene.CentralBodies.Earth.Imagery.AddUriString(globeOverlayFile);


Add terrain to the globe

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root
// String terrainOverlayFile: The terrain overlay file

IAgStkGraphicsTerrainOverlay overlay = scene.CentralBodies.Earth.Terrain.AddUriString(
    terrainOverlayFile);


Draw an image on top of another

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root
// String topOverlayFile: The top globe overlay file
// String bottomOverlayFile: The bottom globe overlay file

IAgStkGraphicsGlobeImageOverlay topOverlay = scene.CentralBodies.Earth.Imagery.AddUriString(topOverlayFile);
IAgStkGraphicsGlobeImageOverlay bottomOverlay = scene.CentralBodies.Earth.Imagery.AddUriString(bottomOverlayFile);

//
// Since bottom.jp2 was added after top.jp2, bottom.jp2 will be
// drawn on top.  In order to draw top.jp2 on top, we swap the Overlays.
//
scene.CentralBodies.Earth.Imagery.Swap(topOverlay, bottomOverlay);


Shows the format of the Extent parameter when creating a raster imgae globe overlay.

[C#] Copy Code
// IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Array extent = new object[]
{
    90,
    30,
    -77,
    39
};

IAgStkGraphicsRasterImageGlobeOverlay overlay = sceneManager.Initializers.RasterImageGlobeOverlay.InitializeWithColor(
    Color.Red,
    ref extent);


Adjust brightness, contrast, and gamma

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root
// String imageFile: The image file

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;
IAgStkGraphicsScreenOverlayCollectionBase overlayManager = (IAgStkGraphicsScreenOverlayCollectionBase)manager.ScreenOverlays.Overlays;
//
// The URI can be a file path, http, https, or ftp location
//
IAgStkGraphicsRaster image = manager.Initializers.Raster.InitializeWithStringUri(
    imageFile);

//
// Add brightness, contrast, and gamma correction filters to sequence
//
IAgStkGraphicsSequenceFilter sequenceFilter = manager.Initializers.SequenceFilter.Initialize();
sequenceFilter.Add((IAgStkGraphicsRasterFilter)manager.Initializers.BrightnessFilter.InitializeWithAdjustment(.1));
sequenceFilter.Add((IAgStkGraphicsRasterFilter)manager.Initializers.ContrastFilter.InitializeWithAdjustment(.2));
sequenceFilter.Add((IAgStkGraphicsRasterFilter)manager.Initializers.GammaCorrectionFilter.InitializeWithGamma(.9));
image.ApplyInPlace((IAgStkGraphicsRasterFilter)sequenceFilter);

IAgStkGraphicsRendererTexture2D texture = manager.Textures.FromRaster(image);

//
// Display the image using a screen overlay
//
IAgStkGraphicsTextureScreenOverlay overlay = manager.Initializers.TextureScreenOverlay.Initialize();
((IAgStkGraphicsOverlay)overlay).Width = 0.2;
((IAgStkGraphicsOverlay)overlay).WidthUnit = AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitFraction;
((IAgStkGraphicsOverlay)overlay).Height = 0.2;
((IAgStkGraphicsOverlay)overlay).HeightUnit = AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitFraction;
((IAgStkGraphicsOverlay)overlay).Origin = AgEStkGraphicsScreenOverlayOrigin.eStkGraphicsScreenOverlayOriginCenterRight;
overlay.Texture = texture;

overlayManager.Add((IAgStkGraphicsScreenOverlay)overlay);


Adjust the color levels of an image

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root
// String imageFile: The image file

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;
IAgStkGraphicsScreenOverlayCollectionBase overlayManager = (IAgStkGraphicsScreenOverlayCollectionBase)manager.ScreenOverlays.Overlays;
//
// The URI can be a file path, http, https, or ftp location
//
IAgStkGraphicsRaster image = manager.Initializers.Raster.InitializeWithStringUri(
    imageFile);

//
// Adjust the color levels of the image
//
IAgStkGraphicsLevelsFilter levelsFilter = manager.Initializers.LevelsFilter.Initialize();
levelsFilter.SetLevelAdjustment(AgEStkGraphicsRasterBand.eStkGraphicsRasterBandBlue, -255);
levelsFilter.SetLevelAdjustment(AgEStkGraphicsRasterBand.eStkGraphicsRasterBandGreen, -255);
image.ApplyInPlace((IAgStkGraphicsRasterFilter)levelsFilter);

IAgStkGraphicsRendererTexture2D texture = manager.Textures.FromRaster(image);

//
// Display the image using a screen overlay
//
IAgStkGraphicsTextureScreenOverlay overlay = manager.Initializers.TextureScreenOverlay.Initialize();
((IAgStkGraphicsOverlay)overlay).Width = 0.2;
((IAgStkGraphicsOverlay)overlay).WidthUnit = AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitFraction;
((IAgStkGraphicsOverlay)overlay).Height = 0.2;
((IAgStkGraphicsOverlay)overlay).HeightUnit = AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitFraction;
((IAgStkGraphicsOverlay)overlay).Origin = AgEStkGraphicsScreenOverlayOrigin.eStkGraphicsScreenOverlayOriginBottomRight;
overlay.Texture = texture;

overlayManager.Add((IAgStkGraphicsScreenOverlay)overlay);


Blur an image with a convolution matrix

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root
// String imageFile: The image file

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;
IAgStkGraphicsScreenOverlayCollectionBase overlayManager = (IAgStkGraphicsScreenOverlayCollectionBase)manager.ScreenOverlays.Overlays;
//
// The URI can be a file path, http, https, or ftp location
//
IAgStkGraphicsRaster image = manager.Initializers.Raster.InitializeWithStringUri(
    imageFile);

//
// Set convolution matrix to blur
//
Array kernel = new object[]
    {
        111,
        111,
        111
    };
IAgStkGraphicsConvolutionFilter convolutionMatrix = manager.Initializers.ConvolutionFilter.InitializeWithKernelAndDivisor(ref kernel, 9.0);
image.ApplyInPlace((IAgStkGraphicsRasterFilter)convolutionMatrix);

IAgStkGraphicsRendererTexture2D texture = manager.Textures.FromRaster(image);

//
// Display the image using a screen overlay
//
IAgStkGraphicsTextureScreenOverlay overlay = manager.Initializers.TextureScreenOverlay.Initialize();
((IAgStkGraphicsOverlay)overlay).Width = 0.2;
((IAgStkGraphicsOverlay)overlay).WidthUnit = AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitFraction;
((IAgStkGraphicsOverlay)overlay).Height = 0.2;
((IAgStkGraphicsOverlay)overlay).HeightUnit = AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitFraction;
((IAgStkGraphicsOverlay)overlay).Origin = AgEStkGraphicsScreenOverlayOrigin.eStkGraphicsScreenOverlayOriginBottomLeft;
overlay.Texture = texture;

overlayManager.Add((IAgStkGraphicsScreenOverlay)overlay);


Extract the alpha component from an image

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root
// String imageFile: The image file

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;
IAgStkGraphicsScreenOverlayCollectionBase overlayManager = (IAgStkGraphicsScreenOverlayCollectionBase)manager.ScreenOverlays.Overlays;
//
// The URI can be a file path, http, https, or ftp location
//
IAgStkGraphicsRaster image = manager.Initializers.Raster.InitializeWithStringUri(
    imageFile);

//
// Extract the alpha channel from the image
//
IAgStkGraphicsBandExtractFilter channelExtract = manager.Initializers.BandExtractFilter.InitializeWithBand(AgEStkGraphicsRasterBand.eStkGraphicsRasterBandAlpha);
image.ApplyInPlace((IAgStkGraphicsRasterFilter)channelExtract);

IAgStkGraphicsRendererTexture2D texture = manager.Textures.FromRaster(image);

//
// Display the image using a screen overlay
//
IAgStkGraphicsTextureScreenOverlay overlay = manager.Initializers.TextureScreenOverlay.Initialize();
((IAgStkGraphicsOverlay)overlay).Width = 0.2;
((IAgStkGraphicsOverlay)overlay).WidthUnit = AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitFraction;
((IAgStkGraphicsOverlay)overlay).Height = 0.2;
((IAgStkGraphicsOverlay)overlay).HeightUnit = AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitFraction;
((IAgStkGraphicsOverlay)overlay).Origin = AgEStkGraphicsScreenOverlayOrigin.eStkGraphicsScreenOverlayOriginTopRight;
overlay.Texture = texture;

overlayManager.Add((IAgStkGraphicsScreenOverlay)overlay);


Flip an image

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root
// String imageFile: The image file

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;
IAgStkGraphicsScreenOverlayCollectionBase overlayManager = (IAgStkGraphicsScreenOverlayCollectionBase)manager.ScreenOverlays.Overlays;
//
// The URI can be a file path, http, https, or ftp location
//
IAgStkGraphicsRaster image = manager.Initializers.Raster.InitializeWithStringUri(
    imageFile);
image.Flip(AgEStkGraphicsFlipAxis.eStkGraphicsFlipAxisVertical);

IAgStkGraphicsRendererTexture2D texture = manager.Textures.FromRaster(image);

IAgStkGraphicsTextureScreenOverlay overlay = manager.Initializers.TextureScreenOverlay.Initialize();
((IAgStkGraphicsOverlay)overlay).Size = new object[]
{
    0.20.2,
    AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitFraction,
    AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitFraction
};
((IAgStkGraphicsOverlay)overlay).Origin = AgEStkGraphicsScreenOverlayOrigin.eStkGraphicsScreenOverlayOriginTopLeft;
overlay.Texture = texture;

overlayManager.Add((IAgStkGraphicsScreenOverlay)overlay);


Load and display a raster stream

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root
// String imageFile: Image file to use for the raster

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;
IAgStkGraphicsScreenOverlayCollectionBase overlayManager = (IAgStkGraphicsScreenOverlayCollectionBase)manager.ScreenOverlays.Overlays;

//
// Create the RasterStream from the plugin
//
IAgStkGraphicsProjectionRasterStreamPluginActivator activator =
    manager.Initializers.ProjectionRasterStreamPluginActivator.Initialize();
IAgStkGraphicsProjectionRasterStreamPluginProxy proxy =
    activator.CreateFromDisplayName("ProjectionRasterStreamPlugin.CSharp");

//
// Use reflection to set the plugin's properties
//
Type plugin = proxy.RealPluginObject.GetType();
plugin.GetProperty("RasterPath").SetValue(proxy.RealPluginObject, imageFile, null);

IAgStkGraphicsRasterStream rasterStream = proxy.RasterStream;
rasterStream.UpdateDelta = 0.01667;

//
// Creates the texture screen overlay to display the raster
//
IAgStkGraphicsRendererTexture2D texture = manager.Textures.FromRaster((IAgStkGraphicsRaster)rasterStream);
IAgStkGraphicsTextureScreenOverlay overlay =
    manager.Initializers.TextureScreenOverlay.InitializeWithXYWidthHeight(00,
    texture.Template.Width, texture.Template.Height);
overlay.Texture = texture;
((IAgStkGraphicsOverlay)overlay).Origin = AgEStkGraphicsScreenOverlayOrigin.eStkGraphicsScreenOverlayOriginCenterLeft;

overlayManager.Add((IAgStkGraphicsScreenOverlay)overlay);


Swizzle an image's components

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root
// String imageFile: The image file

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;
IAgStkGraphicsScreenOverlayCollectionBase overlayManager = (IAgStkGraphicsScreenOverlayCollectionBase)manager.ScreenOverlays.Overlays;
//
// The URI can be a file path, http, https, or ftp location
//
IAgStkGraphicsRaster image = manager.Initializers.Raster.InitializeWithStringUri(
    imageFile);

//
// Swizzle RGBA to BGRA
//
IAgStkGraphicsBandOrderFilter channelOrder = manager.Initializers.BandOrderFilter.InitializeWithOrder(AgEStkGraphicsRasterFormat.eStkGraphicsRasterFormatBgra);
image.ApplyInPlace((IAgStkGraphicsRasterFilter)channelOrder);

IAgStkGraphicsRendererTexture2D texture = manager.Textures.FromRaster(image);

//
// Display the image using a screen overlay
//
IAgStkGraphicsTextureScreenOverlay overlay = manager.Initializers.TextureScreenOverlay.Initialize();
((IAgStkGraphicsOverlay)overlay).Width = 0.2;
((IAgStkGraphicsOverlay)overlay).WidthUnit = AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitFraction;
((IAgStkGraphicsOverlay)overlay).Height = 0.2;
((IAgStkGraphicsOverlay)overlay).HeightUnit = AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitFraction;
((IAgStkGraphicsOverlay)overlay).Origin = AgEStkGraphicsScreenOverlayOrigin.eStkGraphicsScreenOverlayOriginTopCenter;
overlay.Texture = texture;

overlayManager.Add((IAgStkGraphicsScreenOverlay)overlay);


Shows the format of the Extent and SubExtent parameters when writing using a Jpeg 2000 Writer.

[C#] Copy Code
// IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager
// String imagePath: Path to the image to write
// String saveFile: Path to the output file

Array extent = new object[]
{
    -1,
    -1,
    1,
    1
};

Array subExtent = new object[]
{
    -0.5,
    -0.5,
    0.5,
    0.5
};

sceneManager.Initializers.Jpeg2000Writer.WriteExtentAndSubExtentString(
    imagePath,
    ref extent,
    ref subExtent,
    AgEStkGraphicsJpeg2000CompressionProfile.eStkGraphicsJpeg2000CompressionProfileDefault,
    1,
    saveFile,
    true);


Shows the format of the model's Position property.

[C#] Copy Code
// IAgStkGraphicsModelPrimitive model: A model primitive

Array position = new object[]
{
    31378.1,
    0,
    0
};

model.Position = position;


Shows the format of the Position parameter when updating a model.

[C#] Copy Code
// IAgStkGraphicsModelPrimitive model: A model primitive

Array position = new object[]
{
    39.88,
    -75.25,
    0
};

model.SetPositionCartographic(
    "Earth",
    ref position);


Shows the format of the overlay's MaximumSize property.

[C#] Copy Code
// IAgStkGraphicsOverlay overlay: A valid overlay object.

Array maximumSize = new object[]
{
    500,
    500,
    AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitPixels,
    AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitPixels
};

overlay.MaximumSize = maximumSize;


Shows the format of the overlay's MinimumSize property.

[C#] Copy Code
// IAgStkGraphicsOverlay overlay: A valid overlay object.

Array minimumSize = new object[]
{
    5,
    5,
    AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitPixels,
    AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitPixels
};

overlay.MinimumSize = minimumSize;


Shows the format of the overlay's Padding property.

[C#] Copy Code
// IAgStkGraphicsOverlay overlay: A valid overlay object.

Array padding = new object[]
{
    10,
    10,
    10,
    10
};

overlay.Padding = padding;


Shows the format of the overlay's PinningPosition property.

[C#] Copy Code
// IAgStkGraphicsOverlay overlay: A valid overlay object.

Array pinningPosition = new object[]
{
    5,
    5,
    AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitPixels,
    AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitPixels
};

overlay.PinningPosition = pinningPosition;


Shows the format of the overlay's Position property.

[C#] Copy Code
// IAgStkGraphicsOverlay overlay: A valid overlay object.

Array position = new object[]
{
    50,
    50,
    AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitPixels,
    AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitPixels
};

overlay.Position = position;


Shows the format of the overlay's RotationPoint property.

[C#] Copy Code
// IAgStkGraphicsOverlay overlay: A valid overlay object.

Array rotationPoint = new object[]
{
    false,
    AgEStkGraphicsScreenOverlayOrigin.eStkGraphicsScreenOverlayOriginCenter,
    true,
    0.0,
    0.0,
    AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitPixels,
    AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitPixels
};

overlay.RotationPoint = rotationPoint;


Shows the format of the overlay's Size property.

[C#] Copy Code
// IAgStkGraphicsOverlay overlay: A valid overlay object.

Array size = new object[]
{
    300,
    300,
    AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitPixels,
    AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitPixels
};

overlay.Size = size;


Shows the format of the path point's Position property.

[C#] Copy Code
// IAgStkGraphicsPathPoint path: A valid path point object

Array position = new object[]
{
    1089235,
    -4800930,
    4046386
};

path.Position = position;


Shows the format of the Position parameter when creating a path point.

[C#] Copy Code
// AgStkObjectRoot root: STK Object Model root
// IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Array position = new object[]
{
    1089235,
    -4800930,
    4046386
};

IAgStkGraphicsPathPoint path = sceneManager.Initializers.PathPoint.InitializeWithDateAndPosition(
    root.ConversionUtility.NewDate("UTCG", ((IAgScenario)root.CurrentScenario).StartTime.ToString()),
    ref position);


Change a model's color on mouse over

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root
// IAgStkGraphicsPrimitive m_SelectedModel: The previously selected model

//
// Get a collection of picked objects under the mouse location.
// The collection is sorted with the closest object at index zero.
//
IAgStkGraphicsPickResultCollection collection = scene.Pick(mouseX, mouseY);
if (collection.Count != 0)
{
    IAgStkGraphicsObjectCollection objects = collection[0].Objects;
    IAgStkGraphicsCompositePrimitive composite = objects[0as IAgStkGraphicsCompositePrimitive;

    //
    // Was a model in our composite picked?
    //
    if (composite == m_Models)
    {
        IAgStkGraphicsPrimitive model = objects[1as IAgStkGraphicsPrimitive;

        //
        // Selected Model
        //
        model.Color = Color.Cyan;

        if (model != m_SelectedModel)
        {
            //
            // Unselect previous model
            //
            if (m_SelectedModel != null)
            {
                m_SelectedModel.Color = Color.Red;
            }
            m_SelectedModel = model;
            scene.Render();
        }
        return;
   }
}

//
// Unselect previous model
//
if (m_SelectedModel != null)
{
    m_SelectedModel.Color = Color.Red;
    m_SelectedModel = null;
    scene.Render();
}


Change model colors within a rectangular region

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root
// List<IAgStkGraphicsModelPrimitive> SelectedModels: The previously selected models

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;
//
// Get a collection of picked objects in a 100 by 100 rectangular region.
// The collection is sorted with the closest object at index zero.
//
List<IAgStkGraphicsModelPrimitive> newModels = new List<IAgStkGraphicsModelPrimitive>();
IAgStkGraphicsPickResultCollection collection = scene.PickRectangular(mouseX - 50, mouseY + 50, mouseX + 50, mouseY - 50);
foreach (IAgStkGraphicsPickResult pickResult in collection)
{
    IAgStkGraphicsObjectCollection objects = pickResult.Objects;
    IAgStkGraphicsCompositePrimitive composite = objects[0as IAgStkGraphicsCompositePrimitive;

    //
    // Was a model in our composite picked?
    //
    if (composite == m_Models)
    {
        IAgStkGraphicsModelPrimitive model = objects[1as IAgStkGraphicsModelPrimitive;

        //
        // Selected Model
        //
        ((IAgStkGraphicsPrimitive)model).Color = Color.Cyan;
        newModels.Add(model);
    }
}
//
// Reset color of models that were previous selected but were not in this pick.
//
foreach (IAgStkGraphicsModelPrimitive selectedModel in SelectedModels)
{
    if (!newModels.Contains(selectedModel))
    {
        ((IAgStkGraphicsPrimitive)selectedModel).Color = Color.Red;
    }
}
SelectedModels = newModels;

manager.Render();



Zoom to a model on double click

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root

IAgStkGraphicsPrimitive selectedModel = null;
//
// Get a collection of picked objects under the mouse location.
// The collection is sorted with the closest object at index zero.
//
IAgStkGraphicsPickResultCollection collection = scene.Pick(mouseX, mouseY);
if (collection.Count != 0)
{
    IAgStkGraphicsObjectCollection objects = collection[0].Objects;
    IAgStkGraphicsCompositePrimitive composite = objects[0as IAgStkGraphicsCompositePrimitive;

    //
    // Was a model in our composite picked?
    //
    if (composite == m_Models)
    {
        selectedModel = objects[1as IAgStkGraphicsPrimitive;
    }
}


Zoom to a particular marker in a batch

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root
// String markerFile: The file to use for the markers
// IList<Array> markerPositions: A list of the marker positions

Array selectedMarkerCartesianPosition = null;
//
// Get a collection of picked objects under the mouse location.
// The collection is sorted with the closest object at index zero.
//
IAgStkGraphicsPickResultCollection collection = scene.Pick(mouseX, mouseY);
if (collection.Count != 0)
{
    IAgStkGraphicsObjectCollection objects = collection[0].Objects;
    IAgStkGraphicsMarkerBatchPrimitive batchPrimitive = objects[0as IAgStkGraphicsMarkerBatchPrimitive;

    //
    // Was a marker in our marker batch picked?
    //
    if (batchPrimitive == m_MarkerBatch)
    {
        //
        // Get the index of the particular marker we picked
        //
        IAgStkGraphicsBatchPrimitiveIndex markerIndex = objects[1as IAgStkGraphicsBatchPrimitiveIndex;

        //
        // Get the position of the particular marker we picked
        //
        Array markerCartographic = markerPositions[markerIndex.Index];

        IAgPosition markerPosition = root.ConversionUtility.NewPositionOnEarth();
        markerPosition.AssignPlanetodetic(
            (double)markerCartographic.GetValue(0),
            (double)markerCartographic.GetValue(1),
            (double)markerCartographic.GetValue(2));

        double x, y, z;
        markerPosition.QueryCartesian(out x, out y, out z);

        selectedMarkerCartesianPosition = new object[] { x, y, z };
    }
}


IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;

IList<Array> positions = new List<Array>();
positions.Add(new object[] {39.88, -75.253000.0 });
positions.Add(new object[] {38.85, -77.043000.0 });
positions.Add(new object[] {38.85, -77.040.0 });
positions.Add(new object[] {29.98, -90.250.0 });
positions.Add(new object[] {37.37, -121.920.0 });

Array positionsArray = Array.CreateInstance(typeof(object), positions.Count * 3);
for (int i = 0; i < positions.Count; ++i)
{
    Array position = positions[i];
    position.CopyTo(positionsArray, i * 3);
}

IAgStkGraphicsMarkerBatchPrimitive markerBatch = manager.Initializers.MarkerBatchPrimitive.Initialize();
markerBatch.Texture = manager.Textures.LoadFromStringUri(
    markerFile);
markerBatch.SetCartographic("Earth"ref positionsArray);

// Save the positions of the markers for use in the pick event
markerPositions = positions;

// Enable per item picking
markerBatch.PerItemPickingEnabled = true;

manager.Primitives.Add((IAgStkGraphicsPrimitive)markerBatch);


Shows the format of the Positions parameter when interpolating positions.

[C#] Copy Code
// IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

IAgStkGraphicsPositionInterpolator interpolator = sceneManager.Initializers.GreatArcInterpolator.InitializeWithCentralBody("Earth"as IAgStkGraphicsPositionInterpolator;

Array positions = new object[]
{
    39.88, -75.250,
    38.85, -77.040,
};

Array results = interpolator.Interpolate(ref positions);


Create layers of primitives

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root
// String modelFile: Location of the model file
// String markerFile: The file to use for the marker batch

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;

Random r = new Random();
const int modelCount = 25;

Array positions = Array.CreateInstance(typeof(object), modelCount * 3);

//
// Create the models
//
IAgStkGraphicsCompositePrimitive models = manager.Initializers.CompositePrimitive.Initialize();

for (int i = 0; i < modelCount; ++i)
{
    double latitude = 35 + 1.5 * r.NextDouble();
    double longitude = -(80 + 1.5 * r.NextDouble());
    double altitude = 0;
    Array position = new object[3]{latitude, longitude, altitude};

    positions.SetValue(latitude, 3 * i);
    positions.SetValue(longitude, (3 * i) + 1);
    positions.SetValue(altitude, (3 * i) + 2);

    IAgStkGraphicsModelPrimitive model = manager.Initializers.ModelPrimitive.InitializeWithStringUri(modelFile);
    model.SetPositionCartographic("Earth"ref position);
    model.Scale = Math.Pow(102);
    models.Add((IAgStkGraphicsPrimitive)model);
}

//
// Create the markers
//
IAgStkGraphicsMarkerBatchPrimitive markers = manager.Initializers.MarkerBatchPrimitive.Initialize();
markers.RenderPass = AgEStkGraphicsMarkerBatchRenderPass.eStkGraphicsMarkerBatchRenderPassTranslucent;

markers.Texture = manager.Textures.LoadFromStringUri(markerFile);
markers.SetCartographic("Earth"ref positions);

//
// Create the points
//
IAgStkGraphicsPointBatchPrimitive points = manager.Initializers.PointBatchPrimitive.Initialize();
points.PixelSize = 5;
Array colors = Array.CreateInstance(typeof(object), modelCount);
for (int i = 0; i < colors.Length; i++)
    colors.SetValue(Color.Orange.ToArgb(), i);
points.SetCartographicWithColorsAndRenderPass("Earth"ref positions, ref colors, AgEStkGraphicsRenderPassHint.eStkGraphicsRenderPassHintOpaque);

//
// Set the display Conditions
//
IAgStkGraphicsAltitudeDisplayCondition near = manager.Initializers.AltitudeDisplayCondition.InitializeWithAltitudes(0500000);
((IAgStkGraphicsPrimitive)models).DisplayCondition = (IAgStkGraphicsDisplayCondition)near;

IAgStkGraphicsAltitudeDisplayCondition medium = manager.Initializers.AltitudeDisplayCondition.InitializeWithAltitudes(5000002000000);
((IAgStkGraphicsPrimitive)markers).DisplayCondition = (IAgStkGraphicsDisplayCondition)medium;

IAgStkGraphicsAltitudeDisplayCondition far = manager.Initializers.AltitudeDisplayCondition.InitializeWithAltitudes(20000004000000);
((IAgStkGraphicsPrimitive)points).DisplayCondition = (IAgStkGraphicsDisplayCondition)far;

manager.Primitives.Add((IAgStkGraphicsPrimitive)models);
manager.Primitives.Add((IAgStkGraphicsPrimitive)markers);
manager.Primitives.Add((IAgStkGraphicsPrimitive)points);


Z-order primitives on the surface

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root
// Array pennsylvaniaPositions: Pennsylvania positions
// Array areaCode610Positions: Area Code 610 positions
// Array areaCode215Positions: Area Code 215 positions
// Array schuylkillPositions: Schuylkill positions

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;

IAgStkGraphicsTriangleMeshPrimitive pennsylvania = manager.Initializers.TriangleMeshPrimitive.Initialize();
pennsylvania.SetTriangulator((IAgStkGraphicsTriangulatorResult)manager.Initializers.SurfacePolygonTriangulator.Compute(
    "Earth"ref pennsylvaniaPositions));
((IAgStkGraphicsPrimitive)pennsylvania).Color = Color.Yellow;

IAgStkGraphicsTriangleMeshPrimitive areaCode610 = manager.Initializers.TriangleMeshPrimitive.Initialize();
areaCode610.SetTriangulator((IAgStkGraphicsTriangulatorResult)manager.Initializers.SurfacePolygonTriangulator.Compute(
    "Earth"ref areaCode610Positions));
((IAgStkGraphicsPrimitive)areaCode610).Color = Color.DarkRed;

IAgStkGraphicsTriangleMeshPrimitive areaCode215 = manager.Initializers.TriangleMeshPrimitive.Initialize();
areaCode215.SetTriangulator((IAgStkGraphicsTriangulatorResult)manager.Initializers.SurfacePolygonTriangulator.Compute(
    "Earth"ref areaCode215Positions));
((IAgStkGraphicsPrimitive)areaCode215).Color = Color.Green;

IAgStkGraphicsPolylinePrimitive schuylkillRiver = manager.Initializers.PolylinePrimitive.Initialize();
schuylkillRiver.Set(ref schuylkillPositions);
((IAgStkGraphicsPrimitive)schuylkillRiver).Color = Color.Blue;
schuylkillRiver.Width = 2;

IAgStkGraphicsCompositePrimitive composite = manager.Initializers.CompositePrimitive.Initialize();
composite.Add((IAgStkGraphicsPrimitive)pennsylvania);
composite.Add((IAgStkGraphicsPrimitive)areaCode610);
composite.Add((IAgStkGraphicsPrimitive)areaCode215);
composite.Add((IAgStkGraphicsPrimitive)schuylkillRiver);

manager.Primitives.Add((IAgStkGraphicsPrimitive)composite);


Draw a set of markers

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root
// String markerImageFile: The image file to use for the markers

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;

Array positions = new object[]
{
    39.88, -75.250,    // Philadelphia
    38.85, -77.040// Washington, D.C.
    29.98, -90.250// New Orleans
    37.37, -121.920    // San Jose
};

IAgStkGraphicsMarkerBatchPrimitive markerBatch = manager.Initializers.MarkerBatchPrimitive.Initialize();
markerBatch.Texture = manager.Textures.LoadFromStringUri(
    markerImageFile);
markerBatch.SetCartographic("Earth"ref positions);

manager.Primitives.Add((IAgStkGraphicsPrimitive)markerBatch);


Shows the format of the Colors parameter when setting per marker colors.

[C#] Copy Code
// IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Array colors = new object[]
{
    Color.Red.ToArgb(),
    Color.Green.ToArgb(),
    Color.Blue.ToArgb(),
    Color.White.ToArgb()
};

IAgStkGraphicsMarkerBatchPrimitiveOptionalParameters parameters = sceneManager.Initializers.MarkerBatchPrimitiveOptionalParameters.Initialize();
parameters.SetColors(ref colors);


Shows the format of the Colors, Positions and Indices parameters when updating a marker batch primitive with cartographic positions.

[C#] Copy Code
// IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager
// IAgStkGraphicsMarkerBatchPrimitive markerBatch: A marker batch primitive

Array colors = new object[]
{
    Color.Red.ToArgb(),
    Color.Green.ToArgb(),
    Color.Blue.ToArgb(),
    Color.White.ToArgb()
};

IAgStkGraphicsMarkerBatchPrimitiveOptionalParameters parameters = sceneManager.Initializers.MarkerBatchPrimitiveOptionalParameters.Initialize();
parameters.SetColors(ref colors);

Array positions = new object[]
{
    39.88, -75.250,
    38.85, -77.040,
    29.98, -90.250,
    37.37, -121.920
};

Array indices = new object[]
{
    0,
    1,
    2,
    3
};

markerBatch.SetPartialCartographicWithOptionalParametersIndicesOrderAndRenderPass(
    "Earth",
    ref positions,
    parameters,
    ref indices,
    AgEStkGraphicsIndicesOrderHint.eStkGraphicsIndicesOrderHintSortedAscending,
    AgEStkGraphicsRenderPassHint.eStkGraphicsRenderPassHintOpaque);


Shows the format of the Colors, Positions and Indices parameters when updating a marker batch primitive.

[C#] Copy Code
// IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager
// IAgStkGraphicsMarkerBatchPrimitive markerBatch: A marker batch primitive

Array colors = new object[]
{
    Color.Red.ToArgb(),
    Color.Green.ToArgb(),
    Color.Blue.ToArgb(),
    Color.White.ToArgb()
};

IAgStkGraphicsMarkerBatchPrimitiveOptionalParameters parameters = sceneManager.Initializers.MarkerBatchPrimitiveOptionalParameters.Initialize();
parameters.SetColors(ref colors);

Array positions = new object[]
{
    1247.87, -4739.744067.77,
    1115.48, -4847.093979.36,
    -24.12, -5529.313168.45,
    -2683.42, -4307.743850.11
};

Array indices = new object[]
{
    0,
    1,
    2,
    3
};

markerBatch.SetPartialWithOptionalParametersIndicesOrderAndRenderPass(
    ref positions,
    parameters,
    ref indices,
    AgEStkGraphicsIndicesOrderHint.eStkGraphicsIndicesOrderHintSortedAscending,
    AgEStkGraphicsRenderPassHint.eStkGraphicsRenderPassHintOpaque);


Shows the format of the EyeOffsets parameter when setting per marker eye offsets.

[C#] Copy Code
// IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Array eyeoffset = new object[]
{
    234,
    234
};

IAgStkGraphicsMarkerBatchPrimitiveOptionalParameters parameters = sceneManager.Initializers.MarkerBatchPrimitiveOptionalParameters.Initialize();
parameters.SetEyeOffsets(ref eyeoffset);


Shows the format of the marker batch's EyeOffset property.

[C#] Copy Code
// IAgStkGraphicsMarkerBatchPrimitive markerBatch: A marker batch primitive

Array eyeoffset = new object[]
{
    2,
    3,
    4
};

markerBatch.EyeOffset = eyeoffset;


Shows the format of the marker batch's PixelOffset property.

[C#] Copy Code
// IAgStkGraphicsMarkerBatchPrimitive markerBatch: A marker batch primitive

Array pixelOffset = new object[]
{
    1,
    2
};

markerBatch.PixelOffset = pixelOffset;


Shows the format of the marker batch's Size property.

[C#] Copy Code
// IAgStkGraphicsMarkerBatchPrimitive markerBatch: A marker batch primitive

Array size = new object[]
{
    256,
    128
};

markerBatch.Size = size;


Shows the format of the marker batch's TextureCoordinate property.

[C#] Copy Code
// IAgStkGraphicsMarkerBatchPrimitive markerBatch: A marker batch primitive

Array coordinates = new object[]
{
    0,
    0,
    1,
    1
};

markerBatch.TextureCoordinate = coordinates;


Shows the format of the Origins parameter when setting per marker origins.

[C#] Copy Code
// IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Array origins = new object[]
{
    AgEStkGraphicsOrigin.eStkGraphicsOriginCenter,
    AgEStkGraphicsOrigin.eStkGraphicsOriginBottomLeft,
    AgEStkGraphicsOrigin.eStkGraphicsOriginBottomRight,
    AgEStkGraphicsOrigin.eStkGraphicsOriginTopLeft
};

IAgStkGraphicsMarkerBatchPrimitiveOptionalParameters parameters = sceneManager.Initializers.MarkerBatchPrimitiveOptionalParameters.Initialize();
parameters.SetOrigins(ref origins);


Shows the format of the PixelOffsets parameter when setting per marker pixel offsets.

[C#] Copy Code
// IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Array pixelOffset = new object[]
{
    12,
    21
};

IAgStkGraphicsMarkerBatchPrimitiveOptionalParameters parameters = sceneManager.Initializers.MarkerBatchPrimitiveOptionalParameters.Initialize();
parameters.SetPixelOffsets(ref pixelOffset);


Shows the format of the RotationAngles parameter when setting per marker rotations.

[C#] Copy Code
// IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Array rotations = new object[]
{
    15,
    30,
    45,
    60
};

IAgStkGraphicsMarkerBatchPrimitiveOptionalParameters parameters = sceneManager.Initializers.MarkerBatchPrimitiveOptionalParameters.Initialize();
parameters.SetRotations(ref rotations);


Shows the format of the Sizes parameter when setting per marker sizes.

[C#] Copy Code
// IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Array size = new object[]
{
    256,
    128,
    128,
    256
};

IAgStkGraphicsMarkerBatchPrimitiveOptionalParameters parameters = sceneManager.Initializers.MarkerBatchPrimitiveOptionalParameters.Initialize();
parameters.SetSizes(ref size);


Shows the format of the TextureCoordinates parameter when setting per marker texture coordinates.

[C#] Copy Code
// IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Array coordinates = new object[]
{
    0011,
    1100
};

IAgStkGraphicsMarkerBatchPrimitiveOptionalParameters parameters = sceneManager.Initializers.MarkerBatchPrimitiveOptionalParameters.Initialize();
parameters.SetTextureCoordinates(ref coordinates);


Shows the format of the Textures parameter when setting per marker textures.

[C#] Copy Code
// IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager
// String texturePath1: Path to the first texture file
// String texturePath2: Path to the second texture file
// String texturePath3: Path to the third texture file
// String texturePath4: Path to the fourth texture file

Array textures = new object[]
{
    sceneManager.Textures.LoadFromStringUri(texturePath1),
    sceneManager.Textures.LoadFromStringUri(texturePath2),
    sceneManager.Textures.LoadFromStringUri(texturePath3),
    sceneManager.Textures.LoadFromStringUri(texturePath4)
};

IAgStkGraphicsMarkerBatchPrimitiveOptionalParameters parameters = sceneManager.Initializers.MarkerBatchPrimitiveOptionalParameters.Initialize();
parameters.SetTextures(ref textures);


Draw a Collada model with user defined lighting

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root
// String modelFile: The model file

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;
IAgStkGraphicsModelPrimitive model = manager.Initializers.ModelPrimitive.InitializeWithStringUri(
    modelFile);

Array position = new object[] { 39.88, -75.25500000.0 };
model.SetPositionCartographic("Earth"ref position);
model.Scale = Math.Pow(102);

manager.Primitives.Add((IAgStkGraphicsPrimitive)model);


Draw a Collada or MDL model

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root
// String modelFile: The model file

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;
IAgStkGraphicsModelPrimitive model = manager.Initializers.ModelPrimitive.InitializeWithStringUri(
    modelFile);

Array position = new object[] { 39.88, -75.255000.0 };
model.SetPositionCartographic("Earth"ref position);
model.Scale = Math.Pow(102);

manager.Primitives.Add((IAgStkGraphicsPrimitive)model);


Draw a dynamically textured Collada model

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root
// String modelFile: The model file

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;
IAgStkGraphicsModelPrimitive model = manager.Initializers.ModelPrimitive.InitializeWithStringUri(
    modelFile);

Array position = new object[] { 49.88, -77.255000.0 };
model.SetPositionCartographic("Earth"ref position);
model.Scale = Math.Pow(102);

manager.Primitives.Add((IAgStkGraphicsPrimitive)model);

//  hellfireflame.anc
//
//  <?xml version = "1.0" standalone = "yes"?>
//  <ancillary_model_data version = "1.0">
//       <video_textures>
//           <video_texture image_id = "smoketex_tga" init_from = "smoke.avi" video_loop="true" video_framerate="60" />
//           <video_texture image_id = "flametex_tga" init_from = "flame.mov" video_loop="true" video_framerate="60" />
//      </video_textures>
//  </ancillary_model_data>


Draw a model with moving articulations

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root
// String modelFile: The model file

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;
//
// Create the model
//
IAgStkGraphicsModelPrimitive model = manager.Initializers.ModelPrimitive.InitializeWithStringUri(
    modelFile);

Array position = new object[3] { 36, -116.7525000.0 };
model.SetPositionCartographic("Earth"ref position);

//
// Rotate the model to be oriented correctly
//
model.Articulations.GetByName("Commuter").GetByName("Roll").CurrentValue = 4.084070562;
model.Articulations.GetByName("Commuter").GetByName("Yaw").CurrentValue = -0.436332325;

manager.Primitives.Add((IAgStkGraphicsPrimitive)model);


internal void TimeChanged(double TimeEpSec)
{
    //
    // Rotate the propellors every time the animation updates
    //
    if (m_Model != null)
    {
        double TwoPI = 2 * Math.PI;
        ((IAgStkGraphicsModelPrimitive)m_Model).Articulations.GetByName("props").GetByName("Spin").CurrentValue = TimeEpSec % TwoPI;
    }
}


Orient a model

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root
// String modelFile: The model file
// IAgCrdnSystem referenceFrame: A reference frame for the model

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;

IAgStkGraphicsModelPrimitive model = manager.Initializers.ModelPrimitive.InitializeWithStringUri(
    modelFile);
((IAgStkGraphicsPrimitive)model).ReferenceFrame = referenceFrame;  // Model is oriented using east-north-up axes.  Use model.Orientation for addition rotation.
Array zero = new object[] { 000 }; // Origin of reference frame
model.Position = zero;
model.Scale = Math.Pow(101.5);

manager.Primitives.Add((IAgStkGraphicsPrimitive)model);


Shows the format of the Positions parameter when adding points to a path primitive.

[C#] Copy Code
// IAgStkGraphicsPathPrimitive path: A path primitive

Array positions = new object[]
{
    000,
    111,
    222,
    333,
    444
};

path.AddRangeToFront(ref positions);


Draw a set of points

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;

Array positions = new object[]
{
    39.88, -75.250,    // Philadelphia
    38.85, -77.040// Washington, D.C.
    29.98, -90.250// New Orleans
    37.37, -121.920    // San Jose
};

IAgStkGraphicsPointBatchPrimitive pointBatch = manager.Initializers.PointBatchPrimitive.Initialize();
pointBatch.SetCartographic("Earth"ref positions);
pointBatch.PixelSize = 5;
((IAgStkGraphicsPrimitive)pointBatch).Color = Color.White;
pointBatch.DisplayOutline = true;
pointBatch.OutlineWidth = 2;
pointBatch.OutlineColor = Color.Red;

manager.Primitives.Add((IAgStkGraphicsPrimitive)pointBatch);


Draw a set of uniquely colored points

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;
Array positions = new object[]
{
    37.62, -122.380.0,    // San Francisco
    38.52, -121.500.0,    // Sacramento
    33.93, -118.400.0,    // Los Angeles
    32.82, -117.130.0     // San Diego
};

Array colors = new object[]
{
    (uint)Color.Red.ToArgb(),
    (uint)Color.Orange.ToArgb(),
    (uint)Color.Blue.ToArgb(),
    (uint)Color.White.ToArgb()
};

IAgStkGraphicsPointBatchPrimitive pointBatch = manager.Initializers.PointBatchPrimitive.Initialize();
pointBatch.SetCartographicWithColors("Earth"ref positions, ref colors);
pointBatch.PixelSize = 8;

manager.Primitives.Add((IAgStkGraphicsPrimitive)pointBatch);


Shows the format of the Positions, Colors and Indices parameters when updating a point batch with cartographic positions.

[C#] Copy Code
// IAgStkGraphicsPointBatchPrimitive pointBatch: A point batch primitive

Array positions = new object[]
{
    39.88, -75.250,
    38.85, -77.040,
    29.98, -90.250,
    37.37, -121.920
};

Array colors = new object[]
{
    Color.Red.ToArgb(),
    Color.Green.ToArgb(),
    Color.Blue.ToArgb(),
    Color.White.ToArgb()
};

Array indices = new object[]
{
    0,
    1,
    2,
    3
};

pointBatch.SetPartialCartographicWithColorsIndicesOrderAndRenderPass(
    "Earth",
    ref positions,
    ref colors,
    ref indices,
    AgEStkGraphicsIndicesOrderHint.eStkGraphicsIndicesOrderHintSortedAscending,
    AgEStkGraphicsRenderPassHint.eStkGraphicsRenderPassHintOpaque);


Shows the format of the Positions, Colors and Indices parameters when updating a point batch.

[C#] Copy Code
// IAgStkGraphicsPointBatchPrimitive pointBatch: A point batch primitive

Array positions = new object[]
{
    1247.87, -4739.744067.77,
    1115.48, -4847.093979.36,
    -24.12, -5529.313168.45,
    -2683.42, -4307.743850.11
};

Array colors = new object[]
{
    Color.Red.ToArgb(),
    Color.Green.ToArgb(),
    Color.Blue.ToArgb(),
    Color.White.ToArgb()
};

Array indices = new object[]
{
    0,
    1,
    2,
    3
};

pointBatch.SetPartialWithColorsIndicesOrderAndRenderPass(
    ref positions,
    ref colors,
    ref indices,
    AgEStkGraphicsIndicesOrderHint.eStkGraphicsIndicesOrderHintSortedAscending,
    AgEStkGraphicsRenderPassHint.eStkGraphicsRenderPassHintOpaque);


Draw a great arc on the globe

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;
Array washingtonDC = new object[]
{
    38.85,
    -77.04,
    0.0
};
Array newOrleans = new object[]
{
    29.98,
    -90.25,
    0.0
};

Array positions = new object[6];
washingtonDC.CopyTo(positions, 0);
newOrleans.CopyTo(positions, 3);

IAgStkGraphicsPositionInterpolator interpolator = manager.Initializers.GreatArcInterpolator.Initialize() as IAgStkGraphicsPositionInterpolator;
IAgStkGraphicsPolylinePrimitive line = manager.Initializers.PolylinePrimitive.InitializeWithInterpolator(interpolator);
line.SetCartographic("Earth"ref positions);

manager.Primitives.Add((IAgStkGraphicsPrimitive)line);


Draw a line between two points

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;
Array philadelphia = new object[]
{
    39.88,
    -75.25,
    3000.0
};
Array washingtonDC = new object[]
{
    38.85,
    -77.04,
    3000.0
};

Array positions = new object[6];
philadelphia.CopyTo(positions, 0);
washingtonDC.CopyTo(positions, 3);

IAgStkGraphicsPolylinePrimitive line = manager.Initializers.PolylinePrimitive.Initialize();
line.SetCartographic("Earth"ref positions);
manager.Primitives.Add((IAgStkGraphicsPrimitive)line);


Draw a rhumb line on the globe

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;
Array newOrleans = new object[]
{
    29.98,
    -90.25,
    0.0
};
Array sanJose = new object[]
{
    37.37,
    -121.92,
    0.0
};

Array positions = new object[6];
newOrleans.CopyTo(positions, 0);
sanJose.CopyTo(positions, 3);

IAgStkGraphicsPositionInterpolator interpolator = manager.Initializers.RhumbLineInterpolator.Initialize() as IAgStkGraphicsPositionInterpolator;
IAgStkGraphicsPolylinePrimitive line = manager.Initializers.PolylinePrimitive.InitializeWithInterpolator(interpolator);
line.SetCartographic("Earth"ref positions);
manager.Primitives.Add((IAgStkGraphicsPrimitive)line);


Draw a STK area target outline on the globe

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root
// Array positions: The area target positions

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;

IAgStkGraphicsPolylinePrimitive line = manager.Initializers.PolylinePrimitive.Initialize();
line.Set(ref positions);
line.Width = 2;
((IAgStkGraphicsPrimitive)line).Color = Color.Yellow;
line.DisplayOutline = true;
line.OutlineWidth = 2;
line.OutlineColor = Color.Black;

manager.Primitives.Add((IAgStkGraphicsPrimitive)line);


Draw the outline of a circle on the globe

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;
Array center = new object[] { 39.88, -75.250.0 }; // Philadelphia

IAgStkGraphicsSurfaceShapesResult shape = manager.Initializers.SurfaceShapes.ComputeCircleCartographic("Earth"ref center, 10000);
Array positions = shape.Positions;

IAgStkGraphicsPolylinePrimitive line = manager.Initializers.PolylinePrimitive.InitializeWithType(shape.PolylineType);
line.Set(ref positions);
line.Width = 2;
((IAgStkGraphicsPrimitive)line).Color = Color.White;

manager.Primitives.Add((IAgStkGraphicsPrimitive)line);


Draw the outline of an ellipse on the globe

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;
Array center = new object[] { 38.85, -77.043000.0 }; // Washington, DC

IAgStkGraphicsSurfaceShapesResult shape = manager.Initializers.SurfaceShapes.ComputeEllipseCartographic(
    "Earth"ref center, 450003000045);
Array positions = shape.Positions;

IAgStkGraphicsPolylinePrimitive line = manager.Initializers.PolylinePrimitive.InitializeWithType(shape.PolylineType);
line.Set(ref positions);
((IAgStkGraphicsPrimitive)line).Color = Color.Cyan;

manager.Primitives.Add((IAgStkGraphicsPrimitive)line);


Shows the format of the Positions parameter when updating a polyline primitive with cartographic positions.

[C#] Copy Code
// IAgStkGraphicsPolylinePrimitive polyline: A polyline primitive

Array positions = new object[]
{
    39.88, -75.250,
    38.85, -77.040,
    29.98, -90.250,
    37.37, -121.920
};

polyline.SetSubsetCartographic(
    "Earth",
    ref positions,
    1,
    2);


Shows the format of the Positions parameter when updating a polyline primitive.

[C#] Copy Code
// IAgStkGraphicsPolylinePrimitive polyline: A polyline primitive

Array positions = new object[]
{
    1247.87, -4739.744067.77,
    1115.48, -4847.093979.36,
    -24.12, -5529.313168.45,
    -2683.42, -4307.743850.11
};

polyline.SetSubset(
    ref positions,
    1,
    2);


Shows the format of the Positions, Colors and Indices parameters when updating a polyline primitive with cartographic positions.

[C#] Copy Code
// IAgStkGraphicsPolylinePrimitive polyline: A polyline primitive

Array positions = new object[]
{
    39.88, -75.250,
    38.85, -77.040,
    29.98, -90.250,
    37.37, -121.920
};

Array colors = new object[]
{
    Color.Red.ToArgb(),
    Color.Green.ToArgb(),
    Color.Blue.ToArgb(),
    Color.White.ToArgb()
};

Array indices = new object[]
{
    0,
    1,
    2,
    3
};

polyline.SetPartialCartographicWithColorsIndicesOrderAndRenderPass(
    "Earth",
    ref positions,
    ref colors,
    ref indices,
    AgEStkGraphicsIndicesOrderHint.eStkGraphicsIndicesOrderHintSortedAscending,
    AgEStkGraphicsRenderPassHint.eStkGraphicsRenderPassHintOpaque);


Shows the format of the Positions, Colors and Indices parameters when updating a polyline primitive.

[C#] Copy Code
// IAgStkGraphicsPolylinePrimitive polyline: A polyline primitive

Array positions = new object[]
{
    1247.87, -4739.744067.77,
    1115.48, -4847.093979.36,
    -24.12, -5529.313168.45,
    -2683.42, -4307.743850.11
};

Array colors = new object[]
{
    Color.Red.ToArgb(),
    Color.Green.ToArgb(),
    Color.Blue.ToArgb(),
    Color.White.ToArgb()
};

Array indices = new object[]
{
    0,
    1,
    2,
    3
};

polyline.SetPartialWithColorsIndicesOrderAndRenderPassHint(
    ref positions,
    ref colors,
    ref indices,
    AgEStkGraphicsIndicesOrderHint.eStkGraphicsIndicesOrderHintSortedAscending,
    AgEStkGraphicsRenderPassHint.eStkGraphicsRenderPassHintOpaque);


Draw a box

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root
// IAgCrdnSystem system: A system for the solid

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;

Array size = new object[] {100010002000 };
IAgStkGraphicsSolidTriangulatorResult result = manager.Initializers.BoxTriangulator.Compute(ref size);
IAgStkGraphicsSolidPrimitive solid = manager.Initializers.SolidPrimitive.Initialize();
((IAgStkGraphicsPrimitive)solid).ReferenceFrame = system;
solid.SetWithResult(result);

manager.Primitives.Add((IAgStkGraphicsPrimitive)solid);


Draw a cylinder

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root
// IAgCrdnSystem system: A system for the solid

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;

IAgStkGraphicsSolidTriangulatorResult result = manager.Initializers.CylinderTriangulator.CreateSimple(10002000);
IAgStkGraphicsSolidPrimitive solid = manager.Initializers.SolidPrimitive.Initialize();
((IAgStkGraphicsPrimitive)solid).ReferenceFrame = system;
((IAgStkGraphicsPrimitive)solid).Color = Color.Yellow;
solid.OutlineColor = Color.Black;
solid.OutlineWidth = 2;
solid.OutlineAppearance = AgEStkGraphicsOutlineAppearance.eStkGraphicsStylizeBackLines;
solid.BackLineColor = Color.Black;
solid.BackLineWidth = 1;
solid.SetWithResult(result);

manager.Primitives.Add((IAgStkGraphicsPrimitive)solid);


Draw an ellipsoid

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root
// IAgCrdnSystem system: A system for the solid

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;

Array radii = new object[] {200010001000 };
IAgStkGraphicsSolidTriangulatorResult result = manager.Initializers.EllipsoidTriangulator.ComputeSimple(ref radii);
IAgStkGraphicsSolidPrimitive solid = manager.Initializers.SolidPrimitive.Initialize();
((IAgStkGraphicsPrimitive)solid).ReferenceFrame = system;
((IAgStkGraphicsPrimitive)solid).Color =  Color.Orange;
((IAgStkGraphicsPrimitive)solid).Translucency = 0.3f;
solid.OutlineAppearance = AgEStkGraphicsOutlineAppearance.eStkGraphicsFrontLinesOnly;
solid.OutlineColor = Color.Blue;
solid.OutlineWidth = 2;
solid.DisplaySilhouette = true;
solid.SetWithResult(result);

manager.Primitives.Add((IAgStkGraphicsPrimitive)solid);


Draw a filled STK area target on terrain

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root
// String terrainFile: The terrain file
// Array positions: The positions used to compute triangulation

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;
IAgStkGraphicsTerrainOverlay overlay = scene.CentralBodies.Earth.Terrain.AddUriString(
    terrainFile);

IAgStkGraphicsSurfaceTriangulatorResult triangles =
    manager.Initializers.SurfacePolygonTriangulator.Compute("Earth"ref positions);

IAgStkGraphicsSurfaceMeshPrimitive mesh = manager.Initializers.SurfaceMeshPrimitive.Initialize();
((IAgStkGraphicsPrimitive)mesh).Color = Color.Purple;
mesh.Set(triangles);
manager.Primitives.Add((IAgStkGraphicsPrimitive)mesh);


Draw a filled STK area target on the globe

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root
// String textureFile: The texture file

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;
//
// Load the UAV image where each corner maps to a longitude and latitude defined
// in degrees below.
//
//    lower left  = (-0.386182, 42.938583)
//    lower right = (-0.375100, 42.929871)
//    upper right = (-0.333891, 42.944780)
//    upper left  = (-0.359980, 42.973438)
//

IAgStkGraphicsRendererTexture2D texture = manager.Textures.LoadFromStringUri(
    textureFile);

//
// Define the bounding extent of the image.  Create a surface mesh that uses this extent.
//
IAgStkGraphicsSurfaceMeshPrimitive mesh = manager.Initializers.SurfaceMeshPrimitive.Initialize();
mesh.Texture = texture;

Array cartographicExtent = new object[]
{
    -0.386182,
    42.929871,
    -0.333891,
    42.973438
};

IAgStkGraphicsSurfaceTriangulatorResult triangles = manager.Initializers.SurfaceExtentTriangulator.ComputeSimple("Earth"ref cartographicExtent);
mesh.Set(triangles);
((IAgStkGraphicsPrimitive)mesh).Translucency = 0.0f;

//
// Create the texture matrix that maps the image corner points to their actual
// cartographic coordinates.  A few notes:
//
// 1. The TextureMatrix does not do any special processing on these values
//    as if they were cartographic coordinates.
//
// 2. Because of 1., the values only have to be correct relative to each
//    other, which is why they do not have to be converted to radians.
//
// 3. Because of 2., if your image straddles the +/- 180 degs longitude line,
//    ensure that longitudes east of the line are greater than those west of
//    the line.  For example, if one point were 179.0 degs longitude and the
//    other were to the east at -179.0 degs, the one to the east should be
//    specified as 181.0 degs.
//

Array c0 = new object[] { -0.38618242.938583 };
Array c1 = new object[] { -0.37510042.929871 };
Array c2 = new object[] { -0.33389142.944780 };
Array c3 = new object[] { -0.35998042.973438 };

mesh.TextureMatrix = manager.Initializers.TextureMatrix.InitializeWithRectangles(
    ref c0, ref c1, ref c2, ref c3);

//
// Enable the transparent texture border option on the mesh so that the texture will not
// bleed outside of the trapezoid.
//
mesh.TransparentTextureBorder = true;

//
// Add the surface mesh to the Scene manager
//
manager.Primitives.Add((IAgStkGraphicsPrimitive)mesh);


Draw a filled, dynamically textured extent on terrain

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root
// String rasterFile: The file to use as the raster

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;
IAgStkGraphicsProjectionRasterStreamPluginActivator activator =
    manager.Initializers.ProjectionRasterStreamPluginActivator.Initialize();
IAgStkGraphicsProjectionRasterStreamPluginProxy proxy =
    activator.CreateFromDisplayName("ProjectionRasterStreamPlugin.CSharp");

//
// Use reflection to set the plugin's properties
//
Type plugin = proxy.RealPluginObject.GetType();
plugin.GetProperty("RasterPath").SetValue(proxy.RealPluginObject, rasterFile, null);

IAgStkGraphicsRasterStream rasterStream = proxy.RasterStream;
rasterStream.UpdateDelta = 0.025;

IAgStkGraphicsRendererTexture2D texture = manager.Textures.FromRaster((IAgStkGraphicsRaster)rasterStream);
Array extent = ((IAgStkGraphicsGlobeOverlay)overlay).Extent;
IAgStkGraphicsSurfaceTriangulatorResult triangles = manager.Initializers.SurfaceExtentTriangulator.ComputeSimple("Earth"ref extent);
IAgStkGraphicsSurfaceMeshPrimitive mesh = manager.Initializers.SurfaceMeshPrimitive.Initialize();
((IAgStkGraphicsPrimitive)mesh).Translucency = 0.2f;
mesh.Texture = texture;
mesh.Set(triangles);
manager.Primitives.Add((IAgStkGraphicsPrimitive)mesh);


Draw a filled, textured extent on terrain

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root
// String textureFile: The file to use as the texture of the surface mesh

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;
Array overlayExtent = ((IAgStkGraphicsGlobeOverlay)overlay).Extent;
IAgStkGraphicsSurfaceTriangulatorResult triangles =
    manager.Initializers.SurfaceExtentTriangulator.ComputeSimple("Earth"ref overlayExtent);
IAgStkGraphicsRendererTexture2D texture = manager.Textures.LoadFromStringUri(
    textureFile);
IAgStkGraphicsSurfaceMeshPrimitive mesh = manager.Initializers.SurfaceMeshPrimitive.Initialize();
((IAgStkGraphicsPrimitive)mesh).Translucency = 0.3f;
mesh.Texture = texture;
mesh.Set(triangles);
manager.Primitives.Add((IAgStkGraphicsPrimitive)mesh);


Draw a moving water texture using affine transformations

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root
// String textureFile: The file to use as the texture of the surface mesh

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;
Array cartographicExtent = new object[]
{
    -96,
    22,
    -85,
    28
};

IAgStkGraphicsSurfaceTriangulatorResult triangles =
    manager.Initializers.SurfaceExtentTriangulator.ComputeSimple("Earth"ref cartographicExtent);

IAgStkGraphicsRendererTexture2D texture = manager.Textures.LoadFromStringUri(
    textureFile);
IAgStkGraphicsSurfaceMeshPrimitive mesh = manager.Initializers.SurfaceMeshPrimitive.Initialize();
((IAgStkGraphicsPrimitive)mesh).Translucency = 0.3f;
mesh.Texture = texture;
mesh.TextureFilter = manager.Initializers.TextureFilter2D.LinearRepeat;
mesh.Set(triangles);
manager.Primitives.Add((IAgStkGraphicsPrimitive)mesh);


internal void TimeChanged(IAgStkGraphicsScene scene, AgStkObjectRoot root, double TimeEpSec)
{
    //
    //  Translate the surface mesh every animation update
    //
    if (m_Primitive != null)
    {
        IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;

        m_Translation = (float)TimeEpSec;
        m_Translation /= 1000;

        Matrix transformation = new Matrix();
        transformation.Translate(-m_Translation, 0); // Sign determines the direction of apparent flow

        // Convert the matrix to an object array
        Array transformationArray = Array.CreateInstance(typeof(object), transformation.Elements.Length);
        for (int i = 0; i < transformationArray.Length; ++i)
        {
            transformationArray.SetValue((object)transformation.Elements.GetValue(i), i);
        }

        ((IAgStkGraphicsSurfaceMeshPrimitive)m_Primitive).TextureMatrix =
            manager.Initializers.TextureMatrix.InitializeWithAffineTransform(ref transformationArray);
    }
}


Draw a set of strings

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;

Array text = new object[]
{
    "Philadelphia",
    "Washington, D.C.",
    "New Orleans",
    "San Jose"
};

Array positions = new object[]
{
    39.88, -75.250,    // Philadelphia
    38.85, -77.040// Washington, D.C.
    29.98, -90.250// New Orleans
    37.37, -121.920    // San Jose
};

IAgStkGraphicsGraphicsFont font = manager.Initializers.GraphicsFont.InitializeWithNameSizeFontStyleOutline("MS Sans Serif"12, AgEStkGraphicsFontStyle.eStkGraphicsFontStyleBold, true);
IAgStkGraphicsTextBatchPrimitive textBatch = manager.Initializers.TextBatchPrimitive.InitializeWithGraphicsFont(font);
((IAgStkGraphicsPrimitive)textBatch).Color = Color.White;
textBatch.OutlineColor = Color.Red;
textBatch.SetCartographic("Earth"ref positions, ref text);

manager.Primitives.Add((IAgStkGraphicsPrimitive)textBatch);


Draw a set of uniquely colored strings

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;
Array strings = new object[]
{
    "San Francisco",
    "Sacramento",
    "Los Angeles",
    "San Diego"
};

Array positions = new object[]
{
    37.62, -122.380.0,
    38.52, -121.500.0,
    33.93, -118.400.0,
    32.82, -117.130.0
};

Array colors = new object[]
{
    (uint)Color.Red.ToArgb(),
    (uint)Color.Green.ToArgb(),
    (uint)Color.Blue.ToArgb(),
    (uint)Color.White.ToArgb()
};

IAgStkGraphicsTextBatchPrimitiveOptionalParameters parameters = manager.Initializers.TextBatchPrimitiveOptionalParameters.Initialize();
parameters.SetColors(ref colors);

IAgStkGraphicsGraphicsFont font = manager.Initializers.GraphicsFont.InitializeWithNameSizeFontStyleOutline("MS Sans Serif"12, AgEStkGraphicsFontStyle.eStkGraphicsFontStyleBold, false);
IAgStkGraphicsTextBatchPrimitive textBatch = manager.Initializers.TextBatchPrimitive.InitializeWithGraphicsFont(font);
textBatch.SetCartographicWithOptionalParameters("Earth"ref positions, ref strings, parameters);

manager.Primitives.Add((IAgStkGraphicsPrimitive)textBatch);


Shows the format of the Colors parameter when setting per string colors.

[C#] Copy Code
// IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Array colors = new object[]
{
    Color.Red.ToArgb(),
    Color.Green.ToArgb(),
    Color.Blue.ToArgb(),
    Color.White.ToArgb()
};

IAgStkGraphicsTextBatchPrimitiveOptionalParameters parameters = sceneManager.Initializers.TextBatchPrimitiveOptionalParameters.Initialize();
parameters.SetColors(ref colors);


Shows the format of the EyeOffset property when setting the per-batch eye offset.

[C#] Copy Code
// IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Array eyeoffset = new object[]
{
    2,
    3,
    4
};

IAgStkGraphicsTextBatchPrimitiveOptionalParameters parameters = sceneManager.Initializers.TextBatchPrimitiveOptionalParameters.Initialize();
parameters.EyeOffset = eyeoffset;


Shows the format of the EyeOffsets parameter when setting per string eye offsets.

[C#] Copy Code
// IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Array eyeoffset = new object[]
{
    234,
    234
};

IAgStkGraphicsTextBatchPrimitiveOptionalParameters parameters = sceneManager.Initializers.TextBatchPrimitiveOptionalParameters.Initialize();
parameters.SetEyeOffsets(ref eyeoffset);


Shows the format of the Origins parameter when setting per string origins.

[C#] Copy Code
// IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Array origins = new object[]
{
    AgEStkGraphicsOrigin.eStkGraphicsOriginCenter,
    AgEStkGraphicsOrigin.eStkGraphicsOriginBottomLeft,
    AgEStkGraphicsOrigin.eStkGraphicsOriginBottomRight,
    AgEStkGraphicsOrigin.eStkGraphicsOriginTopLeft
};

IAgStkGraphicsTextBatchPrimitiveOptionalParameters parameters = sceneManager.Initializers.TextBatchPrimitiveOptionalParameters.Initialize();
parameters.SetOrigins(ref origins);


Shows the format of the PixelOffset property when setting the per-batch pixel offset.

[C#] Copy Code
// IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Array pixelOffset = new object[]
{
    1,
    2
};

IAgStkGraphicsTextBatchPrimitiveOptionalParameters parameters = sceneManager.Initializers.TextBatchPrimitiveOptionalParameters.Initialize();
parameters.PixelOffset = pixelOffset;


Shows the format of the PixelOffsets parameter when setting per string pixel offsets.

[C#] Copy Code
// IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Array pixelOffset = new object[]
{
    12,
    21
};

IAgStkGraphicsTextBatchPrimitiveOptionalParameters parameters = sceneManager.Initializers.TextBatchPrimitiveOptionalParameters.Initialize();
parameters.SetPixelOffsets(ref pixelOffset);


Shows the format of the Text, Positions, Colors and Indices parameters when updating a text batch primitive with cartographic positions.

[C#] Copy Code
// IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager
// IAgStkGraphicsTextBatchPrimitive textBatch: A text batch primitive

Array colors = new object[]
{
    Color.Red.ToArgb(),
    Color.Green.ToArgb(),
    Color.Blue.ToArgb(),
    Color.White.ToArgb()
};

IAgStkGraphicsTextBatchPrimitiveOptionalParameters parameters = sceneManager.Initializers.TextBatchPrimitiveOptionalParameters.Initialize();
parameters.SetColors(ref colors);

Array text = new object[]
{
    "Philadelphia",
    "Washington D.C.",
    "New Orleans",
    "San Jose"
};

Array positions = new object[]
{
    39.88, -75.250,    // Philadelphia
    38.85, -77.040// Washington, D.C.
    29.98, -90.250// New Orleans
    37.37, -121.920    // San Jose
};

Array indices = new object[]
{
    0,
    1,
    2,
    3
};

textBatch.SetPartialCartographicWithOptionalParametersIndicesOrderAndRenderPass(
    "Earth",
    ref positions,
    ref text,
    parameters,
    ref indices,
    AgEStkGraphicsIndicesOrderHint.eStkGraphicsIndicesOrderHintSortedAscending,
    AgEStkGraphicsRenderPassHint.eStkGraphicsRenderPassHintOpaque);


Shows the format of the Text, Positions, Colors and Indices parameters when updating a text batch primitive.

[C#] Copy Code
// IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager
// IAgStkGraphicsTextBatchPrimitive textBatch: A text batch primitive

Array colors = new object[]
{
    Color.Red.ToArgb(),
    Color.Green.ToArgb(),
    Color.Blue.ToArgb(),
    Color.White.ToArgb()
};

IAgStkGraphicsTextBatchPrimitiveOptionalParameters parameters = sceneManager.Initializers.TextBatchPrimitiveOptionalParameters.Initialize();
parameters.SetColors(ref colors);

Array text = new object[]
{
    "Philadelphia",
    "Washington D.C.",
    "New Orleans",
    "San Jose"
};

Array positions = new object[]
{
    1247.87, -4739.744067.77,
    1115.48, -4847.093979.36,
    -24.12, -5529.313168.45,
    -2683.42, -4307.743850.11
};

Array indices = new object[]
{
    0,
    1,
    2,
    3
};

textBatch.SetPartialWithOptionalParametersIndicesOrderAndRenderPass(
    ref positions,
    ref text,
    parameters,
    ref indices,
    AgEStkGraphicsIndicesOrderHint.eStkGraphicsIndicesOrderHintSortedAscending,
    AgEStkGraphicsRenderPassHint.eStkGraphicsRenderPassHintOpaque);


Draw a filled circle on the globe

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;
Array center = new object[] { 39.88, -75.250.0 };

IAgStkGraphicsSurfaceShapesResult shape = manager.Initializers.SurfaceShapes.ComputeCircleCartographic("Earth"ref center, 10000);
Array positions = shape.Positions;
IAgStkGraphicsSurfaceTriangulatorResult triangles = manager.Initializers.SurfacePolygonTriangulator.Compute("Earth"ref positions);

IAgStkGraphicsTriangleMeshPrimitive mesh = manager.Initializers.TriangleMeshPrimitive.Initialize();
mesh.SetTriangulator((IAgStkGraphicsTriangulatorResult)triangles);
((IAgStkGraphicsPrimitive)mesh).Color = Color.White;
((IAgStkGraphicsPrimitive)mesh).Translucency = 0.5f;

manager.Primitives.Add((IAgStkGraphicsPrimitive)mesh);


Draw a filled ellipse on the globe

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;
Array center = new object[] { 38.85, -77.043000.0 }; // Washington, DC

IAgStkGraphicsSurfaceShapesResult shape = manager.Initializers.SurfaceShapes.ComputeEllipseCartographic(
    "Earth"ref center, 450003000045);
Array positions = shape.Positions;

IAgStkGraphicsSurfaceTriangulatorResult triangles = manager.Initializers.SurfacePolygonTriangulator.Compute(
    "Earth"ref positions);
IAgStkGraphicsTriangleMeshPrimitive mesh = manager.Initializers.TriangleMeshPrimitive.Initialize();
mesh.SetTriangulator((IAgStkGraphicsTriangulatorResult)triangles);
((IAgStkGraphicsPrimitive)mesh).Color = Color.Cyan;

manager.Primitives.Add((IAgStkGraphicsPrimitive)mesh);


Draw a filled polygon with a hole on the globe

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root
// Array positions: The positions used to compute triangulation
// Array holePositions: The positions of the hole

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;

IAgStkGraphicsSurfaceTriangulatorResult triangles = manager.Initializers.SurfacePolygonTriangulator.ComputeWithHole(
    "Earth"ref positions, ref holePositions);

IAgStkGraphicsTriangleMeshPrimitive mesh = manager.Initializers.TriangleMeshPrimitive.Initialize();
mesh.SetTriangulator((IAgStkGraphicsTriangulatorResult)triangles);
((IAgStkGraphicsPrimitive)mesh).Color = Color.Gray;
((IAgStkGraphicsPrimitive)mesh).Translucency = 0.5f;
manager.Primitives.Add((IAgStkGraphicsPrimitive)mesh);

IAgStkGraphicsPolylinePrimitive boundaryLine = manager.Initializers.PolylinePrimitive.Initialize();
Array boundaryPositionsArray = triangles.BoundaryPositions;
boundaryLine.Set(ref boundaryPositionsArray);
((IAgStkGraphicsPrimitive)boundaryLine).Color = Color.Red;
boundaryLine.Width = 2;
manager.Primitives.Add((IAgStkGraphicsPrimitive)boundaryLine);

IAgStkGraphicsPolylinePrimitive holeLine = manager.Initializers.PolylinePrimitive.Initialize();
holeLine.Set(ref holePositions);
((IAgStkGraphicsPrimitive)holeLine).Color = Color.Red;
holeLine.Width = 2;
manager.Primitives.Add((IAgStkGraphicsPrimitive)holeLine);


Draw a filled rectangular extent on the globe

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;

Array extent = new object[]
{
    -9429,
    -8933
};

IAgStkGraphicsSurfaceTriangulatorResult triangles = manager.Initializers.SurfaceExtentTriangulator.ComputeSimple(
        "Earth"ref extent);

IAgStkGraphicsTriangleMeshPrimitive mesh = manager.Initializers.TriangleMeshPrimitive.Initialize();
mesh.SetTriangulator((IAgStkGraphicsTriangulatorResult)triangles);
((IAgStkGraphicsPrimitive)mesh).Color = Color.Salmon;
mesh.Lighting = false;  /* Turn off lighting for the mesh so the color we assigned will always be consistent */

manager.Primitives.Add((IAgStkGraphicsPrimitive)mesh);


Draw a filled STK area target

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root
// Array positions: The positions used to compute triangulation

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;

IAgStkGraphicsSurfaceTriangulatorResult triangles =
    manager.Initializers.SurfacePolygonTriangulator.Compute("Earth"ref positions);

IAgStkGraphicsTriangleMeshPrimitive mesh = manager.Initializers.TriangleMeshPrimitive.Initialize();
mesh.SetTriangulator((IAgStkGraphicsTriangulatorResult)triangles);
((IAgStkGraphicsPrimitive)mesh).Color = Color.Red;
manager.Primitives.Add((IAgStkGraphicsPrimitive)mesh);


Draw an extrusion around a STK area target

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root
// Array positions: The positions used to compute triangulation

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;

IAgStkGraphicsExtrudedPolylineTriangulatorResult triangles =
    manager.Initializers.ExtrudedPolylineTriangulator.ComputeWithAltitudes(
    "Earth"ref positions, 1000025000);
IAgStkGraphicsTriangleMeshPrimitive mesh = manager.Initializers.TriangleMeshPrimitive.Initialize();
mesh.SetTriangulator((IAgStkGraphicsTriangulatorResult)triangles);
((IAgStkGraphicsPrimitive)mesh).Color = Color.Red;
((IAgStkGraphicsPrimitive)mesh).Translucency = 0.4f;

manager.Primitives.Add((IAgStkGraphicsPrimitive)mesh);


Shows the format of the Colors parameter when setting per vertex colors.

[C#] Copy Code
// IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Array colors = new object[]
{
    Color.Red.ToArgb(),
    Color.Green.ToArgb(),
    Color.Blue.ToArgb(),
    Color.White.ToArgb()
};

IAgStkGraphicsTriangleMeshPrimitiveOptionalParameters parameters = sceneManager.Initializers.TriangleMeshPrimitiveOptionalParameters.Initialize();
parameters.SetPerVertexColors(ref colors);


Shows the format of the Positions, Normals and Indices parameters when updating a triangle mesh primitive.

[C#] Copy Code
// IAgStkGraphicsTriangleMeshPrimitive triangleMesh: A triangle mesh primitive

Array positions = new object[]
{
    000,
    7000000,
    0700000
};

Array normals = new object[]
{
    001,
    001,
    001
};

Array indices = new object[]
{
    0,
    1,
    2
};

triangleMesh.Set(ref positions, ref normals, ref indices);


Shows the format of the TextureCoordinates parameter when setting per vertex texture coordinates.

[C#] Copy Code
// IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Array coordinates = new object[]
{
    0011,
    0011
};

IAgStkGraphicsTriangleMeshPrimitiveOptionalParameters parameters = sceneManager.Initializers.TriangleMeshPrimitiveOptionalParameters.Initialize();
parameters.SetTextureCoordinates(ref coordinates);


Shows the format of the Position parameter when creating a projection.

[C#] Copy Code
// IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager
// IAgOrientation orientation: A valid orientation object.

Array position = new object[]
{
    31378.1,
    0,
    0
};

IAgStkGraphicsProjection projection = sceneManager.Initializers.Projection.InitializeWithData(
    ref position,
    orientation,
    200,
    200,
    20,
    10000);


Shows the format of the projection's Position property.

[C#] Copy Code
// IAgStkGraphicsProjection projection: A valid projection object

Array position = new object[]
{
    31378.1,
    0,
    0
};

projection.Position = position;


How to get the scene manager from the STK Object Model root.

[C#] Copy Code
// AgStkObjectRoot root: STK Object Model root

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;


Add a company logo with a texture overlay

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root
// String imageFile: The image file

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;
IAgStkGraphicsScreenOverlayCollectionBase overlayManager = (IAgStkGraphicsScreenOverlayCollectionBase)manager.ScreenOverlays.Overlays;

IAgStkGraphicsRendererTexture2D texture2D = manager.Textures.LoadFromStringUri(
    imageFile);

IAgStkGraphicsTextureScreenOverlay overlay = manager.Initializers.TextureScreenOverlay.InitializeWithXYWidthHeight(
    100,
    texture2D.Template.Width / 2,
    texture2D.Template.Height / 2);
((IAgStkGraphicsOverlay)overlay).Translucency = 0.1f;
((IAgStkGraphicsOverlay)overlay).Origin = AgEStkGraphicsScreenOverlayOrigin.eStkGraphicsScreenOverlayOriginCenterRight;
overlay.Texture = texture2D;

overlayManager.Add((IAgStkGraphicsScreenOverlay)overlay);


Add a video with a texture overlay

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root
// String videoFile: The video file

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;
IAgStkGraphicsScreenOverlayCollectionBase overlayManager = (IAgStkGraphicsScreenOverlayCollectionBase)manager.ScreenOverlays.Overlays;

IAgStkGraphicsVideoStream videoStream = manager.Initializers.VideoStream.InitializeWithStringUri(videoFile);
videoStream.Playback = AgEStkGraphicsVideoPlayback.eStkGraphicsVideoPlaybackRealTime;
videoStream.Loop = true;

IAgStkGraphicsTextureScreenOverlay overlay = manager.Initializers.TextureScreenOverlay.InitializeWithXYWidthHeight(
    00,
    ((IAgStkGraphicsRaster)videoStream).Width / 4,
    ((IAgStkGraphicsRaster)videoStream).Height / 4);
((IAgStkGraphicsOverlay)overlay).Translucency = 0.3f;
((IAgStkGraphicsOverlay)overlay).Origin = AgEStkGraphicsScreenOverlayOrigin.eStkGraphicsScreenOverlayOriginTopRight;
((IAgStkGraphicsOverlay)overlay).BorderSize = 1;
((IAgStkGraphicsOverlay)overlay).BorderTranslucency = 0.3f;
overlay.Texture = manager.Textures.FromRaster((IAgStkGraphicsRaster)videoStream);

overlayManager.Add((IAgStkGraphicsScreenOverlay)overlay);


Add overlays to a panel overlay

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root
// String imageFile: The image file to use for the child overlay
// String rasterFile: The raster file for the second child overlay

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;
IAgStkGraphicsScreenOverlayCollectionBase overlayManager = (IAgStkGraphicsScreenOverlayCollectionBase)manager.ScreenOverlays.Overlays;

IAgStkGraphicsTextureScreenOverlay overlay =
    manager.Initializers.TextureScreenOverlay.InitializeWithXYWidthHeight(00,
    188200);
((IAgStkGraphicsOverlay)overlay).Origin = AgEStkGraphicsScreenOverlayOrigin.eStkGraphicsScreenOverlayOriginTopLeft;
((IAgStkGraphicsOverlay)overlay).Color = Color.LightSkyBlue;
((IAgStkGraphicsOverlay)overlay).Translucency = 0.7f;
((IAgStkGraphicsOverlay)overlay).BorderTranslucency = 0.3f;
((IAgStkGraphicsOverlay)overlay).BorderSize = 1;
((IAgStkGraphicsOverlay)overlay).BorderColor = Color.LightBlue;

IAgStkGraphicsTextureScreenOverlay childOverlay =
    manager.Initializers.TextureScreenOverlay.InitializeWithXYWidthHeight(
    00, ((IAgStkGraphicsOverlay)overlay).Width, ((IAgStkGraphicsOverlay)overlay).Height);
((IAgStkGraphicsOverlay)childOverlay).Origin = AgEStkGraphicsScreenOverlayOrigin.eStkGraphicsScreenOverlayOriginCenter;

childOverlay.Texture = manager.Textures.LoadFromStringUri(imageFile);

//
// Create the RasterStream from the plugin the same way as in ImageDynamicCodeSnippet.cs
//
IAgStkGraphicsProjectionRasterStreamPluginActivator activator =
    manager.Initializers.ProjectionRasterStreamPluginActivator.Initialize();
IAgStkGraphicsProjectionRasterStreamPluginProxy proxy =
    activator.CreateFromDisplayName("ProjectionRasterStreamPlugin.CSharp");
Type plugin = proxy.RealPluginObject.GetType();
plugin.GetProperty("RasterPath").SetValue(proxy.RealPluginObject, rasterFile, null);

IAgStkGraphicsRasterStream rasterStream = proxy.RasterStream;
rasterStream.UpdateDelta = 0.01667;
IAgStkGraphicsRendererTexture2D texture2D = manager.Textures.FromRaster((IAgStkGraphicsRaster)rasterStream);

IAgStkGraphicsTextureScreenOverlay secondChildOverlay =
    manager.Initializers.TextureScreenOverlay.InitializeWithXYWidthHeight(00,
    128128);
((IAgStkGraphicsOverlay)secondChildOverlay).Origin = AgEStkGraphicsScreenOverlayOrigin.eStkGraphicsScreenOverlayOriginTopRight;
((IAgStkGraphicsOverlay)secondChildOverlay).TranslationX = -36;
((IAgStkGraphicsOverlay)secondChildOverlay).TranslationY = -18;
((IAgStkGraphicsOverlay)secondChildOverlay).ClipToParent = false;
secondChildOverlay.Texture = texture2D;

overlayManager.Add((IAgStkGraphicsScreenOverlay)overlay);

IAgStkGraphicsScreenOverlayCollectionBase parentOverlayManager = ((IAgStkGraphicsOverlay)overlay).Overlays as IAgStkGraphicsScreenOverlayCollectionBase;
parentOverlayManager.Add((IAgStkGraphicsScreenOverlay)childOverlay);

IAgStkGraphicsScreenOverlayCollectionBase childOverlayManager = ((IAgStkGraphicsOverlay)childOverlay).Overlays as IAgStkGraphicsScreenOverlayCollectionBase;
childOverlayManager.Add((IAgStkGraphicsScreenOverlay)secondChildOverlay);


Shows the format of the Position and Size parameters when creating a screen overlay.

[C#] Copy Code
// IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Array position = new object[]
{
    0,
    0,
    AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitPixels,
    AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitPixels
};

Array size = new object[]
{
    100,
    200,
    AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitPixels,
    AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitPixels
};

IAgStkGraphicsScreenOverlay screenOverlay = sceneManager.Initializers.ScreenOverlay.InitializeWithPosAndSize(ref position, ref size);


Shows the format of the screen overlay manager's Padding property.

[C#] Copy Code
// IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Array padding = new object[]
{
    10,
    10,
    10,
    10
};

sceneManager.ScreenOverlays.Padding = padding;


Write text to a texture overlay

[C#] Copy Code
// IAgStkGraphicsScene scene: Current Scene
// AgStkObjectRoot root: STK Object Model root
// String temporaryFile: The file to which the bitmap will be temporarily saved (should not exist yet)

IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager;
IAgStkGraphicsScreenOverlayCollectionBase overlayManager = (IAgStkGraphicsScreenOverlayCollectionBase)manager.ScreenOverlays.Overlays;

Font font = new Font("Arial"12, FontStyle.Bold);
string text = "STK Engine\nAnalytical Graphics\nOverlays";
Size textSize = MeasureString(text, font);
Bitmap textBitmap = new Bitmap(textSize.Width, textSize.Height);
Graphics gfx = Graphics.FromImage(textBitmap);
gfx.DrawString(text, font, Brushes.White, new PointF(00));

IAgStkGraphicsTextureScreenOverlay overlay =
    manager.Initializers.TextureScreenOverlay.InitializeWithXYWidthHeight(1010, textSize.Width, textSize.Height);
((IAgStkGraphicsOverlay)overlay).Origin = AgEStkGraphicsScreenOverlayOrigin.eStkGraphicsScreenOverlayOriginBottomLeft;

//
// Any bitmap can be written to a texture by temporarily saving the texture to disk.
//
string filePath = temporaryFile;
textBitmap.Save(filePath);
overlay.Texture = manager.Textures.LoadFromStringUri(filePath);
System.IO.File.Delete(filePath); // The temporary file is not longer required and can be deleted

overlay.TextureFilter = manager.Initializers.TextureFilter2D.NearestClampToEdge;

overlayManager.Add((IAgStkGraphicsScreenOverlay)overlay);


Shows the format of the Extent parameter when computing using a surface extent triangulator.

[C#] Copy Code
// IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

//The LongitudeUnit and LatitudeUnit is expected to be in degrees
Array extent = new object[]
{
    90,
    30,
    -77,
    39
};

IAgStkGraphicsSurfaceTriangulatorResult result = sceneManager.Initializers.SurfaceExtentTriangulator.ComputeSimple(
    "Earth",
    ref extent);


Shows the format of the Positions and HolePositions parameters when computing using a surface polygon triangulator.

[C#] Copy Code
// IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Array positions = new object[]
{
    1097959.63, -5171334.093556288,
    1007572.15, -5150349.713612667.74,
    978879.05, -5195164.233556326.55,
    1037389.68, -5188523.963549473.77,
    1097959.63, -5171334.093556288
};

Array holePositions = new object[]
{
    1079859.69, -5169944.963563791.24,
    1030755, -5179965.113563781.97,
    1028569.57, -5145251.033614006.53,
    1039944.33, -5153880.713598525.9,
    1027115.87, -5150522.493606951.77,
    1026998.55, -5162243.133590303.25,
    1079859.69, -5169944.963563791.24
};

IAgStkGraphicsSurfaceTriangulatorResult result = sceneManager.Initializers.SurfacePolygonTriangulator.ComputeWithHole("Earth"ref positions, ref holePositions);


Shows the format of the Positions parameter when computing using a surface polygon triangulator.

[C#]