Visual Basic .NET 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

[Visual Basic .NET] Copy Code

' Before instantiating AgStkObjectRoot an instance of AgSTKXApplication or an STK X control must be created
Dim root As New AgStkObjectRoot()


Get a reference to the AgStkObjectRoot using the running STK instance

[Visual Basic .NET] Copy Code

' Get reference to running STK instance
Dim uiApplication As AgUiApplication = TryCast(System.Runtime.InteropServices.Marshal.GetActiveObject("STK11.Application"), 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
Dim stkRoot As IAgStkObjectRoot = TryCast(uiApplication.Personality2, IAgStkObjectRoot)


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

[Visual Basic .NET] Copy Code

' Get reference to running STK instance
Dim uiApplication As AgUiApplication = TryCast(System.Runtime.InteropServices.Marshal.GetActiveObject("STK11.Application"), 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.
Dim uiApplication2 As AgUiApplication = TryCast(uiApplication.CreateApplication(), 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
Dim stkRoot As IAgStkObjectRoot = TryCast(uiApplication2.Personality2, IAgStkObjectRoot)


Start STK and get a reference to IAgStkObjectRoot

[Visual Basic .NET] Copy Code

' Create an instance of STK
Dim uiApplication As New AgUiApplication()
uiApplication.LoadPersonality("STK")
uiApplication.Visible = True

' Get our IAgStkObjectRoot interface
Dim stkRoot As IAgStkObjectRoot = TryCast(uiApplication.Personality2, IAgStkObjectRoot)


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

[Visual Basic .NET] 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)
Dim areaTarget As IAgAreaTarget = TryCast(root.CurrentScenario.Children.[New](AgESTKObjectType.eAreaTarget, "MyAreaTarget"), IAgAreaTarget)


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

[Visual Basic .NET] 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
Dim patterns As IAgAreaTypePatternCollection = TryCast(areaTarget.AreaTypeData, 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)

[Visual Basic .NET] 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
#If Not CSToJava Then
#Else
#End If
Dim boundary As Array = New Object(,) {{48.89718.637}, {46.53413.919}, {44.17321.476}}

' SetAreaTypePattern expects a two dimensional array of latitude and longitude values
#If Not CSToJava Then
areaTarget.CommonTasks.SetAreaTypePattern(boundary)
#Else
#End If


List all points in an area target

[Visual Basic .NET] Copy Code
' IAgAreaTarget areaTarget: AreaTarget object

If areaTarget.AreaType = AgEAreaType.ePattern Then
     ' Get IAgAreaTypePatternCollection interface from AreaTypeData
     Dim patternPoints As IAgAreaTypePatternCollection = TryCast(areaTarget.AreaTypeData, IAgAreaTypePatternCollection)

     ' ToArray returns a two dimensional array of latitude and longitude points
     Dim areaTargetPoints As Array = patternPoints.ToArray()

     Console.WriteLine("All points in Area Target")
     Dim i As Integer = 0
     While i < areaTargetPoints.GetLength(0)
          Console.WriteLine("  Latitude {0} Longitude: {1}", Convert.ToDouble(areaTargetPoints.GetValue(i, 0)), Convert.ToDouble(areaTargetPoints.GetValue(i, 1)))
          System.Threading.Interlocked.Increment(i)
     End While
End If


Set an elliptical area target

[Visual Basic .NET] 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
Dim ellipse As IAgAreaTypeEllipse = TryCast(areaTarget.AreaTypeData, 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)

[Visual Basic .NET] 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.

[Visual Basic .NET] Copy Code
' IAgChain chain: Chain object

chain.SetTimePeriodType(AgEChTimePeriodType.eUserSpecifiedTimePeriod)
Dim userSpecifiedTimePeriod As IAgChUserSpecifiedTimePeriod = TryCast(chain.TimePeriod, 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)

[Visual Basic .NET] 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)
Dim chain As IAgChain = TryCast(root.CurrentScenario.Children.[New](AgESTKObjectType.eChain, "MyChain"), IAgChain)


Define and compute a chain (advance)

[Visual Basic .NET] 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
Dim chainUserTimePeriod As IAgChUserSpecifiedTimePeriod = TryCast(chain.TimePeriod, 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)

[Visual Basic .NET] 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

[Visual Basic .NET] Copy Code
' IAgChain chain: Chain Object

Dim chainAsStkObject As IAgStkObject = TryCast(chain, 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)

Dim objectParticipationIntervals As IAgCrdnEventIntervalCollection = chainAsStkObject.Vgt.EventIntervalCollections("StrandAccessIntervals")
Dim intervalListResult As IAgCrdnIntervalsVectorResult = objectParticipationIntervals.FindIntervalCollection()

Dim i As Integer = 0
While i < intervalListResult.IntervalCollections.Count
     If intervalListResult.IsValid Then
          Console.WriteLine("Link Name: {0}", objectParticipationIntervals.Labels.GetValue(i))
          Console.WriteLine("--------------")
          Dim j As Integer = 0
          While j < intervalListResult.IntervalCollections(i).Count
               Dim startTime As Object = intervalListResult.IntervalCollections(i)(j).Start
               Dim stopTime As Object = intervalListResult.IntervalCollections(i)(j).[Stop]
               Console.WriteLine("Start: {0}, Stop: {1}", startTime, stopTime)
               System.Threading.Interlocked.Increment(j)
          End While
     End If
     System.Threading.Interlocked.Increment(i)
End While


Delete a STK Object

[Visual Basic .NET] Copy Code
' IAgStkObject stkObject: STK Object to be removed

stkObject.Unload()


Export a STK Object to a file

[Visual Basic .NET] Copy Code
' IAgStkObject stkObject: STK Object to be exported
' String outputPath: Output path

Dim fileNameWithoutExtension As String = Path.Combine(outputPath, "MySatellite1")
stkObject.Export(fileNameWithoutExtension)


Import an existing STK Object file into an object collection

[Visual Basic .NET] Copy Code
' IAgStkObjectCollection col: STK Object Collection
' String stkObjectLocation: Path of STK Object external file

col.ImportObject(stkObjectLocation)


Rename a STK Object

[Visual Basic .NET] Copy Code
' IAgStkObject stkObject: STK Object to be renamed

stkObject.InstanceName = "NewObjectName"


Set/Get the STK Object description

[Visual Basic .NET] 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
Dim longDescription As String = stkobject.LongDescription
Dim shortDescription As String = stkobject.ShortDescription


Add an access constraint to an STK Object

[Visual Basic .NET] Copy Code
' IAgStkObject stkobject: STK Object

Dim accessConstraints As IAgAccessConstraintCollection = stkobject.AccessConstraints

' Add constraints
accessConstraints.AddConstraint(AgEAccessConstraints.eCstrSunElevationAngle)


Add and configure a lighting condition access constraint

[Visual Basic .NET] Copy Code
' IAgAccessConstraintCollection accessConstraints: Access Constraint collection

' Condition constraint
Dim light As IAgAccessCnstrCondition = TryCast(accessConstraints.AddConstraint(AgEAccessConstraints.eCstrLighting), IAgAccessCnstrCondition)
light.Condition = AgECnstrLighting.eDirectSun


Add and configure a LOS sun exclusion access constraint

[Visual Basic .NET] Copy Code
' IAgAccessConstraintCollection accessConstraints: Access Constraint collection

' Angle constraint
Dim cnstrAngle As IAgAccessCnstrAngle = TryCast(accessConstraints.AddConstraint(AgEAccessConstraints.eCstrLOSSunExclusion), IAgAccessCnstrAngle)
cnstrAngle.Angle = 176


Add and configure a lunar elevation angle access constraint

[Visual Basic .NET] Copy Code
' IAgAccessConstraintCollection accessConstraints: Access Constraint collection

Dim minmax As IAgAccessCnstrMinMax = TryCast(accessConstraints.AddConstraint(AgEAccessConstraints.eCstrLunarElevationAngle), IAgAccessCnstrMinMax)
minmax.EnableMin = True
minmax.Min = 11.1
minmax.EnableMax = True
minmax.Max = 88.8


Add and configure a sun elevation angle access constraint

[Visual Basic .NET] Copy Code
' IAgAccessConstraintCollection accessConstraints: Access Constraint collection

Dim minmax As IAgAccessCnstrMinMax = TryCast(accessConstraints.AddConstraint(AgEAccessConstraints.eCstrSunElevationAngle), IAgAccessCnstrMinMax)
minmax.EnableMin = True
minmax.Min = 22.2
minmax.EnableMax = True
minmax.Max = 77.7


Add and configure a third body obstruction access constraint

[Visual Basic .NET] Copy Code
' IAgAccessConstraintCollection accessconstraints: Access Constraint collection

' Get IAgAccessCnstrThirdBody interface
Dim thirdBodyConstraint As IAgAccessCnstrThirdBody = TryCast(accessconstraints.AddConstraint(AgEAccessConstraints.eCstrThirdBodyObstruction), IAgAccessCnstrThirdBody)

' AvailableObstructions returns a one dimensional array of obstruction paths
Dim availableArray As Array = thirdBodyConstraint.AvailableObstructions

' In this example add all available obstructions
Console.WriteLine("Available obstructions")
For Each available As String In availableArray
     Console.WriteLine(available)
     thirdBodyConstraint.AddObstruction(available)
Next

' AssignedObstructions returns a one dimensional array of obstruction paths
Dim assignedArray As Array = thirdBodyConstraint.AssignedObstructions

Console.WriteLine("Assigned obstructions")
For Each assigned As String In assignedArray
     Console.WriteLine(assigned)
Next


Add and configure an altitude access constraint

[Visual Basic .NET] Copy Code
' IAgAccessConstraintCollection accessConstraints: Access Constraint collection

' Attitude constraint
Dim altitude As IAgAccessCnstrMinMax = TryCast(accessConstraints.AddConstraint(AgEAccessConstraints.eCstrAltitude), IAgAccessCnstrMinMax)
altitude.EnableMin = True
altitude.Min = 20.5


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

[Visual Basic .NET] Copy Code
' IAgStkObject stkobject: STK Object

Dim accessConstraints As IAgAccessConstraintCollection = 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

[Visual Basic .NET] Copy Code
' IAgStkObjectRoot root: STK Object Model root

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

' Get the access intervals
Dim accessIntervals As IAgIntervalCollection = 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
#If Not CSToJava Then
#Else
#End If
Dim dataPrvElements As Array = New Object() {"Time""FromAngularRate""FromRange"}

Dim dp As IAgDataPrvTimeVar = TryCast(access.DataProviders("Constraint Data"), IAgDataPrvTimeVar)

Dim index0 As Integer = 0
While index0 < accessIntervals.Count
     Dim startTime As Object = Nothing, stopTime As Object = Nothing

     #If Not CSToJava Then
     accessIntervals.GetInterval(index0, startTime, stopTime)
     #Else
     #End If

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

     #If Not CSToJava Then
     Dim result As IAgDrResult = dp.ExecElements(startTime, stopTime, 60, dataPrvElements)
     #Else
     #End If

     Dim timeValues As Array = result.DataSets(0).GetValues()
     Dim fromAngularRateValues As Array = result.DataSets(1).GetValues()
     Dim fromRangeValues As Array = result.DataSets(2).GetValues()

     Dim index1 As Integer = 0
     While index1 < timeValues.GetLength(0)
          Console.WriteLine("{0}: FromAngularRate={1} FromRange={2}", timeValues.GetValue(index1), fromAngularRateValues.GetValue(index1), fromRangeValues.GetValue(index1))
          System.Threading.Interlocked.Increment(index1)
     End While

     Console.WriteLine()
     System.Threading.Interlocked.Increment(index0)
End While


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

[Visual Basic .NET] Copy Code
' IAgStkObject stkObject1: STK Object
' IAgStkObject stkObject2: STK Object

' Get access by STK Object
Dim access As IAgStkAccess = stkObject1.GetAccessToObject(stkObject2)

' Compute access
access.ComputeAccess()


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

[Visual Basic .NET] Copy Code
' IAgStkObject stkObject: STK Object

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

' Compute access
access.ComputeAccess()


Compute an access for one point

[Visual Basic .NET] Copy Code
' IAgStkObject facility: Facility object

Dim onePtAccess As IAgOnePtAccess = 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
Dim results As IAgOnePtAccessResultCollection = onePtAccess.Compute()

' Print results
Dim i As Integer = 0
While i < results.Count
     Dim result As IAgOnePtAccessResult = results(i)

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

     Dim j As Integer = 0
     While j < result.Constraints.Count
          Dim constraint As IAgOnePtAccessConstraint = result.Constraints(j)
          Console.WriteLine("Constraint: {0}, Object {1}, Status {2}, Value {3}", constraint.Constraint, constraint.ObjectPath, constraint.Status, constraint.Value)
          System.Math.Max(System.Threading.Interlocked.Increment(j),j - 1)
     End While
     System.Math.Max(System.Threading.Interlocked.Increment(i),i - 1)
End While


Compute and extract access interval times

[Visual Basic .NET] Copy Code
' IAgStkAccess access: Access calculation

' Get and display the Computed Access Intervals
Dim intervalCollection As IAgIntervalCollection = access.ComputedAccessIntervalTimes

' Set the intervals to use to the Computed Access Intervals
Dim computedIntervals As Array = intervalCollection.ToArray(0, -1)
#If Not CSToJava Then
access.SpecifyAccessIntervals(computedIntervals)
#Else
#End If


Configure the access analysis time period to specified time instants.

[Visual Basic .NET] Copy Code
' IAgStkObjectRoot stkRoot: STK Object Model root

Dim uav As IAgStkObject = stkRoot.GetObjectFromPath("/Aircraft/UAV")
Dim sensor As IAgStkObject = stkRoot.GetObjectFromPath("/Aircraft/UAV/Sensor/UAVSensor")
Dim coloradoSprings As IAgStkObject = 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.
Dim timeOfAltMin As IAgCrdnEvent = uav.Vgt.Events("GroundTrajectory.Detic.LLA.Altitude.TimeOfMin")
Dim timeOfAltMax As IAgCrdnEvent = uav.Vgt.Events("GroundTrajectory.Detic.LLA.Altitude.TimeOfMax")

' Set the access time period with the times we figured out above.
Dim access As IAgStkAccess = sensor.GetAccessToObject(coloradoSprings)
access.AccessTimePeriod = AgEAccessTimeType.eUserSpecAccessTime
Dim accessTimePeriod As IAgAccessTimePeriod = TryCast(access.AccessTimePeriodData, IAgAccessTimePeriod)

accessTimePeriod.AccessInterval.State = AgECrdnSmartIntervalState.eCrdnSmartIntervalStateStartStop

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

Dim accessStopEpoch As IAgCrdnEventSmartEpoch = 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.

[Visual Basic .NET] Copy Code
' IAgStkObjectRoot stkRoot: STK Object Model root

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

access.AccessTimePeriod = AgEAccessTimeType.eUserSpecAccessTime
Dim accessTimePeriod As IAgAccessTimePeriod = TryCast(access.AccessTimePeriodData, IAgAccessTimePeriod)

If otherObject.Vgt.EventIntervals.Contains("AvailabilityTimeSpan"Then
     Dim availabilityTimeSpan As IAgCrdnEventInterval = otherObject.Vgt.EventIntervals("AvailabilityTimeSpan")
     accessTimePeriod.AccessInterval.SetImplicitInterval(availabilityTimeSpan)
End If


Enumerate the available constraints collection

[Visual Basic .NET] 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.

Dim arAvailable As Array = accessConstraints.AvailableConstraints()
Dim i As Integer = 0
While i < arAvailable.GetLength(0)
     Dim availName As String = DirectCast(arAvailable.GetValue(i, 0), String)
     Dim eAccessConstraint As AgEAccessConstraints = DirectCast(DirectCast(arAvailable.GetValue(i, 1), Integer), AgEAccessConstraints)
     Console.WriteLine(vbTab & "Constraint {0}: {1} ({2})", i, availName, eAccessConstraint)
     System.Math.Max(System.Threading.Interlocked.Increment(i),i - 1)
End While


GetAccessBetweenObjectsByPath using the output of GetExistingAccesses

[Visual Basic .NET] Copy Code
' IAgStkObjectRoot stkRoot: STK Object Model root

Dim scenario As IAgScenario = TryCast(stkRoot.CurrentScenario, IAgScenario)
Dim accesses As Array = scenario.GetExistingAccesses()

Dim numAccesses As Integer = accesses.GetLength(0)
' number of accesses
Dim object1 As String = accesses.GetValue(00).ToString()
' e.g. "Facility/Fac1"
Dim object2 As String = accesses.GetValue(01).ToString()
' e.g. "Satellite/Sat1"
Dim computed As Boolean = DirectCast(accesses.GetValue(02), Boolean)
' e.g. true  (if access has been computed)
Dim access As IAgStkAccess = scenario.GetAccessBetweenObjectsByPath(object1, object2)


List all exclusion zones of an access constraint

[Visual Basic .NET] Copy Code
' IAgAccessConstraintCollection accessconstraints: Access Constraint collection

Dim excZones As IAgAccessCnstrExclZonesCollection = TryCast(accessconstraints.GetActiveConstraint(AgEAccessConstraints.eCstrExclusionZone), IAgAccessCnstrExclZonesCollection)

If excZones IsNot Nothing Then
     ' ToArray returns a two dimensional array
     ' The second dimension is an array of minLon, minLat, maxLon, maxLat values
     Dim zones As Array = excZones.ToArray(0, -1)

     Dim i As Integer = 0
     While i < zones.GetUpperBound(0)
          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))
          System.Math.Max(System.Threading.Interlocked.Increment(i),i - 1)
     End While
End If


Remove an access constraint from a STK Object

[Visual Basic .NET] Copy Code
' IAgStkObject stkobject: STK Object

Dim accessConstraints As IAgAccessConstraintCollection = stkobject.AccessConstraints

' Remove constraints
accessConstraints.RemoveConstraint(AgEAccessConstraints.eCstrSunElevationAngle)


Coarse grain approach to retrieving a fixed data provider

[Visual Basic .NET] Copy Code
' IAgStkObjectRoot root: STK Object Model root
' IAgStkObject facility: STK Object that contains fixed data provider

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


Coarse grain approach to retrieving a interval data provider

[Visual Basic .NET] Copy Code
' IAgStkObject facility: STK Object

Dim dp As IAgDataPrvInterval = facility.DataProviders.GetDataPrvIntervalFromPath("Lighting Times//Sunlight")
Dim result As IAgDrResult = 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

[Visual Basic .NET] Copy Code
' IAgStkObject facility: STK Object

Dim dp As IAgDataPrvTimeVar = facility.DataProviders.GetDataPrvTimeVarFromPath("Lighting AER")
Dim result As IAgDrResult = dp.Exec("1 Jan 2012 12:00:00.000""1 Jan 2012 12:00:20.000"60)


Coarse grain approach to retrieving data provider information

[Visual Basic .NET] Copy Code
' IAgStkObject facility: Facility STK Object

' The path separator is //
Dim dp As IAgDataProviderInfo = facility.DataProviders.GetDataPrvInfoFromPath("Lighting Times//Sunlight")
Dim dpiName As String = dp.Name
Dim dpiType As AgEDataProviderType = dp.Type
Dim isGroup As Boolean = dp.IsGroup()


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

[Visual Basic .NET] Copy Code
' IAgStkObject facility: STK Object

Dim dpInfo As IAgDataPrvFixed = TryCast(facility.DataProviders("Cartesian Position"), IAgDataPrvFixed)
Dim resInfo As IAgDrResult = dpInfo.Exec()


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

[Visual Basic .NET] Copy Code
' IAgStkObject facility: STK Object

#If Not CSToJava Then
#Else
#End If
Dim elems As Array = New Object() {"x""z"}

Dim dpInfo As IAgDataPrvFixed = TryCast(facility.DataProviders("Cartesian Position"), IAgDataPrvFixed)

' ExecElements expects a one dimensional array of element names
#If Not CSToJava Then
Dim resInfo As IAgDrResult = dpInfo.ExecElements(elems)
#Else
#End If


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

[Visual Basic .NET] Copy Code
' IAgStkObject facility: STK Object

Dim dpInfo As IAgDataPrvTimeVar = TryCast(facility.DataProviders("Lighting AER"), IAgDataPrvTimeVar)
Dim resInfo As IAgDrResult = dpInfo.Exec("1 Jan 2012 12:00:00.000""1 Jan 2012 12:00:20.000"60)


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

[Visual Basic .NET] Copy Code
' IAgStkObject satellite: STK Object

Dim dp As IAgDataPrvTimeVar = TryCast(satellite.DataProviders("Precision Passes"), IAgDataPrvTimeVar)
Dim resInfo As IAgDrResult = dp.ExecSingle("1 Jan 2012 12:00:00.000")


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

[Visual Basic .NET] Copy Code
' IAgStkObject satellite: STK Object

#If Not CSToJava Then
#Else
#End If
Dim times As Array = New Object() {"1 Jan 2012 12:00:00.000""1 Jan 2012 12:00:20.000""1 Jan 2012 12:00:40.000"}
#If Not CSToJava Then
#Else
#End If
Dim elems As Array = New Object() {"Time""Precision Pass Number"}

Dim dp As IAgDataPrvTimeVar = TryCast(satellite.DataProviders("Precision Passes"), IAgDataPrvTimeVar)

' ExecSingleElementsArray expects each safe array parameter to be one dimensional,
' all arrays must have the same length
#If Not CSToJava Then
Dim resInfo As IAgDrTimeArrayElements = dp.ExecSingleElementsArray(times, elems)
#Else
#End If


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

[Visual Basic .NET] Copy Code
' IAgStkObject satellite: STK Object

#If Not CSToJava Then
#Else
#End If
Dim elems As Array = New Object() {"Time""Precision Pass Number"}

Dim dp As IAgDataPrvTimeVar = TryCast(satellite.DataProviders("Precision Passes"), IAgDataPrvTimeVar)

' ExecSingleElements expects as the second parameter a one dimensional array of element names
#If Not CSToJava Then
Dim resInfo As IAgDrResult = dp.ExecSingleElements("1 Jan 2012 12:00:00.000", elems)
#Else
#End If


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

[Visual Basic .NET] Copy Code
' IAgStkObject satObj: Satellite STK Object

#If Not CSToJava Then
#Else
#End If
Dim elems As Array = New Object() {"Range""Radial Rate"}
Dim RICdp As IAgDataPrvTimeVar = TryCast(satObj.DataProviders("Relative Motion"), IAgDataPrvTimeVar)
TryCast(RICdp, IAgDataProvider).PreData = "Satellite/Satellite123"
Dim result As IAgDrResult = RICdp.ExecElements("26 Jan 2015 17:00:00.000""27 Jan 2015 17:00:00.000"120, elems)
Dim datasets As IAgDrDataSetCollection = result.DataSets

If result.DataSets.Count > 0 Then
     Dim arrayRange As System.Array = datasets(0).GetValues()
     Dim arrayRadialRate As System.Array = datasets(1).GetValues()
End If


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

[Visual Basic .NET] Copy Code
' IAgStkObject satObj: Satellite STK Object

#If Not CSToJava Then
#Else
#End If
Dim elems As Array = New Object() {"Time""x""y""z"}
Dim dpVectorChoose As IAgDataProviderGroup = TryCast(satObj.DataProviders("Vector Choose Axes"), IAgDataProviderGroup)
Dim groupPosition As IAgDataProvider = TryCast(dpVectorChoose.Group("Position"), IAgDataProvider)
groupPosition.PreData = "Satellite/Sat2 Body"
Dim timeVarDP As IAgDataPrvTimeVar = TryCast(groupPosition, IAgDataPrvTimeVar)
Dim result As IAgDrResult = timeVarDP.ExecElements("26 Jan 2015 17:00:00.000""27 Jan 2015 17:00:00.000"120, elems)
Dim datasets As IAgDrDataSetCollection = result.DataSets

If result.DataSets.Count > 0 Then
     Dim arrayTime As System.Array = datasets(0).GetValues()
     Dim arrayX As System.Array = datasets(1).GetValues()
     Dim arrayY As System.Array = datasets(2).GetValues()
     Dim arrayZ As System.Array = datasets(2).GetValues()
End If


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

[Visual Basic .NET] Copy Code
' IAgStkObject satellite: Satellite STK Object
' IAgStkObject areatarget: Area Target STK Object

Dim Access As IAgStkAccess = TryCast(satellite.GetAccessToObject(areatarget), IAgStkAccess)
Access.ComputeAccess()

Dim dpInfo As IAgDataPrvInterval = TryCast(Access.DataProviders("Access Data"), IAgDataPrvInterval)

Dim resInfo As IAgDrResult = 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

[Visual Basic .NET] Copy Code
' IAgStkObject satellite: Satellite STK Object
' IAgStkObject areatarget: Area Target STK Object

Dim access As IAgStkAccess = TryCast(satellite.GetAccessToObject(areatarget), IAgStkAccess)
access.ComputeAccess()

Dim dp As IAgDataPrvInterval = TryCast(access.DataProviders("Access Data"), IAgDataPrvInterval)

#If Not CSToJava Then
#Else
#End If
Dim elems As Array = 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
#If Not CSToJava Then
Dim resInfo As IAgDrResult = dp.ExecElements("1 Jan 2012 12:00:00.000""2 Jan 2012 12:00:00.000", elems)
#Else
#End If


Execute an object coverage data provider and dump its result

[Visual Basic .NET] Copy Code
' IAgStkObjectRoot root: STK Object

Dim aircraft As IAgStkObject = root.CurrentScenario.Children("aircraft340")

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

Dim provider As IAgDataPrvTimeVar = TryCast(objectCoverage.DataProviders("FOM by Time"), IAgDataPrvTimeVar)

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

For Each section As IAgDrSubSection In result.Sections
     For Each interval As IAgDrInterval In section.Intervals
          #If Not CSToJava Then
          #Else
          #End If
          Dim arBoundaries As Array = New Object() {12345}

          ' MultipleThresholdCrossings expects the second parameter
          ' to be a one demensional array of boundary index values
          #If Not CSToJava Then
          Dim arRanges As Array = interval.MultipleThresholdCrossings("FOM Value", arBoundaries)
          #Else
          #End If

          Dim iRange As Integer = 0
          While iRange < arRanges.GetLength(0)
               Console.Write(vbLf & "Range: {0}" & vbLf, iRange)

               Dim arTimeSpans As Array = TryCast(arRanges.GetValue(iRange), Array)
               Dim iSpan As Integer = 0
               While iSpan < arTimeSpans.GetLength(0)
                    Dim strStart As String = arTimeSpans.GetValue(iSpan, 0).ToString()
                    Dim strStop As String = arTimeSpans.GetValue(iSpan, 1).ToString()

                    Console.Write("Start: {0}" & vbTab & "Stop: {1}" & vbLf, strStart, strStop)
                    System.Math.Max(System.Threading.Interlocked.Increment(iSpan),iSpan - 1)
               End While
               System.Math.Max(System.Threading.Interlocked.Increment(iRange),iRange - 1)
          End While
     Next
Next


Extract data from IAgDrDataSetCollection (generic)

[Visual Basic .NET] Copy Code
' IAgDrDataSetCollection datasets: Data provider data sets

For Each name As [StringIn 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.
     Dim dataset As IAgDrDataSet = datasets.GetDataSetByName(name)

     Dim datasetValues As Array = dataset.GetValues()

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

     For Each value As Object In datasetValues
          Console.WriteLine(vbTab & "{0}", value.ToString())
     Next
Next


Extract data from IAgDrDataSetCollection across multiple intervals.

[Visual Basic .NET] Copy Code
' IAgDrDataSetCollection datasets: Data provider data sets

For Each [setAs IAgDrDataSet In datasets
     Console.WriteLine("{0}", [set].ElementName)
     For Each value As Object In [set].GetValues()
          Console.WriteLine(vbTab & "{0}", value.ToString())
     Next
Next


Extract data from IAgDrIntervalCollection (generic)

[Visual Basic .NET] Copy Code
' IAgDrIntervalCollection intervals: Data provider intervals

' Enumerate IAgDrIntervalCollection collection
For Each interval As IAgDrInterval In intervals
     Console.WriteLine("{0} - {1}", interval.StartTime, interval.StopTime)

     For Each dataset As IAgDrDataSet In interval.DataSets
          Dim values As Array = dataset.GetValues()

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

          For Each value As Object In values
               Console.WriteLine(vbTab & "{0}", value.ToString())
          Next
     Next
Next


Extract data from IAgDrResult based on its category (generic)

[Visual Basic .NET] Copy Code
' IAgDrResult result: Data provider result

' Look at the Category property to find out which interface to use
Select Case result.Category
     Case AgEDrCategories.eDrCatDataSetList
          Dim datasets As IAgDrDataSetCollection = result.DataSets
          ' See IAgDrDataSetCollection inteface
          Exit Select
     Case AgEDrCategories.eDrCatIntervalList
          Dim intervals As IAgDrIntervalCollection = result.Intervals
          ' See IAgDrIntervalCollection interface
          Exit Select
     Case AgEDrCategories.eDrCatMessage
          Dim message As IAgDrTextMessage = result.Message
          ' See IAgDrTextMessage interface
          Exit Select
     Case AgEDrCategories.eDrCatSubSectionList
          Dim section As IAgDrSubSectionCollection = result.Sections
          ' See IAgDrSubSectionCollection interface
          Exit Select
End Select


Extract data from IAgDrSubSectionCollection (generic)

[Visual Basic .NET] Copy Code
' IAgDrSubSectionCollection subSection: Subsection collection

For Each section As IAgDrSubSection In subSection
     Console.WriteLine(section.Title)

     For Each interval As IAgDrInterval In section.Intervals
          Console.WriteLine(vbTab & "Time {0} - {1}", interval.StartTime, interval.StopTime)

          For Each dataset As IAgDrDataSet In interval.DataSets
               Dim values As Array = dataset.GetValues()

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

               For Each value As Object In values
                    Console.WriteLine(vbTab & vbTab & "{0}", value.ToString())
               Next
          Next
     Next
Next


Extract data from IAgDrTextMessage (generic)

[Visual Basic .NET] Copy Code
' IAgDrTextMessage message: 

For Each messagei As Object In message.Messages
     Console.WriteLine(messagei)
Next


Set STK Object Display to always on

[Visual Basic .NET] Copy Code
' IAgStkObject stkObject: STK Object

Dim display As IAgDisplayTm = TryCast(stkObject, IAgDisplayTm)
display.SetDisplayStatusType(AgEDisplayTimesType.eAlwaysOn)


Set STK Object Display to use during access mode

[Visual Basic .NET] Copy Code
' IAgStkObject stkObject: STK Object

' Attempt to cast STK Object to the IAgDisplayTm interface
Dim display As IAgDisplayTm = TryCast(stkObject, IAgDisplayTm)
If display IsNot Nothing Then
     ' Configure during access
     If display.IsDisplayStatusTypeSupported(AgEDisplayTimesType.eDuringAccess) Then
          display.SetDisplayStatusType(AgEDisplayTimesType.eDuringAccess)

          Dim duringAccess As IAgDuringAccess = TryCast(display.DisplayTimesData, IAgDuringAccess)

          ' Add subsequent existing stk objects to access diplay ...
          duringAccess.AccessObjects.Add("Satellite/satellite1")
          duringAccess.AccessObjects.Add("Star/star1")
     End If
End If


Set STK Object Display to use intervals mode

[Visual Basic .NET] Copy Code
' IAgStkObject stkObject: STK Object

' Attempt to cast STK Object to the IAgDisplayTm interface
Dim display As IAgDisplayTm = TryCast(stkObject, IAgDisplayTm)
If display IsNot Nothing Then
     ' Configure display intervals
     If display.IsDisplayStatusTypeSupported(AgEDisplayTimesType.eUseIntervals) Then
          display.SetDisplayStatusType(AgEDisplayTimesType.eUseIntervals)

          ' Get IAgIntervalCollection interface
          Dim intervalCollection As IAgIntervalCollection = TryCast(display.DisplayTimesData, IAgIntervalCollection)
          intervalCollection.RemoveAll()

          ' Add subsequent intervals...
          intervalCollection.Add("1 Jan 2012 12:00:00.00""1 Jan 2012 13:00:00.000")
     End If
End If


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

[Visual Basic .NET] Copy Code
' IAgScenario scenario: Scenario object

Dim gfx As IAgScGraphics = 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
#If Not CSToJava Then
#Else
#End If
Dim objects As Array = New Object() {"Facility/facility1""Facility/facility2"}
#If Not CSToJava Then
gfx.HideObjects(objects, "1")
gfx.ShowObjects(objects, "all")
#Else
#End If


Configure 3D data display

[Visual Basic .NET] Copy Code
' IAgVODataDisplayCollection datadisplaycol: Data Display Collection

' Add existing data display
' See AvailableData property for available data display
Dim displayElement As IAgVODataDisplayElement = 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

[Visual Basic .NET] Copy Code
' IAgVOModel model: VO Model from an STK Object

' Configure articulation
Dim modelArticulation As IAgVOModelArtic = model.Articulation
modelArticulation.EnableDefaultSave = False
modelArticulation.SaveArticFileOnSave = True

' Set our articulation and transformations
' For this sample, these articulations exist for a default satellite model
Dim levelOfDetail As Integer = 0
Dim articulation As String = "Satellite"
Dim transformation As String = "Size"


' Get the current transition value
Dim currentTransVal As Double = modelArticulation.GetTransValue(levelOfDetail, articulation, transformation)

' Change the value
Dim newTransVal As Double = currentTransVal * 0.5

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


Configure 3D model file

[Visual Basic .NET] Copy Code
' IAgVOModel model: VO model

' Set new ModelFile.Filename
model.ModelType = AgEModelType.eModelFile
Dim modelFile As IAgVOModelFile = TryCast(model.ModelData, IAgVOModelFile)
modelFile.Filename = "\STKData\VO\Models\Space\alexis.mdl"

' Configure basic settings
model.Visible = True
model.ScaleValue = 4.8


Configure 3D model level of detail

[Visual Basic .NET] Copy Code
' IAgVOModel model: VO Model from an STK Object

' Configure level of details
Dim detail As IAgVODetailThreshold = model.DetailThreshold
detail.EnableDetailThreshold = True

' (assuming unit preferences set to km)
detail.All = 2.51189
detail.ModelLabel = 158489
detail.MarkerLabel = 2511890
detail.Marker = 25110000
detail.Point = 1000000000000


Configure 3D vector

[Visual Basic .NET] Copy Code
' IAgVOVector vector: VO Vector

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

' Draw on Central Body
Dim body As IAgVORefCrdnVector = TryCast(vector.RefCrdns.GetCrdnByName(AgEGeometricElemType.eAxesElem, DirectCast(m_Root.CentralBodies("Earth").Vgt.Vectors("Moon"), IAgCrdn).QualifiedPath), IAgVORefCrdnVector)
DirectCast(body, IAgVORefCrdn).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


List all 3D model articulations

[Visual Basic .NET] 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

Dim modelArticulation As IAgVOModelArtic = model.Articulation

Dim lod As Integer = 0
While lod < modelArticulation.LODCount
     ' Get all articulations
     ' GetAvailableArticulations returns a one dimensional array of articulation names
     Dim articulations As Array = modelArticulation.GetAvailableArticulations(lod)

     ' Enumerate through available articulations
     Dim articulation As Integer = 0
     While articulation < articulations.Length
          ' We need the articulation string to call the GetAvailableTransformations function
          Dim articulationString As [String] = TryCast(articulations.GetValue(articulation), [String])

          ' Get all transformations
          Dim transformations As IAgVOModelTransCollection = modelArticulation.GetAvailableTransformations(lod, articulationString)

          ' Enumerate through available transformations
          For Each trans As IAgVOModelTrans In transformations
               Console.WriteLine("Name: {0}, Current {1}, Max {2}, Min {3}", trans.Name, trans.Value, trans.Max, trans.Min)
          Next
          System.Math.Max(System.Threading.Interlocked.Increment(articulation),articulation - 1)
     End While
     System.Math.Max(System.Threading.Interlocked.Increment(lod),lod - 1)
End While


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

[Visual Basic .NET] Copy Code
' IAgStkObjectRoot root: STK Object Root

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

Dim firstSunlightEpoch As IAgCrdnEvent = airspaceAreaTarget.Vgt.Events("LightingIntervals.Sunlight.First.Start")
Dim lastSunlightEpoch As IAgCrdnEvent = airspaceAreaTarget.Vgt.Events("LightingIntervals.Sunlight.First.Stop")

uavAircraft.ObjectCoverage.UseObjectTimes = False
Dim startEpoch As IAgCrdnEventSmartEpoch = uavAircraft.ObjectCoverage.AccessInterval.GetStartEpoch()
startEpoch.SetImplicitTime(firstSunlightEpoch)

Dim stopEpoch As IAgCrdnEventSmartEpoch = 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

[Visual Basic .NET] Copy Code
' IAgTransmitter geoTransmitter: Transmitter object
' IAgReceiver facilityReceiver: Receiver object
' IAgAntenna facilityDish: Antenna object
' IAgRFEnvironment scenarioRFEnv: Scenario RF Environment

Dim xmtrAsStkObject As IAgStkObject = TryCast(geoTransmitter, IAgStkObject)
Dim rcvrAsStkObject As IAgStkObject = TryCast(facilityReceiver, 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")
Dim complexTrans As IAgTransmitterModelComplex = TryCast(geoTransmitter.Model, 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

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

'Set the beamwidth of the parablic antenna to 2 degrees
Dim helix As IAgAntennaModelHelix = TryCast(complexTrans.AntennaControl.EmbeddedModel, IAgAntennaModelHelix)
helix.NumberOfTurns = 30

'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")
Dim complexRcvr As IAgReceiverModelComplex = TryCast(facilityReceiver.Model, 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.
Dim parabolic As IAgAntennaModelParabolic = TryCast(facilityDish.Model, IAgAntennaModelParabolic)
parabolic.InputType = AgEAntennaModelInputType.eAntennaModelInputTypeDiameter
parabolic.Diameter = 5

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

'Compute access
linkAccess.ComputeAccess()

' Get the access intervals
Dim accessIntervals As IAgIntervalCollection = linkAccess.ComputedAccessIntervalTimes

#If Not CSToJava Then
' Extract the access intervals and the range information for each access interval
Dim dataPrvElements As Array = New Object() {"Time""Xmtr Gain""Rcvr Gain""Eb/No""BER"}
#Else
#End If

Dim dp As IAgDataPrvTimeVar = TryCast(linkAccess.DataProviders("Link Information"), IAgDataPrvTimeVar)

Dim index0 As Integer = 0
While index0 < accessIntervals.Count
     Dim startTime As Object = Nothing, stopTime As Object = Nothing

     #If Not CSToJava Then
     accessIntervals.GetInterval(index0, startTime, stopTime)
     #Else
     #End If

     #If Not CSToJava Then
     Dim result As IAgDrResult = dp.ExecElements(startTime, stopTime, 60, dataPrvElements)
     #Else
     #End If

     Dim timeValues As Array = result.DataSets(0).GetValues()
     Dim xmtrGain As Array = result.DataSets(1).GetValues()
     Dim rcvrGain As Array = result.DataSets(2).GetValues()
     Dim ebno As Array = result.DataSets(3).GetValues()
     Dim ber As Array = result.DataSets(4).GetValues()

     Dim index1 As Integer = 0
     While index1 < timeValues.GetLength(0)
          Dim time As String = DirectCast(timeValues.GetValue(index1), String)
          Dim xmtrGainVal As Double = DirectCast(xmtrGain.GetValue(index1), Double)
          Dim rcvrGainVal As Double = DirectCast(rcvrGain.GetValue(index1), Double)
          Dim ebnoVal As Double = DirectCast(ebno.GetValue(index1), Double)
          Dim berVal As Double = DirectCast(ber.GetValue(index1), Double)
          Console.WriteLine("{0}: Xmtr Gain = {1} Rcvr Gain = {2} Eb/No={3} BER={4}", time, xmtrGainVal, rcvrGainVal, ebnoVal, berVal)
          System.Threading.Interlocked.Increment(index1)
     End While

     Console.WriteLine()
     System.Threading.Interlocked.Increment(index0)
End While



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

[Visual Basic .NET] Copy Code
' IAgTransmitter geoTransmitter: Transmitter object
' IAgReceiver facilityReceiver: Receiver object

Dim xmtrAsStkObject As IAgStkObject = TryCast(geoTransmitter, IAgStkObject)
Dim rcvrAsStkObject As IAgStkObject = TryCast(facilityReceiver, IAgStkObject)

'Set the transmitter to the simple model
geoTransmitter.SetModel("Simple Transmitter Model")
Dim simpleTrans As IAgTransmitterModelSimple = TryCast(geoTransmitter.Model, 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

'Set the receiver to the simple model
facilityReceiver.SetModel("Simple Receiver Model")
Dim simpleRcvr As IAgReceiverModelSimple = TryCast(facilityReceiver.Model, IAgReceiverModelSimple)

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

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

'Compute access
linkAccess.ComputeAccess()

' Get the access intervals
Dim accessIntervals As IAgIntervalCollection = linkAccess.ComputedAccessIntervalTimes

#If Not CSToJava Then
' Extract the access intervals and the range information for each access interval
Dim dataPrvElements As Array = New Object() {"Time""Eb/No""BER"}
#Else
#End If

Dim dp As IAgDataPrvTimeVar = TryCast(linkAccess.DataProviders("Link Information"), IAgDataPrvTimeVar)

Dim index0 As Integer = 0
While index0 < accessIntervals.Count
     Dim startTime As Object = Nothing, stopTime As Object = Nothing
     #If Not CSToJava Then
     accessIntervals.GetInterval(index0, startTime, stopTime)
     #Else
     #End If

     #If Not CSToJava Then
     Dim result As IAgDrResult = dp.ExecElements(startTime, stopTime, 60, dataPrvElements)
     #Else
     #End If

     Dim timeValues As Array = result.DataSets(0).GetValues()
     Dim ebno As Array = result.DataSets(1).GetValues()
     Dim ber As Array = result.DataSets(2).GetValues()

     Dim index1 As Integer = 0
     While index1 < timeValues.GetLength(0)
          Dim time As String = DirectCast(timeValues.GetValue(index1), String)
          Dim ebnoVal As Double = DirectCast(ebno.GetValue(index1), Double)
          Dim berVal As Double = DirectCast(ber.GetValue(index1), Double)
          Console.WriteLine("{0}: Eb/No={1} BER={2}", time, ebnoVal, berVal)
          System.Threading.Interlocked.Increment(index1)
     End While

     Console.WriteLine()
     System.Threading.Interlocked.Increment(index0)
End While



Add a STK Object to constellation using IAgStkObject interface

[Visual Basic .NET] 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

[Visual Basic .NET] Copy Code
' IAgConstellation constellation: Constellation object

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


Compute a coverage definition access

[Visual Basic .NET] 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)

[Visual Basic .NET] Copy Code
' IAgStkObjectRoot root: STK Object Model Root

' Create the CoverageDefinition
Dim cd As IAgCoverageDefinition = TryCast(root.CurrentScenario.Children.[New](AgESTKObjectType.eCoverageDefinition, "cd1"), IAgCoverageDefinition)


Define a coverage definition assets

[Visual Basic .NET] Copy Code
' IAgCoverageDefinition coverageDefinition: Coverage definition object

Dim assetCollection As IAgCvAssetListCollection = coverageDefinition.AssetList
Dim assetName As String = "Satellite/sat1"
Dim subAssetName As String = "Facility/North"

' Remove asset collection if necessary
assetCollection.RemoveAll()

Dim satAsset1 As IAgCvAssetListElement = Nothing

' AvailableAssets returns a one dimensional array of assets
If Array.IndexOf(assetCollection.AvailableAssets, assetName) <> -1 Then
     ' Add assets to coverageDefintion
     If assetCollection.CanAssignAsset(assetName) Then
          satAsset1 = assetCollection.Add(assetName)

          ' Configure asset element
          satAsset1.Required = True
          satAsset1.Grouping = AgECvAssetGrouping.eGrouped
     End If

     ' Add subassets to assets
     If satAsset1.ContainsSubAssets() Then
          Dim subAssetCollection As IAgCvAssetListCollection = satAsset1.SubAssetList
          If subAssetCollection.CanAssignAsset(subAssetName) Then
               assetCollection.Add(subAssetName)
          End If
     End If
End If


Define a coverage definition by points

[Visual Basic .NET] Copy Code
' IAgCoverageDefinition coverageDefinition: Coverage Definition
' String regionFilePath: Path of region file

' Get the IAgCvGrid interface
Dim cvGrid As IAgCvGrid = coverageDefinition.Grid

' Define custom region
cvGrid.BoundsType = AgECvBounds.eBoundsCustomRegions
Dim oBoundsCustom As IAgCvBoundsCustomRegions = TryCast(cvGrid.Bounds, IAgCvBoundsCustomRegions)
oBoundsCustom.RegionFiles.Add(regionFilePath)
oBoundsCustom.AreaTargets.Add("AreaTarget/AreaTarget1")

' Create an Array of LLA points
' Array should contain Lat, Lon, Alt values
#If Not CSToJava Then
#Else
#End If
Dim points As Array = New Object(,) {{69.346423789, -50.2607483720}, {39.613371741, -66.2854299030}, {39.880319688, -73.8817674790}, {40.700636942, -112.249999980}}

' SetPointsLLA expects a two dimensional array of LLA points
#If Not CSToJava Then
coverageDefinition.PointDefinition.SetPointsLLA(points)
#Else
#End If


Define a custom grid using area targets

[Visual Basic .NET] Copy Code
' IAgCoverageDefinition coverageDefinition: Coverage Definition

' Get the IAgCvGrid interface
Dim cvGrid As IAgCvGrid = coverageDefinition.Grid

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

' Get IAgCvBoundsCustomRegions interface
Dim boundRegion As IAgCvBoundsCustomRegions = TryCast(cvGrid.Bounds, IAgCvBoundsCustomRegions)

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


Define a grid resolution by latitude and longitude

[Visual Basic .NET] Copy Code
' IAgCoverageDefinition coverageDefinition: Coverage definition object

' Get the IAgCvGrid interface
Dim grid As IAgCvGrid = coverageDefinition.Grid

' Set resolution type
grid.ResolutionType = AgECvResolution.eResolutionLatLon

' Get the resolution interface
Dim resolution As IAgCvResolution = grid.Resolution
Dim latLonResolution As IAgCvResolutionLatLon = TryCast(resolution, IAgCvResolutionLatLon)

' Assign LatLon used to define grid resolution
' Uses Angle Dimension
latLonResolution.LatLon = 3


Define and configure grid constraint options

[Visual Basic .NET] Copy Code
' IAgCoverageDefinition coverageDefinition: Coverage definition object

Dim pointDefinition As IAgCvPointDefinition = 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
coverageDefinition.PointDefinition.GroundAltitudeMethod = AgECvGroundAltitudeMethod.eCvGroundAltitudeMethodUsePointAlt


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

[Visual Basic .NET] Copy Code
' IAgStkObjectRoot stkRoot: STK Object Root
' IAgCoverageDefinition coverage: An instance of the coverage definition object

Dim currentDateFormat As String = 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.
Dim minStartTime As IAgDate = Nothing
Dim maxStartTime As IAgDate = Nothing

For Each cvAsset As IAgCvAssetListElement In coverage.AssetList
     Dim subAsset As IAgStkObject = stkRoot.GetObjectFromPath(cvAsset.ObjectName)
     If subAsset.Vgt.EventIntervals.Contains("AvailabilityTimeSpan"Then
          Dim availableTimeSpan As IAgCrdnEventIntervalResult = subAsset.Vgt.EventIntervals("AvailabilityTimeSpan").FindInterval()
          Dim startDate As IAgDate = stkRoot.ConversionUtility.NewDate(currentDateFormat, availableTimeSpan.Interval.Start.ToString())
          If Not (minStartTime IsNot Nothing) OrElse startDate.OLEDate < minStartTime.OLEDate Then
               minStartTime = startDate
          End If

          Dim stopTime As IAgDate = stkRoot.ConversionUtility.NewDate(currentDateFormat, availableTimeSpan.Interval.[Stop].ToString())
          If Not (maxStartTime IsNot Nothing) OrElse stopTime.OLEDate > maxStartTime.OLEDate Then
               maxStartTime = stopTime
          End If
     End If
Next

If minStartTime IsNot Nothing AndAlso maxStartTime IsNot Nothing Then
     ' 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))
End If

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


Configure a coverage definition adaptive sampling

[Visual Basic .NET] Copy Code
' IAgCoverageDefinition coverageDefinition: Coverage definition object

' Get the Sampling interface
Dim advanced As IAgCvAdvanced = coverageDefinition.Advanced
Dim sampling As IAgAccessSampling = advanced.Sampling

' Set the Sampling Method
sampling.SetType(AgESamplingMethod.eSamplingMethodAdaptive)
Dim adaptive As IAgSamplingMethodAdaptive = TryCast(sampling.Strategy, IAgSamplingMethodAdaptive)

' Set properties on the Adaptive sampling method interface
adaptive.MaxTimeStep = 180
adaptive.MinTimeStep = 1


Configure a coverage definition fixed step sampling

[Visual Basic .NET] Copy Code
' IAgCoverageDefinition coverageDefinition: Coverage definition object

' Get the Sampling interface
Dim advanced As IAgCvAdvanced = coverageDefinition.Advanced
Dim sampling As IAgAccessSampling = advanced.Sampling

' Set the Sampling Method
sampling.SetType(AgESamplingMethod.eSamplingMethodFixedStep)
Dim fixedStep As IAgSamplingMethodFixedStep = TryCast(sampling.Strategy, IAgSamplingMethodFixedStep)

' Set properties on the Fixed Stop sampling method interface
fixedStep.FixedTimeStep = 360
fixedStep.TimeBound = 5


Configure a coverage definition graphics

[Visual Basic .NET] Copy Code
' IAgCvGraphics cvGraphics: Coverage definition

' Configure animation
Dim cvAnimation As IAgCvGfxAnimation = cvGraphics.Animation
cvAnimation.IsSatisfactionVisible = True
cvAnimation.Color = Color.Green

' Configure progress
Dim cvProgress As IAgCvGfxProgress = cvGraphics.Progress
cvProgress.IsVisible = True
cvProgress.Color = Color.Red

' Configure static
Dim cvStatic As IAgCvGfxStatic = cvGraphics.[Static]
cvStatic.Color = Color.Blue
cvStatic.MarkerStyle = "Star"


Create a facility (on current scenario central body)

[Visual Basic .NET] Copy Code
' IAgStkObjectRoot root: STK Object Model root

' Create a facility on current scenario central body
Dim facility As IAgFacility = TryCast(root.CurrentScenario.Children.[New](AgESTKObjectType.eFacility, "MyFacility"), IAgFacility)


Create a facility from facility database

[Visual Basic .NET] Copy Code
' IAgStkObjectRoot root: STK Object Model root

' Get STK database location using Connect
Dim result As IAgExecCmdResult = root.ExecuteCommand("GetDirectory / Database Facility")
Dim facDataDir As String = result(0)
Dim filelocation As String = Path.Combine(facDataDir, "stkFacility.fd")

' Import object from database using Connect
Dim command As String = "ImportFromDB * Facility """ + filelocation + """ Class Facility SiteName Weilheim"
root.ExecuteCommand(command)

Dim facility As IAgFacility = TryCast(root.GetObjectFromPath("Facility/Weilheim"), IAgFacility)


Create a facility on Earth at lat/lon/alt

[Visual Basic .NET] Copy Code
' IAgStkObjectRoot root: STK Object Model root

Dim facility As IAgFacility = TryCast(root.CurrentScenario.Children.NewOnCentralBody(AgESTKObjectType.eFacility, "MyFacility""Earth"), 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

[Visual Basic .NET] Copy Code
' IAgStkObjectRoot root: STK Object Model root

Dim facObject As IAgFacility = TryCast(root.CurrentScenario.Children.NewOnCentralBody(AgESTKObjectType.eFacility, "Facility1""Mars"), 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

[Visual Basic .NET] 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

[Visual Basic .NET] Copy Code
' IAgFigureOfMerit fom: Figure of Merit properties

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

' Get IAgFmDefCompute interface
Dim defComp As IAgFmDefCompute = TryCast(fom.Definition, IAgFmDefCompute)

If defComp.IsComputeTypeSupported(AgEFmCompute.ePercentAbove) Then
     ' Set Compute type to supported compute option
     defComp.SetComputeType(AgEFmCompute.ePercentAbove)

     ' Get compute option compute interface
     Dim fomData As IAgFmDefDataPercentLevel = TryCast(defComp.Compute, IAgFmDefDataPercentLevel)
     fomData.PercentLevel = 0.25
End If


Configure coverage time figure of merit

[Visual Basic .NET] Copy Code
' IAgFigureOfMerit fom: Figure of Merit properties

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

' Get IAgFmDefCompute interface
Dim defComp As IAgFmDefCompute = TryCast(fom.Definition, IAgFmDefCompute)

If defComp.IsComputeTypeSupported(AgEFmCompute.eTotalTimeAbove) Then
     ' Set Compute type to supported compute option
     defComp.SetComputeType(AgEFmCompute.eTotalTimeAbove)

     ' Get compute option compute interface
     Dim fomData As IAgFmDefDataMinAssets = TryCast(defComp.Compute, IAgFmDefDataMinAssets)
     fomData.MinAssets = 15
End If


Configure figure of merit Age Of Data definition

[Visual Basic .NET] Copy Code
' IAgFigureOfMerit fom: Figure of Merit properties

' Get the IAgFmDefAgeOfData interface
fom.SetDefinitionType(AgEFmDefinitionType.eFmAgeOfData)
Dim ageOfData As IAgFmDefAgeOfData = TryCast(fom.Definition, IAgFmDefAgeOfData)

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


Configure figure of merit contours

[Visual Basic .NET] 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)
Dim firstLevel As IAgFmGfxLevelAttributesElement = contours.LevelAttributes(0)
firstLevel.Color = Color.Blue

' Add one level (individually)
Dim level As IAgFmGfxLevelAttributesElement = contours.LevelAttributes.AddLevel(55)
level.Color = Color.Red


Configure figure of merit definition altitude access constraint

[Visual Basic .NET] Copy Code
' IAgFigureOfMerit fom: Figure of Merit properties

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

' Get IAgFmDefAccessConstraint interface
Dim defAccessCnstr As IAgFmDefAccessConstraint = TryCast(fom.Definition, IAgFmDefAccessConstraint)

' Confiure access constraint properties
defAccessCnstr.SetComputeType(AgEFmCompute.eMaximum)
defAccessCnstr.AcrossAssets = AgEFmAcrossAssets.eFmMinimum
defAccessCnstr.TimeStep = 60


Configure figure of merit Scalar Calculation definition

[Visual Basic .NET] Copy Code
' IAgFigureOfMerit fom: Figure of Merit properties

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


Configure figure of merit Scalar Calculation definition using VGT

[Visual Basic .NET] Copy Code
' IAgFigureOfMerit fom: Figure of Merit properties
' IAgStkObjectRoot stkRoot: STK Object Model root

' Get the qualified path of a Scalar Calculation (e.g.
Dim provider As IAgCrdnProvider = stkRoot.VgtRoot.GetProvider("CentralBody/Sun")
Dim calcScalar As IAgCrdnCalcScalar = provider.CalcScalars(0)
Dim calcScalarQualifiedPath As String = TryCast(calcScalar, IAgCrdn).QualifiedPath

' Set the Scalar Calculation definition using the qualified path
Dim scalarCalculation As IAgFmDefScalarCalculation = fom.SetScalarCalculationDefinition(calcScalarQualifiedPath)


Configure figure of merit System Response Time

[Visual Basic .NET] Copy Code
' IAgFigureOfMerit fom: Figure of Merit properties

fom.SetDefinitionType(AgEFmDefinitionType.eFmSystemResponseTime)
Dim systemResponseTime As IAgFmDefSystemResponseTime = TryCast(fom.Definition, IAgFmDefSystemResponseTime)

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


Configure figure of merit System Response Time reset

[Visual Basic .NET] Copy Code
' IAgFigureOfMerit fom: Figure of Merit properties

fom.SetDefinitionType(AgEFmDefinitionType.eFmSystemResponseTime)
Dim systemResponseTime As IAgFmDefSystemResponseTime = TryCast(fom.Definition, IAgFmDefSystemResponseTime)

systemResponseTime.CommandStationPath = "NONE"


Create a figure of merit on a coverage definition

[Visual Basic .NET] Copy Code
' IAgCoverageDefinition covdef: Coverage Definition object

' Get the coverage definition as a IAgStkObject interface
Dim covdefObject As IAgStkObject = TryCast(covdef, IAgStkObject)

' Create the figure of merit
Dim fom As IAgFigureOfMerit = TryCast(covdefObject.Children.[New](AgESTKObjectType.eFigureOfMerit, "MyFigureOfMerit"), IAgFigureOfMerit)


Inspect grid by selecting a point

[Visual Basic .NET] Copy Code
' IAgFigureOfMerit fom: Figure of Merit properties

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

Dim pointFom As IAgDataPrvTimeVar = TryCast(gridInspector.PointFOM, IAgDataPrvTimeVar)
Dim pointFomResult As IAgDrResult = pointFom.ExecSingle("1 Jan 2012 12:00:00.00")

Dim pointSatisfaction As IAgDataPrvInterval = TryCast(gridInspector.PointSatisfaction, IAgDataPrvInterval)
Dim pointSatisfactionResult As IAgDrResult = pointSatisfaction.Exec("1 Jan 2012 12:00:00.00""2 Jan 2012 12:00:00.00")

Dim regionFom As IAgDataPrvTimeVar = TryCast(gridInspector.RegionFOM, IAgDataPrvTimeVar)
Dim regionFomResult As IAgDrResult = regionFom.ExecSingle("1 Jan 2012 12:00:00.00")

Dim regionSatisfaction As IAgDataPrvInterval = TryCast(gridInspector.RegionSatisfaction, IAgDataPrvInterval)
Dim regionSatisfactionResult As IAgDrResult = 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

[Visual Basic .NET] Copy Code
' IAgFigureOfMerit fom: Figure of Merit properties

Dim acd As IAgFmDefAccessConstraint = fom.SetAccessConstraintDefinition(AgEFmConstraintName.eFmAzimuthRate)


Set the figure of merit definition to access constraint by name

[Visual Basic .NET] Copy Code
' IAgFigureOfMerit fom: Figure of Merit properties

Dim defAccessCnstr As IAgFmDefAccessConstraint = fom.SetAccessConstraintDefinitionName("AzimuthRate")

' Confiure access constraint properties
defAccessCnstr.SetComputeType(AgEFmCompute.eMaximum)
defAccessCnstr.AcrossAssets = AgEFmAcrossAssets.eFmMinimum
defAccessCnstr.TimeStep = 60


Add MTO track

[Visual Basic .NET] Copy Code
' IAgMto mto: MTO object

Dim trackCollection As IAgMtoTrackCollection = mto.Tracks

#If Not CSToJava Then
#Else
#End If
Dim time As Array = New Object() {"1 Jan 2012 12:10:00.000""1 Jan 2012 12:20:00.000"}
#If Not CSToJava Then
#Else
#End If
Dim latitude As Array = New Object() {27.97, -26.51}
#If Not CSToJava Then
#Else
#End If
Dim longitude As Array = New Object() {-80.01119.42}
#If Not CSToJava Then
#Else
#End If
Dim altitude As Array = New Object() {20.144.2}

' AddTrack expects each safe array parameter to be two dimensional,
' all arrays must have the same length
#If Not CSToJava Then
Dim track As IAgMtoTrack = trackCollection.AddTrack(1, time, latitude, longitude, altitude)
#Else
#End If


Configure MTO

[Visual Basic .NET] Copy Code
' IAgStkObjectRoot root: STK Object Model root
' IAgMto mto: Mto Object

Dim scenario As IAgScenario = TryCast(root.CurrentScenario, IAgScenario)
scenario.SetTimePeriod("1 Feb 2008 12:00:00.000""2 Feb 2008 12:00:00.000")

' Number of tracks and points to add
Dim trackCount As Double = 10
Dim pointCount As Double = 20

' Initial values from which we will interpolate
Dim lat0 As Double = 40.04
Dim lon0 As Double = -75.595
Dim alt0 As Double = 0

root.BeginUpdate()
' Call BeginUpdate for STK engine to delay updates
Dim i As Integer = 0
While i < trackCount
     Dim track As IAgMtoTrack = mto.Tracks.Add(i)
     Dim [date] As IAgDate = root.ConversionUtility.NewDate("UTCG"TryCast(scenario.StartTime, String))

     ' Interpolate mto points
     Dim j As Integer = 0
     While j < pointCount
          Dim lat As Double = lat0 + 1 * i
          Dim lon As Double = lon0 + 0.1 * j
          Dim alt As Double = alt0

          [date] = [date].Add("sec"120)

          track.Points.AddPoint([date].Format("UTCG"), lat, lon, alt)
          System.Threading.Interlocked.Increment(j)
     End While
     System.Threading.Interlocked.Increment(i)
End While

root.EndUpdate()


Create a MTO (on current scenario central body)

[Visual Basic .NET] Copy Code
' IAgStkObjectRoot root: STK Object Model root

' Create the MTO
Dim mto As IAgMto = TryCast(root.CurrentScenario.Children.[New](AgESTKObjectType.eMTO, "mto1"), IAgMto)


Extend MTO track

[Visual Basic .NET] Copy Code
' IAgMtoTrackPointCollection trackPointCollection: Track point collection

#If Not CSToJava Then
#Else
#End If
Dim time As Array = New Object() {"1 Jan 2012 12:20:00.000""1 Jan 2012 12:30:00.000"}
#If Not CSToJava Then
#Else
#End If
Dim latitude As Array = New Object() {-18.3519.55}
#If Not CSToJava Then
#Else
#End If
Dim longitude As Array = New Object() {-42.183.21}
#If Not CSToJava Then
#Else
#End If
Dim altitude As Array = New Object() {30.5215.81}

' Extend expects each parameter to be a two dimensional array,
' all arrays must have the same length
#If Not CSToJava Then
trackPointCollection.Extend(time, latitude, longitude, altitude)
#Else
#End If


Load MTO track points from file

[Visual Basic .NET] 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

[Visual Basic .NET] Copy Code
' IAgMto mto: MTO object

Dim trackCollection As IAgMtoTrackCollection = mto.Tracks

' Build tracksToRemove Array
#If Not CSToJava Then
#Else
#End If
Dim tracksToRemove As Array = New Object() {trackCollection(0), trackCollection(1)}

' RemoveTracks expects a one dimensional array of IAgMtoTrack objects
#If Not CSToJava Then
trackCollection.RemoveTracks(tracksToRemove)
#Else
#End If


Remove MTO tracks by ids

[Visual Basic .NET] Copy Code
' IAgMto mto: MTO object

Dim trackCollection As IAgMtoTrackCollection = mto.Tracks

' RemoveTracksById expects a one dimensional array of mto track ids
#If Not CSToJava Then
#Else
#End If
Dim tracks As Array = New Object() {14}
#If Not CSToJava Then
trackCollection.RemoveTracksById(tracks)
#Else
#End If


Compute MTO field of view

[Visual Basic .NET] Copy Code
' IAgMto mto: MTO object

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

' AreTracksInFOV expects a one dimensional array of mto track ids
#If Not CSToJava Then
#Else
#End If
Dim tracks As Array = New Object() {14}

#If Not CSToJava Then
Dim tracksInView As Boolean = fov.AreTracksInFOV(AgEMtoTrackEval.eMtoTrackEvalAny, tracks, "1 Jan 2012 12:00:00.000")
#Else
#End If


Compute MTO ranges

[Visual Basic .NET] Copy Code
' IAgMto mto: MTO object

Dim range As IAgMtoAnalysisRange = 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
#If Not CSToJava Then
#Else
#End If
Dim tracks As Array = New Object() {14}

#If Not CSToJava Then
Dim result As Array = range.ComputeRanges(AgEMtoRangeMode.eMtoRangeModeEach, tracks, "1 Jan 2012 12:00:00.000")
#Else
#End If

' Print results
Dim i As Integer = 0
While i < result.GetLength(0)
     Console.WriteLine("Track #: {0}, Visible: {1}, Range: {2}", result.GetValue(i, 0), result.GetValue(i, 1), result.GetValue(i, 2))
     System.Math.Max(System.Threading.Interlocked.Increment(i),i - 1)
End While


Compute visibility with MTO tracks

[Visual Basic .NET] 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?

Dim mtoVisibility As IAgMtoAnalysisVisibility = 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"
Dim allTracksAreVisible As Boolean = 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?

[Visual Basic .NET] Copy Code
' IAgStkObjectRoot root: STK Object Model root
' IAgMto mto: MTO object to use for visibility analysis

Dim mtoVisibility As IAgMtoAnalysisVisibility = 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"

#If Not CSToJava Then
#Else
#End If
Dim tracksOfInterest As Array = New Object() {127}

' AreTracksVisible expects as the second parameter a one dimensional array of mto track ids
#If Not CSToJava Then
Dim areTracksAreVisible As Boolean = mtoVisibility.AreTracksVisible(AgEMtoTrackEval.eMtoTrackEvalAll, tracksOfInterest, "1 Jan 2012 12:02:00.000")
#Else
#End If


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

[Visual Basic .NET] Copy Code
' IAgStkObjectRoot root: STK Object Model root
' IAgMto mto: MTO object to use for visibility analysis

Dim mtoVisibility As IAgMtoAnalysisVisibility = 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"
Dim anyTrackIsVisible As Boolean = mtoVisibility.IsAnyTrackVisible("1 Jan 2012 14:02:00.000")


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

[Visual Basic .NET] Copy Code
' IAgMto mto: MTO object to use for visibility analysis

Dim mtoVisibility As IAgMtoAnalysisVisibility = 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
Dim trackVisibilityArray As Array = mtoVisibility.ComputeAllTracks(AgEMtoVisibilityMode.eVisibilityModeEach, "1 Jan 2012 12:00:00.000")

' Ouput results
Console.WriteLine("ComputeAllTracks:")
Dim i As Integer = 0
While i < trackVisibilityArray.GetLength(0)
     Console.WriteLine("   Track {0} visibility: {1}", Convert.ToInt32(trackVisibilityArray.GetValue(i, 0)), Convert.ToInt32(trackVisibilityArray.GetValue(i, 1)))
     System.Threading.Interlocked.Increment(i)
End While


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

[Visual Basic .NET] Copy Code
' IAgStkObjectRoot root: STK Object Model root
' IAgMto mto: MTO object to use for visibility analysis

Dim mtoVisibility As IAgMtoAnalysisVisibility = 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).
#If Not CSToJava Then
#Else
#End If
Dim tracksOfInterest As Array = 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
#If Not CSToJava Then
Dim trackVisibilityArray As Array = mtoVisibility.ComputeTracks(AgEMtoVisibilityMode.eVisibilityModeEach, tracksOfInterest, "1 Jan 2012 12:05:00.000")
#Else
#End If

' Output results
Console.WriteLine("ComputeTracks:")
Dim i As Integer = 0
While i < trackVisibilityArray.GetLength(0)
     Console.WriteLine("   Track {0} visibility: {1}", Convert.ToInt32(trackVisibilityArray.GetValue(i, 0)), Convert.ToInt32(trackVisibilityArray.GetValue(i, 1)))
     System.Threading.Interlocked.Increment(i)
End While


Configure MTO graphics

[Visual Basic .NET] Copy Code
' IAgMto mto: Mto object

Dim tracks As IAgMtoVOTrackCollection = mto.VO.Tracks
For Each element As IAgMtoVOTrack 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
     element.Model.ScaleValue = 2
     element.Model.ZPointsNadir = True

     element.Label.Enable = True
     element.Label.X = 33.5
     element.Label.Y = 82.2
     element.Label.Z = 100
     element.Label.OffsetFrame = AgEOffsetFrameType.eOffsetFrameCartesian
Next


Configure MTO track marker

[Visual Basic .NET] Copy Code
' IAgMtoVOTrack track: Mto VO track properties

Dim marker As IAgMtoVOMarker = 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

[Visual Basic .NET] Copy Code
' IAgMtoVOTrack track: Mto VO track properties

Dim model As IAgMtoVOModel = track.Model
model.IsVisible = True
model.Filename = "STKData\VO\Models\Land\ariane-lp.mdl"
model.InitialBearing = 3
model.ScaleValue = 2
model.ZPointsNadir = True


Create a place (on current scenario central body)

[Visual Basic .NET] Copy Code
' IAgStkObjectRoot root: STK Object Model root

' Create a place on current scenario central body
Dim place As IAgPlace = TryCast(root.CurrentScenario.Children.[New](AgESTKObjectType.ePlace, "MyPlace"), IAgPlace)


Create a place from facility database

[Visual Basic .NET] Copy Code
' IAgStkObjectRoot root: STK Object Model root

' Get STK database location using Connect
Dim result As IAgExecCmdResult = root.ExecuteCommand("GetDirectory / Database Facility")
Dim facDataDir As String = result(0)
Dim filelocation As String = Path.Combine(facDataDir, "stkFacility.fd")

' Import object from database using Connect
Dim command As String = "ImportFromDB * Facility """ + filelocation + """ Class Place SiteName Weilheim"
root.ExecuteCommand(command)

Dim place As IAgPlace = TryCast(root.GetObjectFromPath("Place/Weilheim"), IAgPlace)


Create a place on Earth at lat/lon/alt

[Visual Basic .NET] Copy Code
' IAgStkObjectRoot root: STK Object Model root

Dim place As IAgPlace = TryCast(root.CurrentScenario.Children.NewOnCentralBody(AgESTKObjectType.ePlace, "MyPlace""Earth"), 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

[Visual Basic .NET] Copy Code
' IAgStkObjectRoot root: STK Object Model root

Dim placeObject As IAgPlace = TryCast(root.CurrentScenario.Children.NewOnCentralBody(AgESTKObjectType.ePlace, "Place1""Mars"), 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

[Visual Basic .NET] 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

[Visual Basic .NET] Copy Code
' IAgPlanet planet: Planet

planet.PositionSource = AgEPlPositionSourceType.ePosCentralBody

' Get IAgPlPosCentralBody interface
Dim body As IAgPlPosCentralBody = TryCast(planet.PositionSourceData, IAgPlPosCentralBody)

body.AutoRename = False
body.CentralBody = "Jupiter"

' AvailableEphemSourceTypes is a one dimensional array of AgEEphemSourceType values
If Array.IndexOf(body.AvailableEphemSourceTypes, DirectCast(AgEEphemSourceType.eEphemAnalytic, Integer)) <> -1 Then
     body.EphemSource = AgEEphemSourceType.eEphemAnalytic
End If


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

[Visual Basic .NET] 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

[Visual Basic .NET] 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
Dim displayTime As IAgPlOrbitDisplayTime = TryCast(graphics.OrbitDisplayData, IAgPlOrbitDisplayTime)
displayTime.Time = 10000


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

[Visual Basic .NET] Copy Code
' IAgRadar radar: Radar object
' IAgAircraft targetAircraft: Aircraft object
' IAgRFEnvironment scenarioRFEnv: Scenario RF Environment

Dim rdrAsStkObject As IAgStkObject = TryCast(radar, IAgStkObject)
Dim tgtAsStkObject As IAgStkObject = TryCast(targetAircraft, 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")
Dim monostaticModel As IAgRadarModelMonostatic = TryCast(radar.Model, 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")
Dim parabolic As IAgAntennaModelParabolic = TryCast(radar.Model.AntennaControl.EmbeddedModel, IAgAntennaModelParabolic)

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

'Put the monostatic radar model in Search/Track mode
monostaticModel.SetMode("Search Track")
Dim searchTrackMode As IAgRadarModeMonostaticSearchTrack = TryCast(monostaticModel.Mode, IAgRadarModeMonostaticSearchTrack)

'Set the waveform type to fixed prf
searchTrackMode.SetWaveformType(AgERadarWaveformSearchTrackType.eRadarWaveformSearchTrackTypeFixedPRF)
Dim fixedPrf As IAgRadarWaveformMonostaticSearchTrackFixedPRF = TryCast(searchTrackMode.Waveform, IAgRadarWaveformMonostaticSearchTrackFixedPRF)
fixedPrf.PulseDefinition.Prf = 0.002
'2 kHz
'Set the pulse width to 1e-8 sec
fixedPrf.PulseDefinition.PulseWidth = 1E-08
'sec
'Set the number of pulses
fixedPrf.PulseDefinition.NumberOfPulses = 25

'Set the pulse integration strategy to goal SNR
fixedPrf.PulseIntegrationType = AgERadarPulseIntegrationType.eRadarPulseIntegrationTypeGoalSNR
Dim pulseIntGoalSNR As IAgRadarPulseIntegrationGoalSNR = TryCast(fixedPrf.PulseIntegration, IAgRadarPulseIntegrationGoalSNR)
pulseIntGoalSNR.SNR = 40
'dB
'Set the transmit frequency
monostaticModel.Transmitter.FrequencySpecification = AgERadarFrequencySpec.eRadarFrequencySpecFrequency
monostaticModel.Transmitter.Frequency = 2.1
'GHz
'Set the transmit power
monostaticModel.Transmitter.Power = 50
'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
Dim rcs As IAgRadarCrossSectionModel = TryCast(targetAircraft.RadarCrossSection.Model, IAgRadarCrossSectionModel)

'Set the radar cross section compute strategy to constan value
rcs.FrequencyBands(0).SetComputeStrategy("Constant Value")
Dim constValRcs As IAgRadarCrossSectionComputeStrategyConstantValue = TryCast(rcs.FrequencyBands(0).ComputeStrategy, 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
Dim radarAccess As IAgStkAccess = rdrAsStkObject.GetAccessToObject(tgtAsStkObject)

'Compute access
radarAccess.ComputeAccess()

' Get the access intervals
Dim accessIntervals As IAgIntervalCollection = radarAccess.ComputedAccessIntervalTimes

#If Not CSToJava Then
' Extract the access intervals and the range information for each access interval
Dim dataPrvElements As Array = New Object() {"Time""S/T SNR1""S/T PDet1""S/T Integrated SNR""S/T Integrated PDet"}
#Else
#End If

Dim dp As IAgDataPrvTimeVar = TryCast(radarAccess.DataProviders("Radar SearchTrack"), IAgDataPrvTimeVar)

Dim index0 As Integer = 0
While index0 < accessIntervals.Count
     Dim startTime As Object = Nothing, stopTime As Object = Nothing
     #If Not CSToJava Then
     accessIntervals.GetInterval(index0, startTime, stopTime)
     #Else
     #End If

     #If Not CSToJava Then
     Dim result As IAgDrResult = dp.ExecElements(startTime, stopTime, 60, dataPrvElements)
     #Else
     #End If

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

     Dim index1 As Integer = 0
     While index1 < timeValues.GetLength(0)
          Dim time As String = DirectCast(timeValues.GetValue(index1), String)
          Dim snr1Val As Double = DirectCast(snr1.GetValue(index1), Double)
          Dim pdet1Val As Double = DirectCast(pdet1.GetValue(index1), Double)
          Dim integSnrVal As Double = DirectCast(integSnr.GetValue(index1), Double)
          Dim integPdetVal As Double = DirectCast(integPdet.GetValue(index1), Double)
          Console.WriteLine("{0}: SNR1={1} PDet1={2} Integrated SNR={3} Integrated PDet={4}", time, snr1Val, pdet1Val, integSnrVal, integPdetVal)
          System.Threading.Interlocked.Increment(index1)
     End While

     Console.WriteLine()
     System.Threading.Interlocked.Increment(index0)
End While


Add analytical terrain to the scenario on Earth central body

[Visual Basic .NET] Copy Code
' IAgStkObjectRoot root: STK Object Model root
' String terrainFile: Path of Terrain data file

' Retrieve the IAgScenario interface
Dim scenario As IAgScenario = TryCast(root.CurrentScenario, IAgScenario)

Dim terrainCollection As IAgCentralBodyTerrainCollection = scenario.Terrain
Dim elementCollection As IAgTerrainCollection = terrainCollection("Earth").TerrainCollection

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

' Set Scenario to use terrain data file
terrain.UseTerrain = True


Configure scenario animation

[Visual Basic .NET] Copy Code
' IAgScenario scenario: Scenario

Dim animation As IAgScAnimation = 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

[Visual Basic .NET] Copy Code
' IAgScenario scenario: Scenario

Dim fonts As IAgSc3dFont = scenario.VO.LargeFont

fonts.Bold = True
fonts.Italic = True
fonts.PtSize = AgESc3dPtSize.eSc3dFontSize36

If fonts.IsFontAvailable("Impact"Then
     fonts.Name = "Impact"
End If

' AvailableFonts returns a one dimensional array of font strings
Dim allFonts As Array = fonts.AvailableFonts
Dim index As Integer = Array.IndexOf(allFonts, "Courier")
If index <> -1 Then
     fonts.Name = TryCast(allFonts.GetValue(index), String)
End If


Add a new STK Object to the scenario

[Visual Basic .NET] Copy Code
' IAgStkObjectRoot root: STK Object Model root

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


Import an existing STK Object file into the scenario

[Visual Basic .NET] 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

[Visual Basic .NET] Copy Code
' IAgStkObjectRoot root: STK Object Model root
' AgESTKObjectType type: Object type in scenario that we want to list

Dim allChildrenOfType As IAgStkObjectElementCollection = root.CurrentScenario.Children.GetElements(type)

For Each o As IAgStkObject In allChildrenOfType
     Console.WriteLine(o.InstanceName)
Next


Close a scenario

[Visual Basic .NET] Copy Code
' IAgStkObjectRoot root: STK Object Model root

root.CloseScenario()


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

[Visual Basic .NET] Copy Code
' IAgStkObjectRoot root: STK Object Model root

' Close current scenario
If root.CurrentScenario IsNot Nothing Then
     root.CloseScenario()
End If
root.NewScenario("Scenario1")

' Get IAgScenario interface
Dim scenario As IAgScenario = TryCast(root.CurrentScenario, 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)

[Visual Basic .NET] Copy Code
' IAgStkObjectRoot root: STK Object Model root
' String scenarioLocation: Specified path of scenario

' close current scenario
If root.CurrentScenario IsNot Nothing Then
     root.CloseScenario()
End If
root.LoadScenario(scenarioLocation)


Save a scenario

[Visual Basic .NET] Copy Code
' IAgStkObjectRoot root: STK Object Model root

root.SaveScenario()


Save a scenario to a new location (Save as)

[Visual Basic .NET] Copy Code
' IAgStkObjectRoot root: STK Object Model root
' String fileName: Specified path and file name of scenario

root.SaveScenarioAs(fileName)


Define a complex sensor

[Visual Basic .NET] Copy Code
' IAgSensor sensor: Sensor object

Dim patterndata As IAgSnComplexConicPattern = sensor.CommonTasks.SetPatternComplexConic(107020220)
patterndata.AngularResolution = 0.5


Define a custom sensor

[Visual Basic .NET] Copy Code
' IAgSensor sensor: Sensor object
' String sensorPatternPath: Path of Custom Sensor data file

' Set pattern type to Custom
Dim customPattern As IAgSnCustomPattern = sensor.CommonTasks.SetPatternCustom(sensorPatternPath)
customPattern.AngularResolution = 6
customPattern.UseNativeResolution = False


Define a half power sensor

[Visual Basic .NET] Copy Code
' IAgSensor sensor: Sensor object

' Configure pattern
Dim pattern As IAgSnHalfPowerPattern = sensor.CommonTasks.SetPatternHalfPower(12.53.46)


Define a SAR sensor

[Visual Basic .NET] Copy Code
' IAgSensor sensor: Sensor object

' Configure pattern
Dim patterndata As IAgSnSARPattern = sensor.CommonTasks.SetPatternSAR(10604030700)


Define a simple conic sensor

[Visual Basic .NET] Copy Code
' IAgSensor sensor: Sensor object

Dim patternData As IAgSnSimpleConicPattern = sensor.CommonTasks.SetPatternSimpleConic(400.1)


Define and compute sensor swath

[Visual Basic .NET] Copy Code
' IAgSensor sensor: Sensor object

' Configure swath display properties
Dim swath As IAgSwath = 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
swath.ScatteringTolerance = 70
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

[Visual Basic .NET] Copy Code
' IAgSensor sensor: Sensor object
' String externalSensorPointingPath: Path of sensor external file

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

Dim external As IAgSnPtExternal = TryCast(sensor.Pointing, IAgSnPtExternal)


Define fixed location

[Visual Basic .NET] Copy Code
' IAgSensor sensor: Sensor object

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

' Configure sensor location
Dim pos As IAgPosition = TryCast(sensor.LocationData, IAgPosition)
pos.AssignCartesian(595.2, -110.124.6)


Define fixed sensor pointing

[Visual Basic .NET] Copy Code
' IAgSensor sensor: Sensor object

Dim fixedSensor As IAgSnPtFixed = sensor.CommonTasks.SetPointingFixedAzEl(4.5, -45, AgEAzElAboutBoresight.eAzElAboutBoresightRotate)


Define location from Vector Geometry Tool point

[Visual Basic .NET] Copy Code
' IAgSensor sensor: Sensor object

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

' Get IAgLocationCrdnPoint interface
Dim vgtPoint As IAgLocationCrdnPoint = TryCast(sensor.LocationData, IAgLocationCrdnPoint)

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


Define location on 3D model

[Visual Basic .NET] 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")
Dim model As IAgSnPt3DModel = sensor.CommonTasks.SetPointing3DModel("Solar_PanelsNode")


Define sensor to use azimuth elevation mask file

[Visual Basic .NET] 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
Dim maskFile As IAgSnAzElMaskFile = TryCast(sensor.AzElMaskData, IAgSnAzElMaskFile)

' Configure MaskFile as needed
maskFile.BoresightAxis = AgESnAzElBsightAxisType.ePlus_MinusZ


Define spinning sensor pointing

[Visual Basic .NET] Copy Code
' IAgStkObjectRoot root: STK Object Model root
' IAgSensor sensor: Sensor object

' Set pattern type to Spinning
sensor.SetPointingType(AgESnPointing.eSnPtSpinning)
Dim spinning As IAgSnPtSpinning = TryCast(sensor.Pointing, 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)

[Visual Basic .NET] Copy Code
' IAgSensor sensor: Sensor object

' Configure sensor (using common taks)
sensor.CommonTasks.SetPointingSpinning(14.247.6842.46, AgESnScanMode.eSnContinuous, 88.921110.44_
     1.23.5)


Define targeted sensor pointing

[Visual Basic .NET] Copy Code
' IAgSensor sensor: Sensor object

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


Configure sensor 3D projection

[Visual Basic .NET] Copy Code
' IAgSnVO sensorVo: Sensor VO object

sensorVo.ProjectionType = AgESnVOProjectionType.eProjectionAllIntersections
sensorVo.InheritFrom2D = AgESnVOInheritFrom2D.eSnVOInheritFrom2DExtentOnly
sensorVo.SpaceProjection = 2000


Configure basic properties

[Visual Basic .NET] Copy Code
' IAgStar star: Star object

' Units depend on current unit preferences
star.LocationDeclination = -40
star.LocationRightAscension = 120
' in arcSec
star.Magnitude = -1
star.Parallax = 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)

[Visual Basic .NET] Copy Code
' IAgStkObjectRoot root: STK Object Model root

' Create the Star
Dim star As IAgStar = TryCast(root.CurrentScenario.Children.[New](AgESTKObjectType.eStar, "MyStar"), IAgStar)


Create a star from a star database

[Visual Basic .NET] Copy Code
' IAgStkObjectRoot root: STK Object Model root

' Import object from database using Connect
Dim command As String = "ImportFromDB * Star ScenarioCollection VisualMagnitude 0 1.0 RightAsc 200.0 230.0 Constellation ImportedFromStarDB"
root.ExecuteCommand(command)

Dim star As IAgStar = TryCast(root.GetObjectFromPath("Star/Star-65474"), IAgStar)


Change a target position

[Visual Basic .NET] Copy Code
' IAgTarget target: Target

Dim pos As IAgPosition = target.Position
pos.AssignGeodetic(39.9515.58231.54)


Configure a target from azimuth mask file

[Visual Basic .NET] Copy Code
' IAgTarget target: Target
' String maskfile: Path of maskfile

target.UseLocalTimeOffset = True
target.LocalTimeOffset = 200
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


Create a target (on the current scenario central body)

[Visual Basic .NET] 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)
Dim areaTarget As IAgTarget = TryCast(root.CurrentScenario.Children.[New](AgESTKObjectType.eAreaTarget, "MyAreaTarget"), IAgTarget)


Configure an aircraft route using the Great Arc propagator

[Visual Basic .NET] Copy Code
' IAgAircraft aircraft: Aircraft object

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

' Retrieve propagator interface
Dim propagator As IAgVePropagatorGreatArc = TryCast(aircraft.Route, IAgVePropagatorGreatArc)
propagator.ArcGranularity = 51.333

' Set Ref type to WayPtAltRefTerrain and retreive IAgVeWayPtAltitudeRefTerrain interface
propagator.SetAltitudeRefType(AgEVeAltitudeRef.eWayPtAltRefTerrain)
Dim altRef As IAgVeWayPtAltitudeRefTerrain = TryCast(propagator.AltitudeRef, IAgVeWayPtAltitudeRefTerrain)
altRef.Granularity = 51.33
altRef.InterpMethod = AgEVeWayPtInterpMethod.eWayPtEllipsoidHeight

propagator.Method = AgEVeWayPtCompMethod.eDetermineTimeAccFromVel

' Add waypoints
Dim point1 As IAgVeWaypointsElement = propagator.Waypoints.Add()
point1.Latitude = 39.7674
point1.Longitude = -79.7292
point1.Altitude = 3
point1.Speed = 0.0772

Dim point2 As IAgVeWaypointsElement = propagator.Waypoints.Add()
point2.Latitude = 38.3721
point2.Longitude = -120.116
point2.Altitude = 3
point2.Speed = 0.0772

' Add more way points if necessary...

' Propagate
propagator.Propagate()


Set an aircraft to use Great Arc propagator

[Visual Basic .NET] Copy Code
' IAgAircraft aircraft: Aircraft object

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

' Retrieve propagator interface
Dim propagator As IAgVePropagatorGreatArc = TryCast(aircraft.Route, IAgVePropagatorGreatArc)


Add ground ellipse element and data element

[Visual Basic .NET] Copy Code
' IAgVeGroundEllipsesCollection ellipsesCollection: Ellipses collection

' Add ground ellipse
Dim ellipse As IAgVeGroundEllipseElement = ellipsesCollection.Add("MyEllipses")

' Add ellipse data element
Dim element As IAgVeEllipseDataElement = ellipse.EllipseData.Add()

' Configure element properties
element.Time = "1 Jan 2012 12:00:00.000"
element.Latitude = 35.292
element.Longitude = -93.7299
element.SemiMajorAxis = 400
element.SemiMinorAxis = 300
element.Bearing = 35.71


Export a vehicle attitude to an external file

[Visual Basic .NET] Copy Code
' IAgScenario scenario: Current Scenario Object.
' IAgVeAttitudeExportTool attitudeExport: Attitude Export Tool

' Set and configure attitude coordinate axes
attitudeExport.SetCoordinateAxesType(AgEAttCoordinateAxes.eAttCoordinateAxesCustom)
Dim customAxes As IAgVeCoordinateAxesCustom = TryCast(attitudeExport.CoordinateAxes, 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

[Visual Basic .NET] 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

[Visual Basic .NET] Copy Code
' IAgSatellite satellite: Satellite object

' Set Attitude to Standard
satellite.SetAttitudeType(AgEVeAttitude.eAttitudeStandard)
' Get IAgVeOrbitAttitudeStandard interface
Dim standard As IAgVeOrbitAttitudeStandard = TryCast(satellite.Attitude, IAgVeOrbitAttitudeStandard)

' Set Profile to Inertially Fixed
standard.Basic.SetProfileType(AgEVeProfile.eProfileInertiallyFixed)
' Get IAgVeProfileInertial interface
Dim interfix As IAgVeProfileInertial = TryCast(standard.Basic.Profile, IAgVeProfileInertial)

interfix.Inertial.AssignEulerAngles(AgEEulerOrientationSequence.e123, 20.15020)


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

[Visual Basic .NET] Copy Code
' IAgSatellite satellite: Satellite object

satellite.SetAttitudeType(AgEVeAttitude.eAttitudeStandard)
Dim standard As IAgVeOrbitAttitudeStandard = TryCast(satellite.Attitude, IAgVeOrbitAttitudeStandard)
standard.Basic.SetProfileType(AgEVeProfile.eProfileInertiallyFixed)
Dim interfix As IAgVeProfileInertial = TryCast(standard.Basic.Profile, 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

[Visual Basic .NET] Copy Code
' IAgStkObjectRoot root: STK Object Model root
' IAgSatellite satellite: Satellite object
' Array cpfQuaternion: Array that contains CPF Quaternion data

satellite.SetAttitudeType(AgEVeAttitude.eAttitudeRealTime)
Dim realtime As IAgVeAttitudeRealTime = TryCast(satellite.Attitude, IAgVeAttitudeRealTime)

Dim i As Integer = 0
While i < cpfQuaternion.GetUpperBound(0)
     realtime.AddCBFQuaternion(cpfQuaternion.GetValue(i, 0), DirectCast(cpfQuaternion.GetValue(i, 1), Double), DirectCast(cpfQuaternion.GetValue(i, 2), Double), DirectCast(cpfQuaternion.GetValue(i, 3), Double), DirectCast(cpfQuaternion.GetValue(i, 4), Double))
     System.Math.Max(System.Threading.Interlocked.Increment(i),i - 1)
End While


Configure real-time attitude

[Visual Basic .NET] Copy Code
' IAgSatellite satellite: Satellite object

' set attitude type to real time
satellite.SetAttitudeType(AgEVeAttitude.eAttitudeRealTime)
Dim realtime As IAgVeAttitudeRealTime = TryCast(satellite.Attitude, IAgVeAttitudeRealTime)

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

' Duration
Dim duration As IAgVeDuration = realtime.Duration
duration.LookAhead = 1600
duration.LookBehind = 1600

' BlockFactor
realtime.BlockFactor = 40
realtime.DataReference.SetProfileType(AgEVeProfile.eProfileInertiallyFixed)


Set attitude profile type (if profile is supported)

[Visual Basic .NET] Copy Code
' IAgSatellite satellite: Satellite object

Dim standard As IAgVeOrbitAttitudeStandard = TryCast(satellite.Attitude, IAgVeOrbitAttitudeStandard)
If standard.Basic.IsProfileTypeSupported(AgEVeProfile.eProfileSpinning) Then
     standard.Basic.SetProfileType(AgEVeProfile.eProfileSpinning)
End If


Configure access intervals graphics

[Visual Basic .NET] 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

[Visual Basic .NET] 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

[Visual Basic .NET] Copy Code
' IAgVeGfxAttributesCustom customAttributes: Custom Attributes graphics

Dim customIntervals As IAgVeGfxIntervalsCollection = 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

[Visual Basic .NET] 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
Dim elevation As IAgVeGfxElevationsElement = gfxContours.Elevations.AddLevel(25)

' 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


Configure sunlight lighting graphics

[Visual Basic .NET] Copy Code
' IAgVeGfxLighting lighting: Vehicle graphics lighting

Dim sunlight As IAgVeGfxLightingElement = 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

[Visual Basic .NET] Copy Code
' IAgGreatArcGraphics graphics: Great Arc graphics

If graphics.IsAttributesTypeSupported(AgEVeGfxAttributes.eAttributesAccess) Then
     ' Set graphics to access intervals
     graphics.SetAttributesType(AgEVeGfxAttributes.eAttributesAccess)

     ' Get IAgVeGfxAttributesAccess interface

          ' adjust the access intervals graphics
     Dim accessAttributes As IAgVeGfxAttributesAccess = TryCast(graphics.Attributes, IAgVeGfxAttributesAccess)
End If


Set a vehicle's graphics to basic

[Visual Basic .NET] Copy Code
' IAgGreatArcGraphics graphics: Great Arc graphics

If graphics.IsAttributesTypeSupported(AgEVeGfxAttributes.eAttributesBasic) Then
     ' Set graphics to basic
     graphics.SetAttributesType(AgEVeGfxAttributes.eAttributesBasic)

     ' Get IAgVeGfxAttributesBasic interface

          ' adjust the basic graphics
     Dim basicAttributes As IAgVeGfxAttributesBasic = TryCast(graphics.Attributes, IAgVeGfxAttributesBasic)
End If


Set a vehicle's graphics to custom intervals

[Visual Basic .NET] Copy Code
' IAgGreatArcGraphics graphics: Great Arc graphics

If graphics.IsAttributesTypeSupported(AgEVeGfxAttributes.eAttributesCustom) Then
     ' Set graphics to custom
     graphics.SetAttributesType(AgEVeGfxAttributes.eAttributesCustom)

     ' Get IAgVeGfxAttributesCustom interface

          ' adjust the custom intervals graphics
     Dim customAttributes As IAgVeGfxAttributesCustom = TryCast(graphics.Attributes, IAgVeGfxAttributesCustom)
End If


Configure 3D dropline graphics

[Visual Basic .NET] 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
' in sec


Configure 3D pass graphics

[Visual Basic .NET] 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

[Visual Basic .NET] Copy Code
' IAgVAMCSTargetSequence sequence: Target sequence object

Dim deoStr As String = "Design Explorer Optimizer"

' Retrieve sequence profile
If Array.IndexOf(sequence.Profiles.AvailableProfiles, deoStr) <> -1 Then
     ' Add a propagate segment on the Target Sequence in order to provide a control
     Dim propagate As IAgVAMCSPropagate = TryCast(sequence.Segments.Insert(AgEVASegmentType.eVASegmentTypePropagate, "MyPropagate""-"), IAgVAMCSPropagate)

     ' Enable the propagate "StoppingConditions.Duration.TripValue" control
     Dim durationControl As IAgVAStoppingConditionElement = propagate.StoppingConditions("Duration")
     durationControl.EnableControlParameter(AgEVAControlStoppingCondition.eVAControlStoppingConditionTripValue)

     Dim deo As IAgVAProfileDEOptimizer = TryCast(sequence.Profiles.Add(deoStr), IAgVAProfileDEOptimizer)

     ' Retrieve result reference
     Dim controls As IAgVADEControlCollection = deo.ControlParameters
     Dim prop1Duration As IAgVADEControl = 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 = 5.5E-05
End If


Configure initial state segment

[Visual Basic .NET] Copy Code
' IAgVADriverMCS driver: Astrogrator driver object

' Add a new segment and cast the segment to the IAgVAMCSInitialState interface
Dim segment As IAgVAMCSSegment = driver.MainSequence.Insert(AgEVASegmentType.eVASegmentTypeInitialState, "Inner Orbit""-")
Dim initState As IAgVAMCSInitialState = TryCast(segment, 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)
Dim cartesian As IAgVAElementCartesian = TryCast(initState.Element, 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 = 2
initState.SpacecraftParameters.K2 = 3
initState.SpacecraftParameters.RadiationPressureArea = 23
initState.SpacecraftParameters.SolarRadiationPressureArea = 22


Configure launch segment

[Visual Basic .NET] Copy Code
' IAgVADriverMCS driver: Astrogrator driver object

' Add launch sequence and retrieve the
Dim segment As IAgVAMCSSegment = driver.MainSequence.Insert(AgEVASegmentType.eVASegmentTypeLaunch, "MyLaunch""-")
Dim launch As IAgVAMCSLaunch = TryCast(segment, 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)
Dim llr As IAgVADisplaySystemGeocentric = DirectCast(launch.DisplaySystem, IAgVADisplaySystemGeocentric)
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
Dim velocity As IAgVABurnoutVelocity = launch.BurnoutVelocity
velocity.BurnoutOption = AgEVABurnoutOptions.eVABurnoutOptionsInertialVelocity
velocity.InertialVelocity = 20
velocity.InertialHorizontalFPA = 22
velocity.InertialVelocityAzimuth = 55
velocity.BurnoutOption = AgEVABurnoutOptions.eVABurnoutOptionsFixedVelocity
velocity.FixedVelocity = 20


Configure maneuver segment

[Visual Basic .NET] Copy Code
' IAgVADriverMCS driver: Astrogrator driver object

' Add launch sequence and retrieve the IAgVAMCSManeuver interface
Dim segment As IAgVAMCSSegment = driver.MainSequence.Insert(AgEVASegmentType.eVASegmentTypeManeuver, "MyManeuver""-")
Dim maneuver As IAgVAMCSManeuver = TryCast(segment, IAgVAMCSManeuver)

' Set Maneuver to Impulsive
maneuver.SetManeuverType(AgEVAManeuverType.eVAManeuverTypeImpulsive)
Dim impulse As IAgVAManeuverImpulsive = TryCast(maneuver.Maneuver, IAgVAManeuverImpulsive)

' Set Impulsive attitude to VelocityVector
impulse.SetAttitudeControlType(AgEVAAttitudeControl.eVAAttitudeControlVelocityVector)
Dim velVec As IAgVAAttitudeControlImpulsiveVelocityVector = TryCast(impulse.AttitudeControl, IAgVAAttitudeControlImpulsiveVelocityVector)
velVec.DeltaVMagnitude = 1

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


Configure propagate segment

[Visual Basic .NET] Copy Code
' IAgVADriverMCS driver: Astrogrator driver object

' Add a propagate segment to our sequence
Dim segment As IAgVAMCSSegment = driver.MainSequence.Insert(AgEVASegmentType.eVASegmentTypePropagate, "Propagate""-")
Dim propagate As IAgVAMCSPropagate = TryCast(segment, 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
Dim duration As IAgVAStoppingCondition = TryCast(propagate.StoppingConditions("Duration").Properties, IAgVAStoppingCondition)
duration.Trip = 7200
duration.Tolerance = 1E-05

' Add any addition stopping conditions
Dim lightning As IAgVAStoppingCondition = TryCast(propagate.StoppingConditions.Add("Lighting"), IAgVAStoppingCondition)


Configure result from a maneuver segment with Design Explorer Optimizer

[Visual Basic .NET] Copy Code
' IAgVAMCSTargetSequence sequence: Target sequence object

' Add a maneuver segment on the Target Sequence in order to provide access result
Dim maneuver As IAgVAMCSManeuver = TryCast(sequence.Segments.Insert(AgEVASegmentType.eVASegmentTypeManeuver, "MyManeuver""-"), IAgVAMCSManeuver)

' Add results the Access result to the manuever
DirectCast(maneuver, IAgVAMCSSegment).Results.Add("Access/Access")

Dim deoStr As String = "Design Explorer Optimizer"

' Retrieve sequence profile
If Array.IndexOf(sequence.Profiles.AvailableProfiles, deoStr) <> -1 Then
     Dim deo As IAgVAProfileDEOptimizer = TryCast(sequence.Profiles.Add(deoStr), IAgVAProfileDEOptimizer)

     ' Retrieve result reference
     Dim altitudeResult As IAgVADEResult = deo.Results.GetResultByPaths("MyManeuver""Access")

     ' Configure VADEResult properties

     altitudeResult.Enable = True
     altitudeResult.Goal = AgEVADEGoal.eVADEGoalMaximize
     altitudeResult.Weight = 2
     altitudeResult.ScalingMethod = AgEVADEScalingMethod.eVADEScalingMethodInitialValue
End If


Configure sequence segment with scripting tool

[Visual Basic .NET] Copy Code
' IAgVADriverMCS driver: Astrogrator driver object

' Add launch sequence and retrieve the
Dim segment As IAgVAMCSSegment = driver.MainSequence.Insert(AgEVASegmentType.eVASegmentTypeSequence, "MySequence""-")
Dim sequence As IAgVAMCSSequence = TryCast(segment, IAgVAMCSSequence)

Dim scriptTool As IAgVAScriptingTool = sequence.ScriptingTool
scriptTool.Enable = True
scriptTool.LanguageType = AgEVALanguage.eVALanguageVBScript
scriptTool.ScriptText(vbCr & vbLf & "            DeltaArg = dArg" & vbCr & vbLf & vbCr & vbLf & "            REM  Set the optimizers desired results" & vbCr & vbLf & "            DEOdArgUB = DeltaArg" & vbCr & vbLf & "            DEOdArgLB = DeltaArg" & vbCr & vbLf & vbCr & vbLf & vbCr & vbLf & "            REM  Initial guess tool:" & vbCr & vbLf & "            REM  Assume transfer orbit is something like a circular orbit linking apoapse of initial orbit to apoapse of final orbit" & vbCr & vbLf & "            REM  Constants: " & vbCr & vbLf & "            mu = 398600" & vbCr & vbLf & "            pi = 3.14159265358979" & vbCr & vbLf & vbCr & vbLf & "            REM  Step 1:  propagate to apoapsis" & vbCr & vbLf & "            Prop1Dur = Period_0/2" & vbCr & vbLf & vbCr & vbLf & "            REM  Step 2:  conditions at end of initial orbit:" & vbCr & vbLf & "            SMA_0 = 0.5*(RadApo_0 + RadPeri_0)" & vbCr & vbLf & "            VelApo_0 = sqr( (RadPeri_0*mu) / (RadApo_0*SMA_0) )" & vbCr & vbLf & vbCr & vbLf & "            REM  Step 3:  evaluate properties of the circular transfer orbit" & vbCr & vbLf & "            Rcirc = RadApo_0" & vbCr & vbLf & "            Vcirc = sqr(mu/Rcirc)" & vbCr & vbLf & "            PeriodCirc = 2*pi*Sqr( Rcirc*Rcirc*Rcirc / mu)" & vbCr & vbLf & vbCr & vbLf & "            REM  Step 4:  set first maneuver to enter transfer orbit" & vbCr & vbLf & "            Burn1X = Vcirc - VelApo_0" & vbCr & vbLf & "            Burn1Z = 0" & vbCr & vbLf & vbCr & vbLf & "            REM  Step 5:  propagate along transfer orbit the desired change in argument of periapse" & vbCr & vbLf & "            If DeltaArg >= 0 Then" & vbCr & vbLf & "             TransferDur = PeriodCirc*(DeltaArg/360)" & vbCr & vbLf & "            Else " & vbCr & vbLf & "             TransferDur = PeriodCirc*(360+DeltaArg)/360" & vbCr & vbLf & "            End If" & vbCr & vbLf & vbCr & vbLf & "            REM Step 6:  set second maneuver to enter desired final orbit" & vbCr & vbLf & "            Burn2X = -Burn1X" & vbCr & vbLf & "            Burn2Z = 0" & vbCr & vbLf & "            ")

' Configure the script tool's segments

Dim burn1X As IAgVAScriptingSegment = scriptTool.SegmentProperties.Add("Burn1X")

If Array.IndexOf(burn1X.AvailableObjectNames, "Optimize_Delta_w.Burn1") <> -1 Then
     burn1X.ObjectName = "Optimize_Delta_w.Burn1"
     burn1X.Attribute = "ImpulsiveMnvr.Cartesian.X"
     burn1X.Unit = "km/sec"
End If

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


Configure target sequence segment

[Visual Basic .NET] Copy Code
' IAgVADriverMCS driver: Astrogrator driver object

' First add a sequence target
Dim segment As IAgVAMCSSegment = driver.MainSequence.Insert(AgEVASegmentType.eVASegmentTypeTargetSequence, "Start Transfer""-")
Dim targetSequence As IAgVAMCSTargetSequence = TryCast(segment, IAgVAMCSTargetSequence)

targetSequence.Action = AgEVATargetSeqAction.eVATargetSeqActionRunActiveProfiles
targetSequence.WhenProfilesFinish = AgEVAProfilesFinish.eVAProfilesFinishRunToReturnAndContinue
targetSequence.ContinueOnFailure = False

' Add as many child segments to target
Dim dv1 As IAgVAMCSManeuver = TryCast(targetSequence.Segments.Insert(AgEVASegmentType.eVASegmentTypeManeuver, "DV1""-"), IAgVAMCSManeuver)
Dim dv2 As IAgVAMCSManeuver = TryCast(targetSequence.Segments.Insert(AgEVASegmentType.eVASegmentTypeManeuver, "DV2""-"), IAgVAMCSManeuver)

' Add more profiles if necessary
Dim profileName As String = "Change Maneuver Type"
If Array.IndexOf(targetSequence.Profiles.AvailableProfiles, profileName) <> -1 Then
     Dim newProfile As IAgVAProfile = targetSequence.Profiles.Add(profileName)
End If

' Enable controls
dv1.EnableControlParameter(AgEVAControlManeuver.eVAControlManeuverImpulsiveCartesianX)
Dim dc As IAgVAProfileDifferentialCorrector = TryCast(targetSequence.Profiles("Differential Corrector"), IAgVAProfileDifferentialCorrector)
Dim controlParam As IAgVADCControl = dc.ControlParameters.GetControlByPaths("DV1""ImpulsiveMnvr.Cartesian.X")
controlParam.Enable = True
controlParam.MaxStep = 0.3

' Enable results
DirectCast(dv1, IAgVAMCSSegment).Results.Add("Epoch")
Dim roaResult As IAgVADCResult = 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

[Visual Basic .NET] Copy Code
' IAgVADriverMCS driver: Astrogrator driver object

Dim startTransfer As IAgVAMCSTargetSequence = TryCast(driver.MainSequence("Start Transfer"), IAgVAMCSTargetSequence)

Dim dcString As String = "Differential Corrector"

If Array.IndexOf(startTransfer.Profiles.AvailableProfiles, dcString) <> -1 Then
     Dim dc As IAgVAProfileDifferentialCorrector = TryCast(startTransfer.Profiles.Add(dcString), 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
     dc.MaxLineSearchIterations = 5
     dc.MaxIterations = 20

     ' Apply
     startTransfer.ApplyProfiles()
End If


Configure the Astrogrator propagator

[Visual Basic .NET] Copy Code
' IAgSatellite satellite: Satellite object

satellite.SetPropagatorType(AgEVePropagatorType.ePropagatorAstrogator)

Dim driver As IAgVADriverMCS = TryCast(satellite.Propagator, IAgVADriverMCS)

' Remove if necessary
driver.MainSequence.RemoveAll()

' Configure properties as necessarily
driver.Options.DrawTrajectoryIn3D = True
driver.Options.GraphicsUpdateRate = 0.9
driver.Options.UpdateAnimationTimeForAllObjects = False
driver.Options.StoppingConditionTimeTolerance = 5E-08
driver.Options.EnableLogging = True


Configure update segment

[Visual Basic .NET] Copy Code
' IAgVADriverMCS driver: Astrogrator driver object

' Add launch sequence and retrieve the
Dim segment As IAgVAMCSSegment = driver.MainSequence.Insert(AgEVASegmentType.eVASegmentTypeUpdate, "MyUpdate""-")
Dim update As IAgVAMCSUpdate = TryCast(segment, 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

[Visual Basic .NET] Copy Code
' IAgVePropagatorBallistic propagator: Ballistic propagator

propagator.[Step] = 30
propagator.SetLaunchType(AgEVeLaunch.eLaunchLLA)

Dim launch As IAgVeLaunchLLA = TryCast(propagator.Launch, IAgVeLaunchLLA)
launch.Lat = 30.338
launch.Lon = 33.468
launch.Alt = 1.5

propagator.SetImpactLocationType(AgEVeImpactLocation.eImpactLocationPoint)

Dim impactLocation As IAgVeImpactLocationPoint = TryCast(propagator.ImpactLocation, IAgVeImpactLocationPoint)
impactLocation.SetImpactType(AgEVeImpact.eImpactLLA)
impactLocation.SetLaunchControlType(AgEVeLaunchControl.eLaunchControlFixedDeltaV)

Dim impact As IAgVeImpactLLA = TryCast(impactLocation.Impact, IAgVeImpactLLA)
impact.Lat = 25.474
impact.Lon = 68.306
impact.Alt = 0

Dim fixedDeltaV As IAgVeLaunchControlFixedDeltaV = TryCast(impactLocation.LaunchControl, IAgVeLaunchControlFixedDeltaV)
fixedDeltaV.DeltaV = 7.545

propagator.Propagate()


Configure the GPS propagator with an almanac

[Visual Basic .NET] 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(DirectCast(propagator.AvailablePRNs.GetValue(0), String))

' Turn the Auto-update off
propagator.AutoUpdateEnabled = False

' Specify a catalog
propagator.SpecifyCatalog.Filename = almanacPath

' Configure the properties specific to the chosen almanac
Select Case propagator.SpecifyCatalog.Properties.Type
     Case AgEVeGPSAlmanacType.eGPSAlmanacTypeSEM
          If True Then
               ' configure the SEM almanac

               Dim sem As IAgVeGPSAlmanacPropertiesSEM = TryCast(propagator.SpecifyCatalog.Properties, IAgVeGPSAlmanacPropertiesSEM)
               sem.ReferenceWeek = AgEGPSReferenceWeek.eGPSReferenceWeek22Aug1999
               Exit Select
          End If
     Case AgEVeGPSAlmanacType.eGPSAlmanacTypeSP3
          If True Then
               ' SP3 almanac contains no configurable properties

               Dim sp3 As IAgVeGPSAlmanacPropertiesSP3 = TryCast(propagator.SpecifyCatalog.Properties, IAgVeGPSAlmanacPropertiesSP3)
               Exit Select
          End If
     Case AgEVeGPSAlmanacType.eGPSAlmanacTypeYUMA
          If True Then
               ' configure the YUMA almanac

               Dim yuma As IAgVeGPSAlmanacPropertiesYUMA = TryCast(propagator.SpecifyCatalog.Properties, IAgVeGPSAlmanacPropertiesYUMA)
               yuma.ReferenceWeek = AgEGPSReferenceWeek.eGPSReferenceWeek22Aug1999
               Exit Select
          End If
End Select

' Propagate
propagator.Propagate()


Configure the Great Arc propagator with a list of waypoints

[Visual Basic .NET] Copy Code
' IAgVePropagatorGreatArc propagator: Great arc propagator

' Array with waypoints to insert
Dim waypoints As Object(,) = New Object(,) {{20.3619.41, -99.125"1 Jan 2012 12:00:00.000"}, {20.319.421, -99.135"1 Jan 2012 13:00:00.000"}, {20.319.434, -99.137"1 Jan 2012 14:00:00.000"}}

propagator.Method = AgEVeWayPtCompMethod.eDetermineVelFromTime

' Remove any previous waypoints
propagator.Waypoints.RemoveAll()

' Insert the waypoints
Dim i As Integer = 0
While i < waypoints.GetLength(0)
     Dim waypoint As IAgVeWaypointsElement = propagator.Waypoints.Add()
     waypoint.Altitude = DirectCast(waypoints(i, 0), Double)
     waypoint.Latitude = waypoints(i, 1)
     waypoint.Longitude = waypoints(i, 2)
     waypoint.Time = waypoints(i, 3)
     System.Math.Max(System.Threading.Interlocked.Increment(i),i - 1)
End While

' Propagate ground vehicle
propagator.Propagate()


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

[Visual Basic .NET] Copy Code
' IAgVePropagatorGreatArc propagator: Great arc propagator

' Array with waypoints to insert
' Consists of: altitude, latitude, longitude, speed
Dim waypoints As Double(,) = New Double(,) {{20.3619.41, -99.12510.5}, {20.319.421, -99.13512.5}, {20.319.434, -99.13715}}

propagator.Method = AgEVeWayPtCompMethod.eDetermineTimeAccFromVel

' Remove any previous waypoints
propagator.Waypoints.RemoveAll()

' Insert the waypoints
Dim i As Integer = 0
While i < waypoints.GetLength(0)
     Dim waypoint As IAgVeWaypointsElement = propagator.Waypoints.Add()
     waypoint.Altitude = waypoints(i, 0)
     waypoint.Latitude = waypoints(i, 1)
     waypoint.Longitude = waypoints(i, 2)
     waypoint.Speed = waypoints(i, 3)
     System.Math.Max(System.Threading.Interlocked.Increment(i),i - 1)
End While

' Propagate ground vehicle
propagator.Propagate()


List all waypoints in a Waypoint Collection

[Visual Basic .NET] Copy Code
' IAgVePropagatorGreatArc propagator: Great arc propagator

' Array with waypoints to insert
Dim waypoints As Object(,) = New Object(,) {{20.3619.41, -99.125"1 Jan 2012 12:00:00.000"}, {20.319.421, -99.135"1 Jan 2012 13:00:00.000"}, {20.319.434, -99.137"1 Jan 2012 14:00:00.000"}}

propagator.Method = AgEVeWayPtCompMethod.eDetermineVelFromTime

' Remove any previous waypoints
propagator.Waypoints.RemoveAll()

' Insert the waypoints
Dim i As Integer = 0
While i < waypoints.GetLength(0)
     Dim waypoint As IAgVeWaypointsElement = propagator.Waypoints.Add()
     waypoint.Altitude = DirectCast(waypoints(i, 0), Double)
     waypoint.Latitude = waypoints(i, 1)
     waypoint.Longitude = waypoints(i, 2)
     waypoint.Time = waypoints(i, 3)
     System.Math.Max(System.Threading.Interlocked.Increment(i),i - 1)
End While

' List the waypoints after extracting them into an array
Dim waypointArray As Array = propagator.Waypoints.ToArray()
Dim j As Integer = 0
While j < waypointArray.GetLength(0)
     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)))
     System.Threading.Interlocked.Increment(j)
End While


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

[Visual Basic .NET] Copy Code
' IAgVePropagatorGreatArc propagator: Great arc propagator

propagator.Method = AgEVeWayPtCompMethod.eDetermineTimeAccFromVel

Dim waypoints As Array = Array.CreateInstance(GetType(Object), 46)

' Point #1
waypoints.SetValue(000)
' Lat
waypoints.SetValue(001)
' Lon
waypoints.SetValue(3500002)
' Alt
waypoints.SetValue(3503)
' Vel
waypoints.SetValue(004)
' Acc
waypoints.SetValue(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(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(024)
' Acc
waypoints.SetValue(025)
' Turn radius
' Point #4
waypoints.SetValue(030)
' Lat
waypoints.SetValue(031)
' Lon
waypoints.SetValue(3520032)
' Alt
waypoints.SetValue(3533)
' Vel
waypoints.SetValue(034)
' Acc
waypoints.SetValue(035)
' Turn radius
#If Not CSToJava Then
propagator.SetPointsSpecifyVelocityAndPropagate(waypoints)
#Else
#End If

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


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

[Visual Basic .NET] Copy Code
' IAgVePropagatorGreatArc propagator: Great arc propagator

propagator.Method = AgEVeWayPtCompMethod.eDetermineTimeFromVelAcc

Dim waypoints As Array = Array.CreateInstance(GetType(Object), 45)
' Point #1
waypoints.SetValue(000)
' Lat
waypoints.SetValue(001)
' Lon
waypoints.SetValue(3500002)
' Alt
waypoints.SetValue(3503)
' Vel
waypoints.SetValue(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(024)
' Turn radius
' Point #4
waypoints.SetValue(030)
' Lat
waypoints.SetValue(031)
' Lon
waypoints.SetValue(3520032)
' Alt
waypoints.SetValue(3533)
' Vel
waypoints.SetValue(034)
' Turn radius
#If Not CSToJava Then
propagator.SetPointsSmoothRateAndPropagate(waypoints)
#Else
#End If

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


Set Waypoints (Derive Velocity from Time) and Propagate

[Visual Basic .NET] Copy Code
' IAgVePropagatorGreatArc propagator: Great arc propagator

propagator.Method = AgEVeWayPtCompMethod.eDetermineVelFromTime

Dim waypoints As Array = Array.CreateInstance(GetType(Object), 45)
' Point #1
waypoints.SetValue("17 Jan 2013 17:00:00.000"00)
' Time
waypoints.SetValue(001)
' Lat
waypoints.SetValue(002)
' Lon
waypoints.SetValue(3500003)
' Alt
waypoints.SetValue(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(024)
' Turn radius
' Point #4
waypoints.SetValue("17 Jan 2013 17:03:00.000"30)
' Time
waypoints.SetValue(031)
' Lat
waypoints.SetValue(032)
' Lon
waypoints.SetValue(3520033)
' Alt
waypoints.SetValue(034)
' Turn radius
#If Not CSToJava Then
propagator.SetPointsSpecifyTimeAndPropagate(waypoints)
#Else
#End If

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


Sets the ephemeris start time to an explicit time, and then add waypoints relative to that time.

[Visual Basic .NET] Copy Code
' IAgVePropagatorGreatArc propagator: Great Arc propagator

' Set the epoch time to tomorrow.
Dim startEpoch As IAgCrdnEventSmartEpoch = propagator.EphemerisInterval.GetStartEpoch()
startEpoch.SetExplicitTime("Tomorrow")
propagator.EphemerisInterval.SetStartEpoch(startEpoch)

' Waypoints time start from explicit start time that we set above.
#If Not CSToJava Then
#Else
#End If
Dim waypointsAndTimes As Array = New Object(,) {{40.329, -76.36600.01540}, {40.38, -76.35900.01540}, {40.406, -76.32900.01540}, {40.417, -76.31100.01540}}

#If Not CSToJava Then
propagator.SetPointsSmoothRateAndPropagate(waypointsAndTimes)
#Else
#End If

Dim i As Integer = 0
While i < propagator.Waypoints.Count
     Console.WriteLine("Waypoint {0}, Lat = {1}, Lon = {2}, Time = {3}", i, propagator.Waypoints(i).Latitude, propagator.Waypoints(i).Longitude, propagator.Waypoints(i).Time)
     System.Threading.Interlocked.Increment(i)
End While


Configure the HPOP propagator

[Visual Basic .NET] Copy Code
' IAgSatellite satellite: Satellite object

' Set satellite propagator to HPOP
satellite.SetPropagatorType(AgEVePropagatorType.ePropagatorHPOP)

' Get IAgVePropagatorLOP interface
Dim hpopProp As IAgVePropagatorHPOP = TryCast(satellite.Propagator, IAgVePropagatorHPOP)

' Configure force model
Dim hpopForceModel As IAgVeHPOPForceModel = 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
Dim hpopDragModel As IAgVeHPOPDragModelSpherical = TryCast(hpopForceModel.Drag.DragModel, IAgVeHPOPDragModelSpherical)
hpopDragModel.Cd = 1.89
hpopDragModel.AreaMassRatio = 0.05
hpopForceModel.Drag.AtmosphericDensityModel = AgEAtmosphericDensityModel.eMSIS90

hpopForceModel.ThirdBodyGravity.RemoveThirdBody("Moon")

' Propagate
hpopProp.Propagate()


Configure the J2 Perturbation propagator

[Visual Basic .NET] Copy Code
' IAgSatellite satellite: Satellite object

' Set propagator to SGP4
satellite.SetPropagatorType(AgEVePropagatorType.ePropagatorJ2Perturbation)

' J2 Perturbation propagator
Dim j2prop As IAgVePropagatorJ2Perturbation = TryCast(satellite.Propagator, IAgVePropagatorJ2Perturbation)

' Configure time period
j2prop.EphemerisInterval.SetExplicitInterval("1 Jan 2012 12:00:00.000""2 Jan 2012 12:00:00.000")
j2prop.[Step] = 60

' Configure propagator initial state
Dim initial As IAgVeJxInitialState = j2prop.InitialState
initial.Representation.Epoch = "1 Jan 2012 12:00:00.000"
' in km (assuming unit preferences set to km)
' in km
' in km
' in km/sec (assuming unit preferences set to km/sec)
' in km/sec
initial.Representation.AssignCartesian(AgECoordinateSystem.eCoordinateSystemFixed, -1514.4, -6790.1, -1.254.81511.771_
     5.6414)
' in km/sec
initial.EllipseOptions = AgEVeEllipseOptions.eSecularlyPrecessing

' Propagate
j2prop.Propagate()


Configure the J4 Perturbation propagator to a circular orbit

[Visual Basic .NET] Copy Code
' IAgSatellite satellite: Satellite object
' Double incl: Inclination (default 45.0)
' Double altitude: Atitude (default 500 km)

satellite.SetPropagatorType(AgEVePropagatorType.ePropagatorJ4Perturbation)
Dim prop As IAgVePropagatorJ4Perturbation = TryCast(satellite.Propagator, IAgVePropagatorJ4Perturbation)

Dim keplerian As IAgOrbitStateClassical = TryCast(prop.InitialState.Representation.ConvertTo(AgEOrbitStateType.eOrbitStateClassical), IAgOrbitStateClassical)

keplerian.SizeShapeType = AgEClassicalSizeShape.eSizeShapeAltitude
Dim size As IAgClassicalSizeShapeAltitude = TryCast(keplerian.SizeShape, IAgClassicalSizeShapeAltitude)

size.ApogeeAltitude = altitude
size.PerigeeAltitude = altitude

keplerian.Orientation.Inclination = incl
keplerian.Orientation.ArgOfPerigee = 0
keplerian.Orientation.AscNodeType = AgEOrientationAscNode.eAscNodeRAAN
TryCast(keplerian.Orientation.AscNode, IAgOrientationAscNodeRAAN).Value = 0

keplerian.LocationType = AgEClassicalLocation.eLocationTrueAnomaly
TryCast(keplerian.Location, IAgClassicalLocationTrueAnomaly).Value = 0

prop.InitialState.Representation.Assign(keplerian)
prop.Propagate()


Configure the J4 Perturbation propagator to a critically inclined orbit

[Visual Basic .NET] 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)
Dim prop As IAgVePropagatorJ4Perturbation = TryCast(satellite.Propagator, IAgVePropagatorJ4Perturbation)

Dim keplerian As IAgOrbitStateClassical = TryCast(prop.InitialState.Representation.ConvertTo(AgEOrbitStateType.eOrbitStateClassical), IAgOrbitStateClassical)

keplerian.SizeShapeType = AgEClassicalSizeShape.eSizeShapeAltitude
Dim size As IAgClassicalSizeShapeAltitude = TryCast(keplerian.SizeShape, IAgClassicalSizeShapeAltitude)

size.ApogeeAltitude = apogeeAlt
size.PerigeeAltitude = perigeeAlt

keplerian.Orientation.Inclination = 63.434949
keplerian.Orientation.ArgOfPerigee = 270
keplerian.Orientation.AscNodeType = AgEOrientationAscNode.eAscNodeLAN
TryCast(keplerian.Orientation.AscNode, IAgOrientationAscNodeLAN).Value = ascNodeLon

keplerian.LocationType = AgEClassicalLocation.eLocationTrueAnomaly
TryCast(keplerian.Location, IAgClassicalLocationTrueAnomaly).Value = 90

prop.InitialState.Representation.Assign(keplerian)
prop.Propagate()


Configure the LOP propagator

[Visual Basic .NET] Copy Code
' IAgSatellite satellite: Satellite object

' Set satellite propagator to LOP
satellite.SetPropagatorType(AgEVePropagatorType.ePropagatorLOP)

' Get IAgVePropagatorLOP interface
Dim lopProp As IAgVePropagatorLOP = TryCast(satellite.Propagator, 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
Dim orbit As IAgOrbitState = lopProp.InitialState.Representation
orbit.Epoch = "1 Jan 2012 12:00:00.000"
' in km (assuming unit preferences set to km)
' in km
' in km
' in km/sec (assuming unit preferences set to km/sec)
' in km/sec
orbit.AssignCartesian(AgECoordinateSystem.eCoordinateSystemFixed, -1120.32, -9520.840.1292.155, -1.54416_
     5.668412)
' in km/sec
' Configure force model
Dim lopForceModel As IAgVeLOPForceModel = 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.125
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

[Visual Basic .NET] Copy Code
' IAgVePropagatorRealtime propagator: Realtime Propagator

Dim points As IAgVeRealtimeLLAPoints = propagator.PointBuilder.LLA
points.Add("1 Jan 2012 12:00:00.000"39.693, -76.3990.0390.034580.01223_
     0.05402)


Add realtime LLA positions in batches

[Visual Basic .NET] Copy Code
' IAgVePropagatorRealtime propagator: Realtime Propagator

' Add realtime LLA points in batches
#If Not CSToJava Then
#Else
#End If
Dim times As Array = New Object() {"1 Jan 2012 12:00:00.000""1 Jan 2012 12:01:00.000""1 Jan 2012 12:02:00.000"}
#If Not CSToJava Then
#Else
#End If
Dim lat As Array = New Object() {39.69341.06139.925}
#If Not CSToJava Then
#Else
#End If
Dim lon As Array = New Object() {-76.399, -74.266, -78.578}
#If Not CSToJava Then
#Else
#End If
Dim alt As Array = New Object() {0.0390.0420.281}
#If Not CSToJava Then
#Else
#End If
Dim latrate As Array = New Object() {0.034580.032150.03188}
#If Not CSToJava Then
#Else
#End If
Dim lonrate As Array = New Object() {0.012230.011480.01075}
#If Not CSToJava Then
#Else
#End If
Dim altrate As Array = New Object() {0.054020.05210.05075}

Dim points As IAgVeRealtimeLLAPoints = propagator.PointBuilder.LLA

' AddBatch expects each parameter to be a one dimensional array and all of the same length
#If Not CSToJava Then
points.AddBatch(times, lat, lon, alt, latrate, lonrate, _
     altrate)
#Else
#End If


Configure the Realtime propagator

[Visual Basic .NET] 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
propagator.TimeStep = 60

' 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) Then
     ' Set the look ahead type
     propagator.LookAheadPropagator = AgELookAheadPropagator.eLookAheadTwoBody

     ' Set the duration time to look ahead and look behind
     Dim duration As IAgVeDuration = propagator.Duration
     duration.LookAhead = 3600
     duration.LookBehind = 3600

     ' Apply the Realtime Propagator settings
     propagator.Propagate()
End If


Configure the SGP4 propagator with file source

[Visual Basic .NET] 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

[Visual Basic .NET] 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

' Add segments
propagator.CommonTasks.AddSegsFromOnlineSource("25544")

' Propagate
propagator.Propagate()


Set SGP4 to auto-update from file source

[Visual Basic .NET] 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
Dim tles As Array = propagator.AutoUpdate.FileSource.Preview()

#If Not CSToJava Then
Dim rx As New Regex("^(?<ssc>[-]?\d+) (?<orbitepoch>[-]?\d+[.]?\d+) (?<revnumber>[-]?\d+)$")
#Else
#End If
For Each line As Object In tles
     Dim m As Match = rx.Match(line.ToString())
     #If Not CSToJava Then
          #Else
          #End If
     Console.WriteLine("SCC: {0}, orbit epoch: {1}, rev number: {2}", m.Groups("ssc"), m.Groups("orbitepoch"), m.Groups("revnumber"))
Next

' Propagate
propagator.Propagate()


Set SGP4 to auto-update from online source

[Visual Basic .NET] 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
Dim tles As Array = propagator.AutoUpdate.FileSource.Preview()

#If Not CSToJava Then
Dim rx As New Regex("^(?<ssc>[-]?\d+) (?<orbitepoch>[-]?\d+[.]?\d+) (?<revnumber>[-]?\d+)$")
#Else
#End If
For Each line As Object In tles
     Dim m As Match = rx.Match(line.ToString())
     #If Not CSToJava Then
          #Else
          #End If
     Console.WriteLine("SCC: {0}, orbit epoch: {1}, rev number: {2}", m.Groups("ssc"), m.Groups("orbitepoch"), m.Groups("revnumber"))
Next

' Propagate
propagator.Propagate()


Configure the Simple Ascent propagator

[Visual Basic .NET] 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

' Set the initial state
propagator.InitialState.Launch.AssignGeodetic(38.3721, -77.640225)
propagator.InitialState.Burnout.AssignGeodetic(48.1395, -82.514525)
propagator.InitialState.BurnoutVel = 7.7258

' Propagate
propagator.Propagate()


Configure the SPICE propagator

[Visual Basic .NET] 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
propagator.BodyName = "-200000"

' Propagate
propagator.Propagate()


Create a ground vehicle (on current scenario central body)

[Visual Basic .NET] Copy Code
' IAgStkObjectRoot root: STK Object Model Root

' Create the ground vehicle
Dim launchVehicle As IAgGroundVehicle = TryCast(root.CurrentScenario.Children.[New](AgESTKObjectType.eGroundVehicle, "MyGroundVehicle"), IAgGroundVehicle)


Get the ground vehicle Attitude Export tool

[Visual Basic .NET] Copy Code
' IAgGroundVehicle groundVehicle: GroundVehicle whose attitude we want to export

Dim attExTool As IAgVeAttitudeExportTool = groundVehicle.ExportTools.GetAttitudeExportTool()


Get the ground vehicle Propagator Definition Export tool

[Visual Basic .NET] Copy Code
' IAgGroundVehicle groundVehicle: GroundVehicle whose propagator definition we want to export

Dim attExTool As IAgVePropDefExportTool = groundVehicle.ExportTools.GetPropDefExportTool()


Get the ground vehicle STK Ephemeris Export tool

[Visual Basic .NET] Copy Code
' IAgGroundVehicle groundVehicle: GroundVehicle whose ephemeris we want to export

Dim stkEphem As IAgVeEphemerisStkExportTool = groundVehicle.ExportTools.GetEphemerisStkExportTool()


Set ground vehicle to use Great Arc propagator

[Visual Basic .NET] Copy Code
' IAgGroundVehicle groundVehicle: Ground Vehicle object

' Set ground vehicle route to great arc
groundVehicle.SetRouteType(AgEVePropagatorType.ePropagatorGreatArc)

' Retrieve propagator interface if necessary
Dim propagator As IAgVePropagatorGreatArc = TryCast(groundVehicle.Route, IAgVePropagatorGreatArc)


Set ground vehicle to use Realtime propagator

[Visual Basic .NET] Copy Code
' IAgGroundVehicle groundVehicle: Ground Vehicle object

' Set ground vehicle route to STK External propagator
groundVehicle.SetRouteType(AgEVePropagatorType.ePropagatorRealtime)

' Retrieve propagator interface if necessary
Dim propagator As IAgVePropagatorRealtime = TryCast(groundVehicle.Route, IAgVePropagatorRealtime)


Set ground vehicle to use STK External propagator

[Visual Basic .NET] Copy Code
' IAgGroundVehicle groundVehicle: Ground Vehicle object

' Set groundVehicle route to STK External propagator
groundVehicle.SetRouteType(AgEVePropagatorType.ePropagatorStkExternal)

' Retrieve propagator interface if necessary
Dim propagator As IAgVePropagatorStkExternal = TryCast(groundVehicle.Route, IAgVePropagatorStkExternal)


Create a launch vehicle (on current scenario central body)

[Visual Basic .NET] Copy Code
' IAgStkObjectRoot root: STK Object Model Root

' Create the Launch vehicle
Dim launchVehicle As IAgLaunchVehicle = TryCast(root.CurrentScenario.Children.[New](AgESTKObjectType.eLaunchVehicle, "MyLaunchVehicle"), IAgLaunchVehicle)


Determine if trajectory type is supported

[Visual Basic .NET] Copy Code
' IAgLaunchVehicle launchVehicle: Launch vehicle

Dim supported As Boolean = launchVehicle.IsTrajectoryTypeSupported(AgEVePropagatorType.ePropagatorRealtime)


Define missile trajectory

[Visual Basic .NET] Copy Code
' IAgMissile missile: Chain object

' Set missile trajectory type
missile.SetTrajectoryType(AgEVePropagatorType.ePropagatorBallistic)

' Retrieve the Propagator interface
Dim trajectory As IAgVePropagatorBallistic = TryCast(missile.Trajectory, 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

' Set flight parameters
trajectory.SetLaunchType(AgEVeLaunch.eLaunchLLA)
Dim launch As IAgVeLaunchLLA = TryCast(trajectory.Launch, IAgVeLaunchLLA)
launch.Lat = 0
launch.Lon = 0
launch.Alt = 0

' Set impact location type
trajectory.SetImpactLocationType(AgEVeImpactLocation.eImpactLocationPoint)

' Retrieve the impact point interface
Dim impactLocation As IAgVeImpactLocationPoint = TryCast(trajectory.ImpactLocation, IAgVeImpactLocationPoint)
impactLocation.SetLaunchControlType(AgEVeLaunchControl.eLaunchControlFixedTimeOfFlight)

' Retrieve the launch flight interface
Dim launchControl As IAgVeLaunchControlFixedTimeOfFlight = TryCast(impactLocation.LaunchControl, IAgVeLaunchControlFixedTimeOfFlight)
launchControl.TimeOfFlight = 9000

' Configure missile Impact parameters
impactLocation.SetImpactType(AgEVeImpact.eImpactLLA)
Dim impact As IAgVeImpactLLA = TryCast(impactLocation.Impact, IAgVeImpactLLA)
impact.Lat = 12
impact.Lon = 5
impact.Alt = 0

' Propagate Missile
trajectory.Propagate()


Create a satellite (on current scenario central body)

[Visual Basic .NET] Copy Code
' IAgStkObjectRoot root: STK Object Model root

' Create the Satellite
Dim satellite As IAgSatellite = TryCast(root.CurrentScenario.Children.[New](AgESTKObjectType.eSatellite, "MySatellite"), IAgSatellite)


Create a satellite from an external ephemeris file (.e)

[Visual Basic .NET] Copy Code
' IAgStkObjectRoot root: STK Object Model root
' String ephemerisFilePath: Path to external ephemeris data file

Dim satellite As IAgSatellite = TryCast(root.CurrentScenario.Children.[New](AgESTKObjectType.eSatellite, "MySatellite"), IAgSatellite)

' Configure propagator's external file path
satellite.SetPropagatorType(AgEVePropagatorType.ePropagatorStkExternal)
Dim ext As IAgVePropagatorStkExternal = TryCast(satellite.Propagator, IAgVePropagatorStkExternal)
ext.Filename = ephemerisFilePath

' Propagate
ext.Propagate()


Create a satellite from the satellite database

[Visual Basic .NET] Copy Code
' IAgStkObjectRoot root: STK Object Model root

' Get STK database location using Connect
Dim result As IAgExecCmdResult = root.ExecuteCommand("GetDirectory / Database Satellite")
Dim satDataDir As String = result(0)
Dim filelocation As String = """" + Path.Combine(satDataDir, "stkAllTLE.sd") + """"
Dim commonname As String = """hst"""

' Import object from database using Connect
Dim command As String = [String].Format("ImportFromDB * Satellite {0} Constellation ImportedFromSatDB Propagate On CommonName {1}", filelocation, commonname)
root.ExecuteCommand(command)


Set the satellite to use the GPS propagator

[Visual Basic .NET] Copy Code
' IAgSatellite satellite: Satellite object

' Set propagator to GPS
satellite.SetPropagatorType(AgEVePropagatorType.ePropagatorGPS)

' Get the GPS propagator
Dim propagator As IAgVePropagatorGPS = TryCast(satellite.Propagator, IAgVePropagatorGPS)


Set the satellite to use the HPOP propagator

[Visual Basic .NET] Copy Code
' IAgSatellite satellite: Satellite object

' Set satellite propagator to HPOP
satellite.SetPropagatorType(AgEVePropagatorType.ePropagatorHPOP)

' Get the HPOP propagator
Dim propagator As IAgVePropagatorHPOP = TryCast(satellite.Propagator, IAgVePropagatorHPOP)


Set the satellite to use the J2 propagator

[Visual Basic .NET] Copy Code
' IAgSatellite satellite: Satellite object

' Set propagator to J2 Perturbation
satellite.SetPropagatorType(AgEVePropagatorType.ePropagatorJ2Perturbation)

' Get the J2 Perturbation propagator
Dim propagator As IAgVePropagatorJ2Perturbation = TryCast(satellite.Propagator, IAgVePropagatorJ2Perturbation)


Set the satellite to use the LOP propagator

[Visual Basic .NET] Copy Code
' IAgSatellite satellite: Satellite object

' Set satellite propagator to LOP
satellite.SetPropagatorType(AgEVePropagatorType.ePropagatorLOP)

' Get the LOP propagator
Dim propagator As IAgVePropagatorLOP = TryCast(satellite.Propagator, IAgVePropagatorLOP)


Set the satellite to use the SGP4 propagator

[Visual Basic .NET] Copy Code
' IAgSatellite satellite: Satellite object

' Set propagator to SGP4
satellite.SetPropagatorType(AgEVePropagatorType.ePropagatorSGP4)

' Get the SGP4 propagator
Dim propagator As IAgVePropagatorSGP4 = TryCast(satellite.Propagator, IAgVePropagatorSGP4)


Set the satellite to use the SPICE propagator

[Visual Basic .NET] Copy Code
' IAgSatellite satellite: Satellite object

' Set propagator to SPICE
satellite.SetPropagatorType(AgEVePropagatorType.ePropagatorSPICE)

' Get the SPICE propagator
Dim propagator As IAgVePropagatorSPICE = TryCast(satellite.Propagator, IAgVePropagatorSPICE)



Set the satellite to use the STK External propagator

[Visual Basic .NET] Copy Code
' IAgSatellite satellite: Satellite object

' Set propagator to STK External
satellite.SetPropagatorType(AgEVePropagatorType.ePropagatorStkExternal)

' Get the STK External propagator
Dim propagator As IAgVePropagatorStkExternal = TryCast(satellite.Propagator, IAgVePropagatorStkExternal)


Create a ship (on current scenario central body)

[Visual Basic .NET] Copy Code
' IAgStkObjectRoot root: STK Object Model Root

' Create the Ship
Dim ship As IAgShip = TryCast(root.CurrentScenario.Children.[New](AgESTKObjectType.eShip, "MyShip"), IAgShip)


Set ship to use Great Arc propagator

[Visual Basic .NET] Copy Code
' IAgShip ship: Ship object

' Set ship route to great arc
ship.SetRouteType(AgEVePropagatorType.ePropagatorGreatArc)

' Retrieve propagator interface if necessary
Dim propagator As IAgVePropagatorGreatArc = TryCast(ship.Route, IAgVePropagatorGreatArc)


Set ship to use Realtime propagator

[Visual Basic .NET] Copy Code
' IAgShip ship: Ship object

' Set ship route to STK External propagator
ship.SetRouteType(AgEVePropagatorType.ePropagatorRealtime)

' Retrieve propagator interface if necessary
Dim propagator As IAgVePropagatorRealtime = TryCast(ship.Route, IAgVePropagatorRealtime)


Set ship to use STK External propagator

[Visual Basic .NET] Copy Code
' IAgShip ship: Ship object

' Set ship route to STK External propagator
ship.SetRouteType(AgEVePropagatorType.ePropagatorStkExternal)

' Retrieve propagator interface if necessary
Dim propagator As IAgVePropagatorStkExternal = TryCast(ship.Route, IAgVePropagatorStkExternal)


Add an Attribute that provides a combobox of values from which the user can choose.

[Visual Basic .NET] Copy Code

'Add the following code to your plugin
Public _choice As Object
Public Property Choice() As Object Implements IExample1.Choice
    Get
        Return _choice
    End Get
    Set(ByVal value As Object)
        _choice = value
    End Set
End Property
Public Choices() As Object = New Object(3) {"0""1""2""3"}


Public Function GetPluginConfig(ByVal pAttrBuilder As AGI.Attr.AgAttrBuilder) As Object Implements IAgUtPluginConfig.GetPluginConfig
    If m_AgAttrScope = Nothing Then
        m_AgAttrScope = pAttrBuilder.NewScope()
        pAttrBuilder.AddChoicesDispatchProperty(m_AgAttrScope, "Choice""A property""Choice", Choices)
    End If

    Return m_AgAttrScope
End Function


Add an Attribute that provides a combobox of values populated by a function from which the user can choose.

[Visual Basic .NET] Copy Code

'Add the following code to your plugin
      Public _choice As Object
      Public Property Choice() As Object Implements IExample2.Choice
          Get
              Return _choice
          End Get
          Set(ByVal value As Object)
              _choice = value
          End Set
      End Property
      Public ReadOnly Property Choices() As Object() Implements IExample2.Choices
          Get
              Return New Object(3) {"0""1""2""3"}
          End Get
      End Property


      Public Function GetPluginConfig(ByVal pAttrBuilder As AGI.Attr.AgAttrBuilder) As Object Implements IAgUtPluginConfig.GetPluginConfig
          If m_AgAttrScope = Nothing Then
              m_AgAttrScope = pAttrBuilder.NewScope()
              pAttrBuilder.AddChoicesFuncDispatchProperty(m_AgAttrScope, "Choice""A property""Choice""Choices")
          End If

          Return m_AgAttrScope
      End Function


Shows the format of the Center parameter when creating a bounding sphere.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Dim center As Array = New Object() {1247.87, -4739.744067.77}

Dim boundingSphere As IAgStkGraphicsBoundingSphere = sceneManager.Initializers.BoundingSphere.Initialize(center, 100)


Shows the format of the Size parameter when computing using a box triangulator.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Dim size As Array = New Object() {100010002000}

Dim result As IAgStkGraphicsSolidTriangulatorResult = sceneManager.Initializers.BoxTriangulator.Compute(size)


Change view mode to use Earth's fixed frame

[Visual Basic .NET] 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.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsScene scene: Current Scene

Dim position As Array = New Object() {31378.100}

scene.Camera.Position = position


Shows the format of the Camera's ReferencePoint property.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsScene scene: Current Scene

Dim point As Array = New Object() {31378.100}

scene.Camera.ReferencePoint = point


Shows the format of the Camera's UpVector property.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsScene scene: Current Scene

Dim upVector As Array = New Object() {001}

scene.Camera.UpVector = upVector


Shows the format of the Extent parameter when zooming to a cartographic extent on a central body.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsScene scene: Current Scene

Dim extent As Array = New Object() {9030, -7739}

scene.Camera.ViewExtent("Earth", extent)


Shows the format of the Offset and UpAxis parameters when setting the camera's reference point with an offset.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsScene scene: Current Scene
' IAgCrdnPoint point: A valid VGT point object.
' IAgCrdnAxes axes: A valid VGT axes object.

Dim offset As Array = New Object() {5050, -50}

Dim upAxis As Array = New Object() {001}

scene.Camera.ViewOffsetWithUpAxis(axes, point, offset, upAxis)


Shows the format of the Position parameter when converting a cartogaphic position to a pixel coordinate.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsScene scene: Current Scene

Dim position As Array = New Object() {0.627, -1.6440}

Dim windowPos As Array = scene.Camera.CartographicToWindow("Earth", position)


Shows the format of the Position parameter when converting a pixel coordinate to a cartographic position.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsScene scene: Current Scene

Dim position As Array = New Object() {150116}

Dim cartographicPos As Array = scene.Camera.WindowToCartographic("Earth", position)


Take a snapshot of the camera's view

[Visual Basic .NET] Copy Code
' IAgStkGraphicsScene scene: Current Scene
' AgStkObjectRoot root: STK Object Model root

Dim manager As IAgStkGraphicsSceneManager = DirectCast(root.CurrentScenario, IAgScenario).SceneManager

'
' The snapshot can be saved to a file, texture, image, or the clipboard
'
Dim texture As IAgStkGraphicsRendererTexture2D = scene.Camera.Snapshot.SaveToTexture()

Dim overlay As IAgStkGraphicsTextureScreenOverlay = CreateOverlayFromTexture(texture, root)
Dim screenOverlayManager As IAgStkGraphicsScreenOverlayCollectionBase = DirectCast(manager.ScreenOverlays, IAgStkGraphicsScreenOverlayCollectionBase)
screenOverlayManager.Add(DirectCast(overlay, IAgStkGraphicsScreenOverlay))


Shows the format of the ConvolutionFilter's Kernel property.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsConvolutionFilter convolutionFilter: A valid convolution filter

Dim kernel As Array = New Object() {111111_
     111}

convolutionFilter.Kernel = kernel


Shows the format of the Kernel parameter when creating a convolution filter.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Dim kernel As Array = New Object() {111111_
     111}

Dim convolutionFilter As IAgStkGraphicsConvolutionFilter = sceneManager.Initializers.ConvolutionFilter.InitializeWithKernel(kernel)


Shows the format of the distance to position display condition's Position property.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsDistanceToPositionDisplayCondition condition: A distance to position display condition

Dim position As Array = New Object() {670000}

condition.Position = position


Shows the format of the Position parameter when creating a distance to position display condition.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Dim position As Array = New Object() {670000}

Dim condition As IAgStkGraphicsDistanceToPositionDisplayCondition = sceneManager.Initializers.DistanceToPositionDisplayCondition.InitializeWithDistances(position, 010000)


Draw a primitive based on a time interval

[Visual Basic .NET] Copy Code
' IAgStkGraphicsScene scene: Current Scene
' AgStkObjectRoot root: STK Object Model root
' String globeOverlayFile: Location of the globe overlay file

Dim manager As IAgStkGraphicsSceneManager = DirectCast(root.CurrentScenario, IAgScenario).SceneManager

Dim overlay As IAgStkGraphicsGeospatialImageGlobeOverlay = manager.Initializers.GeospatialImageGlobeOverlay.InitializeWithString(globeOverlayFile)

Dim start As IAgDate = root.ConversionUtility.NewDate("UTCG""30 May 2008 14:30:00.000")
Dim [endAs IAgDate = root.ConversionUtility.NewDate("UTCG""30 May 2008 15:00:00.000")

DirectCast(root.CurrentScenario, IAgScenario).Animation.StartTime = Double.Parse(start.Subtract("sec"3600).Format("epSec"))

Dim condition As IAgStkGraphicsTimeIntervalDisplayCondition = manager.Initializers.TimeIntervalDisplayCondition.InitializeWithTimes(start, [end])
DirectCast(overlay, IAgStkGraphicsGlobeOverlay).DisplayCondition = TryCast(condition, IAgStkGraphicsDisplayCondition)

scene.CentralBodies.Earth.Imagery.Add(DirectCast(overlay, IAgStkGraphicsGlobeImageOverlay))



Draw a primitive based on multiple conditions

[Visual Basic .NET] 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

Dim manager As IAgStkGraphicsSceneManager = DirectCast(root.CurrentScenario, IAgScenario).SceneManager
Dim position As Array = New Object() {29.98, -90.250.0}

Dim model As IAgStkGraphicsModelPrimitive = manager.Initializers.ModelPrimitive.InitializeWithStringUri( _
    modelFile)
model.SetPositionCartographic("Earth", position)
model.Scale = Math.Pow(101.5)

Dim start1 As IAgDate = root.ConversionUtility.NewDate("UTCG""30 May 2008 14:00:00.000")
Dim end1 As IAgDate = root.ConversionUtility.NewDate("UTCG""30 May 2008 14:30:00.000")
DirectCast(root, IAgAnimation).CurrentTime = Double.Parse(start1.Format("epSec"))
Dim start2 As IAgDate = root.ConversionUtility.NewDate("UTCG""30 May 2008 15:00:00.000")
Dim end2 As IAgDate = root.ConversionUtility.NewDate("UTCG""30 May 2008 15:30:00.000")

Dim time1 As IAgStkGraphicsTimeIntervalDisplayCondition = manager.Initializers.TimeIntervalDisplayCondition.InitializeWithTimes(start1, end1)
Dim time2 As IAgStkGraphicsTimeIntervalDisplayCondition = manager.Initializers.TimeIntervalDisplayCondition.InitializeWithTimes(start2, end2)
Dim composite As IAgStkGraphicsCompositeDisplayCondition = manager.Initializers.CompositeDisplayCondition.Initialize()

composite.Add(DirectCast(time1, IAgStkGraphicsDisplayCondition))
composite.Add(DirectCast(time2, IAgStkGraphicsDisplayCondition))
composite.LogicOperation = AgEStkGraphicsBinaryLogicOperation.eStkGraphicsBinaryLogicOperationOr
DirectCast(model, IAgStkGraphicsPrimitive).DisplayCondition = TryCast(composite, IAgStkGraphicsDisplayCondition)

Dim result As IAgCrdnAxesFindInAxesResult = root.VgtRoot.WellKnownAxes.Earth.Fixed.FindInAxes(DirectCast(root.CurrentScenario, IAgScenario).Epoch, DirectCast(axes, IAgCrdnAxes))
model.Orientation = result.Orientation

manager.Primitives.Add(DirectCast(model, IAgStkGraphicsPrimitive))


Draw a primitive based on viewer altitude

[Visual Basic .NET] Copy Code
' IAgStkGraphicsScene scene: Current Scene
' AgStkObjectRoot root: STK Object Model root

Dim manager As IAgStkGraphicsSceneManager = DirectCast(root.CurrentScenario, IAgScenario).SceneManager
Dim extent As Array = New Object() _
_
    -9429_
    -8933 _
}

Dim triangles As IAgStkGraphicsSurfaceTriangulatorResult = manager.Initializers.SurfaceExtentTriangulator.ComputeSimple("Earth", extent)

Dim line As IAgStkGraphicsPolylinePrimitive = manager.Initializers.PolylinePrimitive.Initialize()
Dim boundaryPositions As Array = triangles.BoundaryPositions
line.Set(boundaryPositions)
DirectCast(line, IAgStkGraphicsPrimitive).Color = Color.White

Dim condition As IAgStkGraphicsAltitudeDisplayCondition = manager.Initializers.AltitudeDisplayCondition.InitializeWithAltitudes(5000002500000)
DirectCast(line, IAgStkGraphicsPrimitive).DisplayCondition = TryCast(condition, IAgStkGraphicsDisplayCondition)

manager.Primitives.Add(DirectCast(line, IAgStkGraphicsPrimitive))



Draw a primitive based on viewer distance

[Visual Basic .NET] Copy Code
' IAgStkGraphicsScene scene: Current Scene
' AgStkObjectRoot root: STK Object Model root
' String modelFile: Location of the model file

Dim manager As IAgStkGraphicsSceneManager = DirectCast(root.CurrentScenario, IAgScenario).SceneManager
Dim model As IAgStkGraphicsModelPrimitive = manager.Initializers.ModelPrimitive.InitializeWithStringUri( _
    modelFile)
Dim position As Array = New Object() {29.98, -90.258000.0}
model.SetPositionCartographic("Earth", position)
model.Scale = Math.Pow(103)

Dim condition As IAgStkGraphicsDistanceDisplayCondition = manager.Initializers.DistanceDisplayCondition.InitializeWithDistances(200040000)
DirectCast(model, IAgStkGraphicsPrimitive).DisplayCondition = TryCast(condition, IAgStkGraphicsDisplayCondition)

manager.Primitives.Add(DirectCast(model, IAgStkGraphicsPrimitive))


Draw a screen overlay based on viewer distance

[Visual Basic .NET] Copy Code
' IAgStkGraphicsScene scene: Current Scene
' AgStkObjectRoot root: STK Object Model root
' IAgStkGraphicsModelPrimitive model: A model
' IAgStkGraphicsScreenOverlay overlay: A overlay

Dim manager As IAgStkGraphicsSceneManager = DirectCast(root.CurrentScenario, IAgScenario).SceneManager
Dim overlayManager As IAgStkGraphicsScreenOverlayCollectionBase = DirectCast(manager.ScreenOverlays.Overlays, IAgStkGraphicsScreenOverlayCollectionBase)

Dim condition As IAgStkGraphicsDistanceToPrimitiveDisplayCondition = manager.Initializers.DistanceToPrimitiveDisplayCondition.InitializeWithDistances(DirectCast(model, IAgStkGraphicsPrimitive), 040000)
DirectCast(overlay, IAgStkGraphicsOverlay).DisplayCondition = DirectCast(condition, IAgStkGraphicsDisplayCondition)

manager.Primitives.Add(DirectCast(model, IAgStkGraphicsPrimitive))
overlayManager.Add(overlay)


Shows the format of the TimeInterval parameter when creating a time interval display condition.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Dim timeInterval As Array = New Object() {"1 Jan 2012 12:00:00.000""1 Jan 2012 14:00:00.000"}

sceneManager.Initializers.TimeIntervalDisplayCondition.InitializeWithTimeInterval(timeInterval)


Shows the format of the Radii parameter when computing using an ellipsoid triangulator.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Dim radii As Array = New Object() {200010001000}

Dim result As IAgStkGraphicsSolidTriangulatorResult = sceneManager.Initializers.EllipsoidTriangulator.ComputeSimple(radii)


Shows the format of the BottomPositions and TopPositions parameters when computing using an extruded polyline triangulator with cartographic positions.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Dim bottomPositions As Array = New Object() {002000000.10.1200000_
     00.120000000200000}

Dim topPositions As Array = New Object() {0.10.19000000.20.2900000_
     0.10.29000000.10.1900000}

Dim result As IAgStkGraphicsExtrudedPolylineTriangulatorResult = sceneManager.Initializers.ExtrudedPolylineTriangulator.ComputeCartographic("Earth", bottomPositions, topPositions)


Shows the format of the BottomPositions and TopPositions parameters when computing using an extruded polyline triangulator.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Dim bottomPositions As Array = New Object() {6578.14006512.79653.458652.476_
     6545.27656.71806578.1400}

Dim topPositions As Array = New Object() {7205.81722.992722.366991.681417.281437.63_
     7097.631438.76722.367205.81722.992722.36}

Dim result As IAgStkGraphicsExtrudedPolylineTriangulatorResult = sceneManager.Initializers.ExtrudedPolylineTriangulator.Compute("Earth", bottomPositions, topPositions)


Shows the format of the Positions parameter when computing using an extruded polyline triangulator with altitudes and cartographic positions.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Dim positions As Array = New Object() {002000000.10.1200000_
     00.120000000200000}

Dim result As IAgStkGraphicsExtrudedPolylineTriangulatorResult = sceneManager.Initializers.ExtrudedPolylineTriangulator.ComputeCartographicWithAltitudes("Earth", positions, 0100)


Shows the format of the Positions parameter when computing using an extruded polyline triangulator with altitudes.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Dim positions As Array = New Object() {6578.14006512.79653.458652.476_
     6545.27656.71806578.1400}

Dim result As IAgStkGraphicsExtrudedPolylineTriangulatorResult = sceneManager.Initializers.ExtrudedPolylineTriangulator.ComputeWithAltitudes("Earth", positions, 0100)


Shows the format of the Positions parameter when computing using an extruded polyline triangulator with cartographic positions.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Dim positions As Array = New Object() {0, -0.007915000, -0.0078045000_
     00.0079150000045000_
     0, -0.007915000}

Dim result As IAgStkGraphicsExtrudedPolylineTriangulatorResult = sceneManager.Initializers.ExtrudedPolylineTriangulator.ComputeSingleConstantAltitudeCartographic("Earth", positions, 30000)


Shows the format of the Positions parameter when computing using an extruded polyline triangulator.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Dim positions As Array = New Object() {6392.94, -50.505306422.940, -49.7669_
     6392.9450.505306422.94049.7669_
     6392.94, -50.50530}

Dim result As IAgStkGraphicsExtrudedPolylineTriangulatorResult = sceneManager.Initializers.ExtrudedPolylineTriangulator.ComputeSingleConstantAltitude("Earth", positions, 30000)


Add custom imagery to the globe

[Visual Basic .NET] Copy Code
' IAgStkGraphicsScene scene: Current Scene
' AgStkObjectRoot root: STK Object Model root

Dim manager As IAgStkGraphicsSceneManager = DirectCast(root.CurrentScenario, IAgScenario).SceneManager

Dim activator As IAgStkGraphicsCustomImageGlobeOverlayPluginActivator = manager.Initializers.CustomImageGlobeOverlayPluginActivator.Initialize()
Dim proxy As IAgStkGraphicsCustomImageGlobeOverlayPluginProxy = activator.CreateFromDisplayName("OpenStreetMapPlugin.VBNET")

Dim overlay As IAgStkGraphicsCustomImageGlobeOverlay = proxy.CustomImageGlobeOverlay
scene.CentralBodies.Earth.Imagery.Add(DirectCast(overlay, IAgStkGraphicsGlobeImageOverlay))


Add jp2 imagery to the globe

[Visual Basic .NET] 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
'
Dim overlay As IAgStkGraphicsGlobeImageOverlay = scene.CentralBodies.Earth.Imagery.AddUriString(globeOverlayFile)


Add terrain to the globe

[Visual Basic .NET] Copy Code
' IAgStkGraphicsScene scene: Current Scene
' AgStkObjectRoot root: STK Object Model root
' String terrainOverlayFile: The terrain overlay file

Dim overlay As IAgStkGraphicsTerrainOverlay = scene.CentralBodies.Earth.Terrain.AddUriString( _
    terrainOverlayFile)


Draw an image on top of another

[Visual Basic .NET] 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

Dim topOverlay As IAgStkGraphicsGlobeImageOverlay = scene.CentralBodies.Earth.Imagery.AddUriString(topOverlayFile)
Dim bottomOverlay As IAgStkGraphicsGlobeImageOverlay = 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.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Dim extent As Array = New Object() {9030, -7739}

Dim overlay As IAgStkGraphicsRasterImageGlobeOverlay = sceneManager.Initializers.RasterImageGlobeOverlay.InitializeWithColor(Color.Red, extent)


Adjust brightness, contrast, and gamma

[Visual Basic .NET] Copy Code
' IAgStkGraphicsScene scene: Current Scene
' AgStkObjectRoot root: STK Object Model root
' String imageFile: The image file

Dim manager As IAgStkGraphicsSceneManager = DirectCast(root.CurrentScenario, IAgScenario).SceneManager
Dim overlayManager As IAgStkGraphicsScreenOverlayCollectionBase = DirectCast(manager.ScreenOverlays.Overlays, IAgStkGraphicsScreenOverlayCollectionBase)
'
' The URI can be a file path, http, https, or ftp location
'
Dim image As IAgStkGraphicsRaster = manager.Initializers.Raster.InitializeWithStringUri( _
    imageFile)

'
' Add brightness, contrast, and gamma correction filters to sequence
'
Dim sequenceFilter As IAgStkGraphicsSequenceFilter = manager.Initializers.SequenceFilter.Initialize()
sequenceFilter.Add(DirectCast(manager.Initializers.BrightnessFilter.InitializeWithAdjustment(0.1), IAgStkGraphicsRasterFilter))
sequenceFilter.Add(DirectCast(manager.Initializers.ContrastFilter.InitializeWithAdjustment(0.2), IAgStkGraphicsRasterFilter))
sequenceFilter.Add(DirectCast(manager.Initializers.GammaCorrectionFilter.InitializeWithGamma(0.9), IAgStkGraphicsRasterFilter))

image.ApplyInPlace(DirectCast(sequenceFilter, IAgStkGraphicsRasterFilter))

Dim texture As IAgStkGraphicsRendererTexture2D = manager.Textures.FromRaster(image)

Dim overlay As IAgStkGraphicsTextureScreenOverlay = manager.Initializers.TextureScreenOverlay.Initialize()
DirectCast(overlay, IAgStkGraphicsOverlay).Width = 0.2
DirectCast(overlay, IAgStkGraphicsOverlay).WidthUnit = AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitFraction
DirectCast(overlay, IAgStkGraphicsOverlay).Height = 0.2
DirectCast(overlay, IAgStkGraphicsOverlay).HeightUnit = AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitFraction
overlay.Texture = texture
DirectCast(overlay, IAgStkGraphicsOverlay).Origin = AgEStkGraphicsScreenOverlayOrigin.eStkGraphicsScreenOverlayOriginCenterRight

overlayManager.Add(DirectCast(overlay, IAgStkGraphicsScreenOverlay))


Adjust the color levels of an image

[Visual Basic .NET] Copy Code
' IAgStkGraphicsScene scene: Current Scene
' AgStkObjectRoot root: STK Object Model root
' String imageFile: The image file

Dim manager As IAgStkGraphicsSceneManager = DirectCast(root.CurrentScenario, IAgScenario).SceneManager
Dim overlayManager As IAgStkGraphicsScreenOverlayCollectionBase = DirectCast(manager.ScreenOverlays.Overlays, IAgStkGraphicsScreenOverlayCollectionBase)
'
' The URI can be a file path, http, https, or ftp location
'
Dim image As IAgStkGraphicsRaster = manager.Initializers.Raster.InitializeWithStringUri( _
    imageFile)

'
' Adjust the color levels of the image
'
Dim levelsFilter As IAgStkGraphicsLevelsFilter = manager.Initializers.LevelsFilter.Initialize()
levelsFilter.SetLevelAdjustment(AgEStkGraphicsRasterBand.eStkGraphicsRasterBandBlue, -255)
levelsFilter.SetLevelAdjustment(AgEStkGraphicsRasterBand.eStkGraphicsRasterBandGreen, -255)
image.ApplyInPlace(DirectCast(levelsFilter, IAgStkGraphicsRasterFilter))

Dim texture As IAgStkGraphicsRendererTexture2D = manager.Textures.FromRaster(image)

Dim overlay As IAgStkGraphicsTextureScreenOverlay = manager.Initializers.TextureScreenOverlay.Initialize()
DirectCast(overlay, IAgStkGraphicsOverlay).Width = 0.2
DirectCast(overlay, IAgStkGraphicsOverlay).WidthUnit = AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitFraction
DirectCast(overlay, IAgStkGraphicsOverlay).Height = 0.2
DirectCast(overlay, IAgStkGraphicsOverlay).HeightUnit = AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitFraction
overlay.Texture = texture
DirectCast(overlay, IAgStkGraphicsOverlay).Origin = AgEStkGraphicsScreenOverlayOrigin.eStkGraphicsScreenOverlayOriginBottomRight

overlayManager.Add(DirectCast(overlay, IAgStkGraphicsScreenOverlay))


Blur an image with a convolution matrix

[Visual Basic .NET] Copy Code
' IAgStkGraphicsScene scene: Current Scene
' AgStkObjectRoot root: STK Object Model root
' String imageFile: The image file

Dim manager As IAgStkGraphicsSceneManager = DirectCast(root.CurrentScenario, IAgScenario).SceneManager
Dim overlayManager As IAgStkGraphicsScreenOverlayCollectionBase = DirectCast(manager.ScreenOverlays.Overlays, IAgStkGraphicsScreenOverlayCollectionBase)
'
' The URI can be a file path, http, https, or ftp location
'
Dim image As IAgStkGraphicsRaster = manager.Initializers.Raster.InitializeWithStringUri( _
    imageFile)

'
' Set convolution matrix to blur
'
Dim kernel As Array = New Object() {111111_
 111}
Dim convolutionMatrix As IAgStkGraphicsConvolutionFilter = manager.Initializers.ConvolutionFilter.InitializeWithKernelAndDivisor(kernel, 9.0)
image.ApplyInPlace(DirectCast(convolutionMatrix, IAgStkGraphicsRasterFilter))

Dim texture As IAgStkGraphicsRendererTexture2D = manager.Textures.FromRaster(image)

Dim overlay As IAgStkGraphicsTextureScreenOverlay = manager.Initializers.TextureScreenOverlay.Initialize()
DirectCast(overlay, IAgStkGraphicsOverlay).Width = 0.2
DirectCast(overlay, IAgStkGraphicsOverlay).WidthUnit = AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitFraction
DirectCast(overlay, IAgStkGraphicsOverlay).Height = 0.2
DirectCast(overlay, IAgStkGraphicsOverlay).HeightUnit = AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitFraction
overlay.Texture = texture
DirectCast(overlay, IAgStkGraphicsOverlay).Origin = AgEStkGraphicsScreenOverlayOrigin.eStkGraphicsScreenOverlayOriginBottomLeft

overlayManager.Add(DirectCast(overlay, IAgStkGraphicsScreenOverlay))


Extract the alpha component from an image

[Visual Basic .NET] Copy Code
' IAgStkGraphicsScene scene: Current Scene
' AgStkObjectRoot root: STK Object Model root
' String imageFile: The image file

Dim manager As IAgStkGraphicsSceneManager = DirectCast(root.CurrentScenario, IAgScenario).SceneManager
Dim overlayManager As IAgStkGraphicsScreenOverlayCollectionBase = DirectCast(manager.ScreenOverlays.Overlays, IAgStkGraphicsScreenOverlayCollectionBase)
'
' The URI can be a file path, http, https, or ftp location
'
Dim image As IAgStkGraphicsRaster = manager.Initializers.Raster.InitializeWithStringUri( _
    imageFile)

'
' Extract the alpha channel from the image
'
Dim channelExtract As IAgStkGraphicsBandExtractFilter = manager.Initializers.BandExtractFilter.InitializeWithBand(AgEStkGraphicsRasterBand.eStkGraphicsRasterBandAlpha)
image.ApplyInPlace(DirectCast(channelExtract, IAgStkGraphicsRasterFilter))

Dim texture As IAgStkGraphicsRendererTexture2D = manager.Textures.FromRaster(image)

Dim overlay As IAgStkGraphicsTextureScreenOverlay = manager.Initializers.TextureScreenOverlay.Initialize()
DirectCast(overlay, IAgStkGraphicsOverlay).Width = 0.2
DirectCast(overlay, IAgStkGraphicsOverlay).WidthUnit = AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitFraction
DirectCast(overlay, IAgStkGraphicsOverlay).Height = 0.2
DirectCast(overlay, IAgStkGraphicsOverlay).HeightUnit = AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitFraction
overlay.Texture = texture
DirectCast(overlay, IAgStkGraphicsOverlay).Origin = AgEStkGraphicsScreenOverlayOrigin.eStkGraphicsScreenOverlayOriginTopRight

overlayManager.Add(DirectCast(overlay, IAgStkGraphicsScreenOverlay))


Flip an image

[Visual Basic .NET] Copy Code
' IAgStkGraphicsScene scene: Current Scene
' AgStkObjectRoot root: STK Object Model root
' String imageFile: The image file

Dim manager As IAgStkGraphicsSceneManager = DirectCast(root.CurrentScenario, IAgScenario).SceneManager
Dim overlayManager As IAgStkGraphicsScreenOverlayCollectionBase = DirectCast(manager.ScreenOverlays.Overlays, IAgStkGraphicsScreenOverlayCollectionBase)
'
' The URI can be a file path, http, https, or ftp location
'
Dim image As IAgStkGraphicsRaster = manager.Initializers.Raster.InitializeWithStringUri( _
    imageFile)
image.Flip(AgEStkGraphicsFlipAxis.eStkGraphicsFlipAxisVertical)

Dim texture As IAgStkGraphicsRendererTexture2D = manager.Textures.FromRaster(image)

Dim overlay As IAgStkGraphicsTextureScreenOverlay = manager.Initializers.TextureScreenOverlay.Initialize()
DirectCast(overlay, IAgStkGraphicsOverlay).Size = New Object() _
    { _
        0.20.2_
        AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitFraction, _
        AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitFraction _
    }
overlay.Texture = texture
DirectCast(overlay, IAgStkGraphicsOverlay).Origin = AgEStkGraphicsScreenOverlayOrigin.eStkGraphicsScreenOverlayOriginTopLeft

overlayManager.Add(DirectCast(overlay, IAgStkGraphicsScreenOverlay))


Load and display a raster stream

[Visual Basic .NET] Copy Code
' IAgStkGraphicsScene scene: Current Scene
' AgStkObjectRoot root: STK Object Model root
' String imageFile: The image file

Dim manager As IAgStkGraphicsSceneManager = DirectCast(root.CurrentScenario, IAgScenario).SceneManager
Dim overlayManager As IAgStkGraphicsScreenOverlayCollectionBase = DirectCast(manager.ScreenOverlays.Overlays, IAgStkGraphicsScreenOverlayCollectionBase)

'
' Create the RasterStream from the plugin
'
Dim activator As IAgStkGraphicsProjectionRasterStreamPluginActivator = manager.Initializers.ProjectionRasterStreamPluginActivator.Initialize()
Dim proxy As IAgStkGraphicsProjectionRasterStreamPluginProxy = activator.CreateFromDisplayName("ProjectionRasterStreamPlugin.VBNET")

'
' Use reflection to set the plugin's properties
'
Dim plugin As Type = proxy.RealPluginObject.[GetType]()
plugin.GetProperty("RasterPath").SetValue(proxy.RealPluginObject, imageFile, Nothing)

Dim rasterStream As IAgStkGraphicsRasterStream = proxy.RasterStream
rasterStream.UpdateDelta = 0.01667

'
' Creates the texture overlay
'
Dim texture As IAgStkGraphicsRendererTexture2D = manager.Textures.FromRaster(DirectCast(rasterStream, IAgStkGraphicsRaster))
Dim overlay As IAgStkGraphicsTextureScreenOverlay = manager.Initializers.TextureScreenOverlay.InitializeWithXYWidthHeight(00, texture.Template.Width, texture.Template.Height)
overlay.Texture = texture
DirectCast(overlay, IAgStkGraphicsOverlay).Origin = AgEStkGraphicsScreenOverlayOrigin.eStkGraphicsScreenOverlayOriginCenterLeft

overlayManager.Add(DirectCast(overlay, IAgStkGraphicsScreenOverlay))



Swizzle an image's components

[Visual Basic .NET] Copy Code
' IAgStkGraphicsScene scene: Current Scene
' AgStkObjectRoot root: STK Object Model root
' String imageFile: The image file

Dim manager As IAgStkGraphicsSceneManager = DirectCast(root.CurrentScenario, IAgScenario).SceneManager
Dim overlayManager As IAgStkGraphicsScreenOverlayCollectionBase = DirectCast(manager.ScreenOverlays.Overlays, IAgStkGraphicsScreenOverlayCollectionBase)
'
' The URI can be a file path, http, https, or ftp location
'
Dim image As IAgStkGraphicsRaster = manager.Initializers.Raster.InitializeWithStringUri( _
    imageFile)

'
' Swizzle RGBA to BGRA
'
Dim channelOrder As IAgStkGraphicsBandOrderFilter = manager.Initializers.BandOrderFilter.InitializeWithOrder(AgEStkGraphicsRasterFormat.eStkGraphicsRasterFormatBgra)
image.ApplyInPlace(DirectCast(channelOrder, IAgStkGraphicsRasterFilter))

Dim texture As IAgStkGraphicsRendererTexture2D = manager.Textures.FromRaster(image)

Dim overlay As IAgStkGraphicsTextureScreenOverlay = manager.Initializers.TextureScreenOverlay.Initialize()
DirectCast(overlay, IAgStkGraphicsOverlay).Width = 0.2
DirectCast(overlay, IAgStkGraphicsOverlay).WidthUnit = AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitFraction
DirectCast(overlay, IAgStkGraphicsOverlay).Height = 0.2
DirectCast(overlay, IAgStkGraphicsOverlay).HeightUnit = AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitFraction
overlay.Texture = texture
DirectCast(overlay, IAgStkGraphicsOverlay).Origin = AgEStkGraphicsScreenOverlayOrigin.eStkGraphicsScreenOverlayOriginTopCenter

overlayManager.Add(DirectCast(overlay, IAgStkGraphicsScreenOverlay))


Shows the format of the Extent and SubExtent parameters when writing using a Jpeg 2000 Writer.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager
' String imagePath: Path to the image to write
' String saveFile: Path to the output file

Dim extent As Array = New Object() {-1, -111}

Dim subExtent As Array = New Object() {-0.5, -0.50.50.5}

sceneManager.Initializers.Jpeg2000Writer.WriteExtentAndSubExtentString(imagePath, extent, subExtent, AgEStkGraphicsJpeg2000CompressionProfile.eStkGraphicsJpeg2000CompressionProfileDefault, 1, saveFile, _
     True)


Shows the format of the model's Position property.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsModelPrimitive model: A model primitive

Dim position As Array = New Object() {31378.100}

model.Position = position


Shows the format of the Position parameter when updating a model.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsModelPrimitive model: A model primitive

Dim position As Array = New Object() {39.88, -75.250}

model.SetPositionCartographic("Earth", position)


Shows the format of the overlay's MaximumSize property.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsOverlay overlay: A valid overlay object.

Dim maximumSize As Array = New Object() {500500, AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitPixels, AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitPixels}

overlay.MaximumSize = maximumSize


Shows the format of the overlay's MinimumSize property.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsOverlay overlay: A valid overlay object.

Dim minimumSize As Array = New Object() {55, AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitPixels, AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitPixels}

overlay.MinimumSize = minimumSize


Shows the format of the overlay's Padding property.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsOverlay overlay: A valid overlay object.

Dim padding As Array = New Object() {10101010}

overlay.Padding = padding


Shows the format of the overlay's PinningPosition property.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsOverlay overlay: A valid overlay object.

Dim pinningPosition As Array = New Object() {55, AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitPixels, AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitPixels}

overlay.PinningPosition = pinningPosition


Shows the format of the overlay's Position property.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsOverlay overlay: A valid overlay object.

Dim position As Array = New Object() {5050, AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitPixels, AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitPixels}

overlay.Position = position


Shows the format of the overlay's RotationPoint property.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsOverlay overlay: A valid overlay object.

Dim rotationPoint As Array = New Object() {False, AgEStkGraphicsScreenOverlayOrigin.eStkGraphicsScreenOverlayOriginCenter, True00, AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitPixels, _
     AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitPixels}

overlay.RotationPoint = rotationPoint


Shows the format of the overlay's Size property.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsOverlay overlay: A valid overlay object.

Dim size As Array = New Object() {300300, AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitPixels, AgEStkGraphicsScreenOverlayUnit.eStkGraphicsScreenOverlayUnitPixels}

overlay.Size = size


Shows the format of the path point's Position property.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsPathPoint path: A valid path point object

Dim position As Array = New Object() {1089235, -48009304046386}

path.Position = position


Shows the format of the Position parameter when creating a path point.

[Visual Basic .NET] Copy Code
' AgStkObjectRoot root: STK Object Model root
' IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Dim position As Array = New Object() {1089235, -48009304046386}

Dim path As IAgStkGraphicsPathPoint = sceneManager.Initializers.PathPoint.InitializeWithDateAndPosition(root.ConversionUtility.NewDate("UTCG"DirectCast(root.CurrentScenario, IAgScenario).StartTime.ToString()), position)


Change a model's color on mouse over

[Visual Basic .NET] 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.
'
            Dim collection As IAgStkGraphicsPickResultCollection = scene.Pick(mouseX, mouseY)
If collection.Count <> 0 Then
     Dim objects As IAgStkGraphicsObjectCollection = collection(0).Objects
     Dim composite As IAgStkGraphicsCompositePrimitive = TryCast(objects(0), IAgStkGraphicsCompositePrimitive)

     '
     ' Was a model in our composite picked?
     '
                If composite Is m_Models Then
                    Dim model As IAgStkGraphicsPrimitive = TryCast(objects(1), IAgStkGraphicsPrimitive)

                    '
                    ' Selected Model
                    '
                    model.Color = Color.Cyan

                    If model IsNot m_SelectedModel Then
                        '
                        ' Unselect previous model
                        '
                        If m_SelectedModel IsNot Nothing Then
                            m_SelectedModel.Color = Color.Red
                        End If
                        m_SelectedModel = model
                        scene.Render()
                    End If
                    Return
                End If
End If

'
' Unselect previous model
'
If m_SelectedModel IsNot Nothing Then
                m_SelectedModel.Color = Color.Red
     m_SelectedModel = Nothing
     scene.Render()


Change model colors within a rectangular region

[Visual Basic .NET] Copy Code
' IAgStkGraphicsScene scene: Current Scene
' AgStkObjectRoot root: STK Object Model root
' List(Of IAgStkGraphicsModelPrimitive) SelectedModels: The previously selected models

Dim manager As IAgStkGraphicsSceneManager = DirectCast(root.CurrentScenario, IAgScenario).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.
'
Dim newModels As New List(Of IAgStkGraphicsModelPrimitive)()
Dim collection As IAgStkGraphicsPickResultCollection = scene.PickRectangular(mouseX - 50, mouseY + 50, mouseX + 50, mouseY - 50)
For Each pickResult As IAgStkGraphicsPickResult In collection
    Dim objects As IAgStkGraphicsObjectCollection = pickResult.Objects
    Dim composite As IAgStkGraphicsCompositePrimitive = TryCast(objects(0), IAgStkGraphicsCompositePrimitive)

    '
    ' Was a model in our composite picked?
    '
    If composite Is m_Models Then
        Dim model As IAgStkGraphicsModelPrimitive = TryCast(objects(1), IAgStkGraphicsModelPrimitive)

        '
        ' Selected Model
        '
        DirectCast(model, IAgStkGraphicsPrimitive).Color = Color.Cyan
        newModels.Add(model)
    End If
Next
'
' Reset color of models that were previous selected but were not in this pick.
'
For Each selectedModel As IAgStkGraphicsModelPrimitive In SelectedModels
    If Not newModels.Contains(selectedModel) Then
        DirectCast(selectedModel, IAgStkGraphicsPrimitive).Color = Color.Red
    End If
Next
SelectedModels = newModels




Zoom to a model on double click

[Visual Basic .NET] Copy Code
' IAgStkGraphicsScene scene: Current Scene
' AgStkObjectRoot root: STK Object Model root

Dim selectedModel As IAgStkGraphicsPrimitive = Nothing
'
' Get a collection of picked objects under the mouse location.
' The collection is sorted with the closest object at index zero.
'
Dim collection As IAgStkGraphicsPickResultCollection = scene.Pick(mouseX, mouseY)
If collection.Count <> 0 Then
    Dim objects As IAgStkGraphicsObjectCollection = collection(0).Objects
    Dim composite As IAgStkGraphicsCompositePrimitive = TryCast(objects(0), IAgStkGraphicsCompositePrimitive)

    '
    ' Was a model in our composite picked?
    '
    If composite Is m_Models Then
        selectedModel = TryCast(objects(1), IAgStkGraphicsPrimitive)
    End If


Zoom to a particular marker in a batch

[Visual Basic .NET] Copy Code
' IAgStkGraphicsScene scene: Current Scene
' AgStkObjectRoot root: STK Object Model root
' String markerFile: The file to use for the markers
' IList(Of Array) markerPositions: A list of the marker positions

Dim selectedMarkerCartesianPosition As Array = Nothing
'
' Get a collection of picked objects under the mouse location.
' The collection is sorted with the closest object at index zero.
'
Dim collection As IAgStkGraphicsPickResultCollection = scene.Pick(mouseX, mouseY)
If collection.Count <> 0 Then
     Dim objects As IAgStkGraphicsObjectCollection = collection(0).Objects
     Dim batchPrimitive As IAgStkGraphicsMarkerBatchPrimitive = TryCast(objects(0), IAgStkGraphicsMarkerBatchPrimitive)

     '
     ' Was a marker in our marker batch picked?
     '
     If batchPrimitive Is m_MarkerBatch Then
          '
          ' Get the index of the particular marker we picked
          '
          Dim markerIndex As IAgStkGraphicsBatchPrimitiveIndex = TryCast(objects(1), IAgStkGraphicsBatchPrimitiveIndex)
          '
          ' Get the position of the particular marker we picked
          '
          Dim markerCartographic As Array = markerPositions(markerIndex.Index)

          Dim markerPosition As IAgPosition = root.ConversionUtility.NewPositionOnEarth()
          markerPosition.AssignPlanetodetic(CDbl(markerCartographic.GetValue(0)), CDbl(markerCartographic.GetValue(1)), CDbl(markerCartographic.GetValue(2)))

          Dim x As Double, y As Double, z As Double
          markerPosition.QueryCartesian(x, y, z)

          selectedMarkerCartesianPosition = New Object() {x, y, z}
     End If
End If


Dim manager As IAgStkGraphicsSceneManager = DirectCast(root.CurrentScenario, IAgScenario).SceneManager

Dim positions As IList(Of Array) = New List(Of 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})

Dim positionsArray As Array = Array.CreateInstance(GetType(Object), positions.Count * 3)
For i As Integer = 0 To positions.Count - 1
     Dim position As Array = positions(i)
     position.CopyTo(positionsArray, i * 3)
Next

Dim markerBatch As IAgStkGraphicsMarkerBatchPrimitive = manager.Initializers.MarkerBatchPrimitive.Initialize()
markerBatch.Texture = manager.Textures.LoadFromStringUri( _
     markerFile)
markerBatch.SetCartographic("Earth", 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(DirectCast(markerBatch, IAgStkGraphicsPrimitive))


Shows the format of the Positions parameter when interpolating positions.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Dim interpolator As IAgStkGraphicsPositionInterpolator = TryCast(sceneManager.Initializers.GreatArcInterpolator.InitializeWithCentralBody("Earth"), IAgStkGraphicsPositionInterpolator)

Dim positions As Array = New Object() {39.88, -75.25038.85, -77.040}

Dim results As Array = interpolator.Interpolate(positions)


Create layers of primitives

[Visual Basic .NET] 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

Dim manager As IAgStkGraphicsSceneManager = DirectCast(root.CurrentScenario, IAgScenario).SceneManager

Dim r As New Random()
Dim holder As Integer = 25
Dim modelCount As Integer = 25

Dim positions As Array = Array.CreateInstance(GetType(Object), modelCount * 3)

'
' Create the models
'
Dim models As IAgStkGraphicsCompositePrimitive = manager.Initializers.CompositePrimitive.Initialize()

For i As Integer = 0 To modelCount - 1
    Dim latitude As Double = 35 + 1.5 * r.NextDouble()
    Dim longitude As Double = -(80 + 1.5 * r.NextDouble())
    Dim altitude As Double = 0
    Dim position As Array = New Object() {latitude, longitude, altitude}

    positions.SetValue(latitude, 3 * i)
    positions.SetValue(longitude, (3 * i) + 1)
    positions.SetValue(altitude, (3 * i) + 2)

    Dim model As IAgStkGraphicsModelPrimitive = manager.Initializers.ModelPrimitive.InitializeWithStringUri(modelFile)
    model.SetPositionCartographic("Earth", position)
    model.Scale = Math.Pow(102)
    models.Add(model)
Next

'
' Create the markers
'
Dim markers As IAgStkGraphicsMarkerBatchPrimitive = manager.Initializers.MarkerBatchPrimitive.Initialize()
markers.RenderPass = AgEStkGraphicsMarkerBatchRenderPass.eStkGraphicsMarkerBatchRenderPassTranslucent

markers.Texture = manager.Textures.LoadFromStringUri(markerFile)
markers.SetCartographic("Earth", positions)

'
' Create the points
'
Dim points As IAgStkGraphicsPointBatchPrimitive = manager.Initializers.PointBatchPrimitive.Initialize()
points.PixelSize = 5
DirectCast(points, IAgStkGraphicsPrimitive).Color = Color.Orange
Dim colors As Array = Array.CreateInstance(GetType(Object), modelCount)
For i As Integer = 0 To colors.Length - 1
    colors.SetValue(Color.Orange.ToArgb(), i)
Next
points.SetCartographicWithColorsAndRenderPass("Earth", positions, colors, AgEStkGraphicsRenderPassHint.eStkGraphicsRenderPassHintOpaque)

'
' Set the display Conditions
'
Dim near As IAgStkGraphicsAltitudeDisplayCondition = manager.Initializers.AltitudeDisplayCondition.InitializeWithAltitudes(0500000)
DirectCast(models, IAgStkGraphicsPrimitive).DisplayCondition = DirectCast(near, IAgStkGraphicsDisplayCondition)

Dim medium As IAgStkGraphicsAltitudeDisplayCondition = manager.Initializers.AltitudeDisplayCondition.InitializeWithAltitudes(5000002000000)
DirectCast(markers, IAgStkGraphicsPrimitive).DisplayCondition = DirectCast(medium, IAgStkGraphicsDisplayCondition)

Dim far As IAgStkGraphicsAltitudeDisplayCondition = manager.Initializers.AltitudeDisplayCondition.InitializeWithAltitudes(20000004000000)
DirectCast(points, IAgStkGraphicsPrimitive).DisplayCondition = DirectCast(far, IAgStkGraphicsDisplayCondition)

manager.Primitives.Add(DirectCast(models, IAgStkGraphicsPrimitive))
manager.Primitives.Add(DirectCast(markers, IAgStkGraphicsPrimitive))
manager.Primitives.Add(DirectCast(points, IAgStkGraphicsPrimitive))



Z-order primitives on the surface

[Visual Basic .NET] 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

Dim manager As IAgStkGraphicsSceneManager = DirectCast(root.CurrentScenario, IAgScenario).SceneManager

Dim pennsylvania As IAgStkGraphicsTriangleMeshPrimitive = manager.Initializers.TriangleMeshPrimitive.Initialize()
pennsylvania.SetTriangulator(DirectCast(manager.Initializers.SurfacePolygonTriangulator.Compute("Earth", pennsylvaniaPositions), IAgStkGraphicsTriangulatorResult))
DirectCast(pennsylvania, IAgStkGraphicsPrimitive).Color = Color.Yellow

Dim areaCode610 As IAgStkGraphicsTriangleMeshPrimitive = manager.Initializers.TriangleMeshPrimitive.Initialize()
areaCode610.SetTriangulator(DirectCast(manager.Initializers.SurfacePolygonTriangulator.Compute("Earth", areaCode610Positions), IAgStkGraphicsTriangulatorResult))
DirectCast(areaCode610, IAgStkGraphicsPrimitive).Color = Color.DarkRed

Dim areaCode215 As IAgStkGraphicsTriangleMeshPrimitive = manager.Initializers.TriangleMeshPrimitive.Initialize()
areaCode215.SetTriangulator(DirectCast(manager.Initializers.SurfacePolygonTriangulator.Compute("Earth", areaCode215Positions), IAgStkGraphicsTriangulatorResult))
DirectCast(areaCode215, IAgStkGraphicsPrimitive).Color = Color.Green

Dim schuylkillRiver As IAgStkGraphicsPolylinePrimitive = manager.Initializers.PolylinePrimitive.Initialize()
schuylkillRiver.Set(schuylkillPositions)
DirectCast(schuylkillRiver, IAgStkGraphicsPrimitive).Color = Color.Blue
schuylkillRiver.Width = 2

Dim composite As IAgStkGraphicsCompositePrimitive = manager.Initializers.CompositePrimitive.Initialize()
composite.Add(DirectCast(pennsylvania, IAgStkGraphicsPrimitive))
composite.Add(DirectCast(areaCode610, IAgStkGraphicsPrimitive))
composite.Add(DirectCast(areaCode215, IAgStkGraphicsPrimitive))
composite.Add(DirectCast(schuylkillRiver, IAgStkGraphicsPrimitive))

manager.Primitives.Add(DirectCast(composite, IAgStkGraphicsPrimitive))


Draw a set of markers

[Visual Basic .NET] Copy Code
' IAgStkGraphicsScene scene: Current Scene
' AgStkObjectRoot root: STK Object Model root
' String markerImageFile: The image file to use for the markers

Dim manager As IAgStkGraphicsSceneManager = DirectCast(root.CurrentScenario, IAgScenario).SceneManager

Dim positions As Array = New Object() { _
    39.88, -75.250_
     38.85, -77.040_
     29.98, -90.250_
     37.37, -121.920}

Dim markerBatch As IAgStkGraphicsMarkerBatchPrimitive = manager.Initializers.MarkerBatchPrimitive.Initialize()
markerBatch.Texture = manager.Textures.LoadFromStringUri( _
    markerImageFile)
markerBatch.SetCartographic("Earth", positions)

manager.Primitives.Add(DirectCast(markerBatch, IAgStkGraphicsPrimitive))


Shows the format of the Colors parameter when setting per marker colors.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Dim colors As Array = New Object() {Color.Red.ToArgb(), Color.Green.ToArgb(), Color.Blue.ToArgb(), Color.White.ToArgb()}

Dim parameters As IAgStkGraphicsMarkerBatchPrimitiveOptionalParameters = sceneManager.Initializers.MarkerBatchPrimitiveOptionalParameters.Initialize()
parameters.SetColors(colors)


Shows the format of the Colors, Positions and Indices parameters when updating a marker batch primitive with cartographic positions.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager
' IAgStkGraphicsMarkerBatchPrimitive markerBatch: A marker batch primitive

Dim colors As Array = New Object() {Color.Red.ToArgb(), Color.Green.ToArgb(), Color.Blue.ToArgb(), Color.White.ToArgb()}

Dim parameters As IAgStkGraphicsMarkerBatchPrimitiveOptionalParameters = sceneManager.Initializers.MarkerBatchPrimitiveOptionalParameters.Initialize()
parameters.SetColors(colors)

Dim positions As Array = New Object() {39.88, -75.25038.85, -77.040_
     29.98, -90.25037.37, -121.920}

Dim indices As Array = New Object() {0123}

markerBatch.SetPartialCartographicWithOptionalParametersIndicesOrderAndRenderPass("Earth", positions, parameters, indices, AgEStkGraphicsIndicesOrderHint.eStkGraphicsIndicesOrderHintSortedAscending, AgEStkGraphicsRenderPassHint.eStkGraphicsRenderPassHintOpaque)


Shows the format of the Colors, Positions and Indices parameters when updating a marker batch primitive.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager
' IAgStkGraphicsMarkerBatchPrimitive markerBatch: A marker batch primitive

Dim colors As Array = New Object() {Color.Red.ToArgb(), Color.Green.ToArgb(), Color.Blue.ToArgb(), Color.White.ToArgb()}

Dim parameters As IAgStkGraphicsMarkerBatchPrimitiveOptionalParameters = sceneManager.Initializers.MarkerBatchPrimitiveOptionalParameters.Initialize()
parameters.SetColors(colors)

Dim positions As Array = New Object() {1247.87, -4739.744067.771115.48, -4847.093979.36_
     -24.12, -5529.313168.45, -2683.42, -4307.743850.11}

Dim indices As Array = New Object() {0123}

markerBatch.SetPartialWithOptionalParametersIndicesOrderAndRenderPass(positions, parameters, indices, AgEStkGraphicsIndicesOrderHint.eStkGraphicsIndicesOrderHintSortedAscending, AgEStkGraphicsRenderPassHint.eStkGraphicsRenderPassHintOpaque)


Shows the format of the EyeOffsets parameter when setting per marker eye offsets.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Dim eyeoffset As Array = New Object() {234234}

Dim parameters As IAgStkGraphicsMarkerBatchPrimitiveOptionalParameters = sceneManager.Initializers.MarkerBatchPrimitiveOptionalParameters.Initialize()
parameters.SetEyeOffsets(eyeoffset)


Shows the format of the marker batch's EyeOffset property.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsMarkerBatchPrimitive markerBatch: A marker batch primitive

Dim eyeoffset As Array = New Object() {234}

markerBatch.EyeOffset = eyeoffset


Shows the format of the marker batch's PixelOffset property.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsMarkerBatchPrimitive markerBatch: A marker batch primitive

Dim pixelOffset As Array = New Object() {12}

markerBatch.PixelOffset = pixelOffset


Shows the format of the marker batch's Size property.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsMarkerBatchPrimitive markerBatch: A marker batch primitive

Dim size As Array = New Object() {256128}

markerBatch.Size = size


Shows the format of the marker batch's TextureCoordinate property.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsMarkerBatchPrimitive markerBatch: A marker batch primitive

Dim coordinates As Array = New Object() {0011}

markerBatch.TextureCoordinate = coordinates


Shows the format of the Origins parameter when setting per marker origins.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Dim origins As Array = New Object() {AgEStkGraphicsOrigin.eStkGraphicsOriginCenter, AgEStkGraphicsOrigin.eStkGraphicsOriginBottomLeft, AgEStkGraphicsOrigin.eStkGraphicsOriginBottomRight, AgEStkGraphicsOrigin.eStkGraphicsOriginTopLeft}

Dim parameters As IAgStkGraphicsMarkerBatchPrimitiveOptionalParameters = sceneManager.Initializers.MarkerBatchPrimitiveOptionalParameters.Initialize()
parameters.SetOrigins(origins)


Shows the format of the PixelOffsets parameter when setting per marker pixel offsets.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Dim pixelOffset As Array = New Object() {1221}

Dim parameters As IAgStkGraphicsMarkerBatchPrimitiveOptionalParameters = sceneManager.Initializers.MarkerBatchPrimitiveOptionalParameters.Initialize()
parameters.SetPixelOffsets(pixelOffset)


Shows the format of the RotationAngles parameter when setting per marker rotations.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Dim rotations As Array = New Object() {15304560}

Dim parameters As IAgStkGraphicsMarkerBatchPrimitiveOptionalParameters = sceneManager.Initializers.MarkerBatchPrimitiveOptionalParameters.Initialize()
parameters.SetRotations(rotations)


Shows the format of the Sizes parameter when setting per marker sizes.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Dim size As Array = New Object() {256128128256}

Dim parameters As IAgStkGraphicsMarkerBatchPrimitiveOptionalParameters = sceneManager.Initializers.MarkerBatchPrimitiveOptionalParameters.Initialize()
parameters.SetSizes(size)


Shows the format of the TextureCoordinates parameter when setting per marker texture coordinates.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsSceneManager sceneManager: The STK Graphics scene manager

Dim coordinates As Array = New Object() {001111_
     00}

Dim parameters As IAgStkGraphicsMarkerBatchPrimitiveOptionalParameters = sceneManager.Initializers.MarkerBatchPrimitiveOptionalParameters.Initialize()
parameters.SetTextureCoordinates(coordinates)


Shows the format of the Textures parameter when setting per marker textures.

[Visual Basic .NET] 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

Dim textures As Array = New Object() {sceneManager.Textures.LoadFromStringUri(texturePath1), sceneManager.Textures.LoadFromStringUri(texturePath2), sceneManager.Textures.LoadFromStringUri(texturePath3), sceneManager.Textures.LoadFromStringUri(texturePath4)}

Dim parameters As IAgStkGraphicsMarkerBatchPrimitiveOptionalParameters = sceneManager.Initializers.MarkerBatchPrimitiveOptionalParameters.Initialize()
parameters.SetTextures(textures)


Draw a Collada model with user defined lighting

[Visual Basic .NET] Copy Code
' IAgStkGraphicsScene scene: Current Scene
' AgStkObjectRoot root: STK Object Model root
' String modelFile: The model file

Dim manager As IAgStkGraphicsSceneManager = DirectCast(root.CurrentScenario, IAgScenario).SceneManager
Dim model As IAgStkGraphicsModelPrimitive = manager.Initializers.ModelPrimitive.InitializeWithStringUri( _
    modelFile)

Dim position As Array = New Object() {39.88, -75.25500000.0}
model.SetPositionCartographic("Earth", position)
model.Scale = Math.Pow(102)

manager.Primitives.Add(DirectCast(model, IAgStkGraphicsPrimitive))


Draw a Collada or MDL model

[Visual Basic .NET] Copy Code
' IAgStkGraphicsScene scene: Current Scene
' AgStkObjectRoot root: STK Object Model root
' String modelFile: The model file

Dim manager As IAgStkGraphicsSceneManager = DirectCast(root.CurrentScenario, IAgScenario).SceneManager
Dim model As IAgStkGraphicsModelPrimitive = manager.Initializers.ModelPrimitive.InitializeWithStringUri( _
    modelFile)

Dim position As Array = New Object() {39.88, -75.255000.0}
model.SetPositionCartographic("Earth", position)
model.Scale = Math.Pow(102)

manager.Primitives.Add(DirectCast(model, IAgStkGraphicsPrimitive))


Draw a dynamically textured Collada model

[Visual Basic .NET] Copy Code
' IAgStkGraphicsScene scene: Current Scene
' AgStkObjectRoot root: STK Object Model root
' String modelFile: The model file

Dim manager As IAgStkGraphicsSceneManager = DirectCast(root.CurrentScenario, IAgScenario).SceneManager
Dim model As IAgStkGraphicsModelPrimitive = manager.Initializers.ModelPrimitive.InitializeWithStringUri( _
    modelFile)

Dim position As Array = New Object() {49.88, -77.255000.0}
model.SetPositionCartographic("Earth", position)
model.Scale = Math.Pow(102)

manager.Primitives.Add(DirectCast(model, IAgStkGraphicsPrimitive))

'  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

[Visual Basic .NET] Copy Code
' IAgStkGraphicsScene scene: Current Scene
' AgStkObjectRoot root: STK Object Model root
' String modelFile: The model file

Dim manager As IAgStkGraphicsSceneManager = DirectCast(root.CurrentScenario, IAgScenario).SceneManager
'
' Create the model
'
Dim model As IAgStkGraphicsModelPrimitive = manager.Initializers.ModelPrimitive.InitializeWithStringUri( _
     modelFile)

Dim position As Array = New Object() {36, -116.7525000.0}
model.SetPositionCartographic("Earth", position)

'
' Rotate the model to be oriented correctly
'
model.Articulations.GetByName("Commuter").GetByName("Roll").CurrentValue = 4.08407
model.Articulations.GetByName("Commuter").GetByName("Yaw").CurrentValue = -0.43633

manager.Primitives.Add(DirectCast(model, IAgStkGraphicsPrimitive))


Friend Sub TimeChanged(TimeEpSec As Double)
     '
     ' Rotate the propellors every time the animation updates
     '
     If m_Model IsNot Nothing Then
          Dim TwoPI As Double = 2 * Math.PI
          DirectCast(m_Model, IAgStkGraphicsModelPrimitive).Articulations.GetByName("props").GetByName("Spin").CurrentValue = TimeEpSec Mod TwoPI
     End If
End Sub


Orient a model

[Visual Basic .NET] 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

Dim manager As IAgStkGraphicsSceneManager = DirectCast(root.CurrentScenario, IAgScenario).SceneManager

Dim model As IAgStkGraphicsModelPrimitive = manager.Initializers.ModelPrimitive.InitializeWithStringUri( _
    modelFile)
DirectCast(model, IAgStkGraphicsPrimitive).ReferenceFrame = referenceFrame
' Model is oriented using east-north-up axes.  Use model.Orientation for addition rotation.
Dim zero As Array = New Object() {000}
' Origin of reference frame
model.Position = zero
model.Scale = Math.Pow(101.5)

manager.Primitives.Add(DirectCast(model, IAgStkGraphicsPrimitive))


Shows the format of the Positions parameter when adding points to a path primitive.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsPathPrimitive path: A path primitive

Dim positions As Array = New Object() {000111_
     222333_
     444}

path.AddRangeToFront(positions)


Draw a set of points

[Visual Basic .NET] Copy Code
' IAgStkGraphicsScene scene: Current Scene
' AgStkObjectRoot root: STK Object Model root

Dim manager As IAgStkGraphicsSceneManager = DirectCast(root.CurrentScenario, IAgScenario).SceneManager
' Philadelphia
' Washington, D.C.
' New Orleans
' San Jose
Dim positions As Array = New Object() {39.88, -75.250_
                                       38.85, -77.040_
                                       29.98, -90.250_
                                       37.37, -121.920}

Dim pointBatch As IAgStkGraphicsPointBatchPrimitive = manager.Initializers.PointBatchPrimitive.Initialize()
pointBatch.SetCartographic("Earth", positions)
pointBatch.PixelSize = 5
DirectCast(pointBatch, IAgStkGraphicsPrimitive).Color = Color.White
pointBatch.DisplayOutline = True
pointBatch.OutlineWidth = 2
pointBatch.OutlineColor = Color.Red

manager.Primitives.Add(DirectCast(pointBatch, IAgStkGraphicsPrimitive))


Draw a set of uniquely colored points

[Visual Basic .NET] Copy Code
' IAgStkGraphicsScene scene: Current Scene
' AgStkObjectRoot root: STK Object Model root

Dim manager As IAgStkGraphicsSceneManager = DirectCast(root.CurrentScenario, IAgScenario).SceneManager
' San Francisco, Sacramento, Los Angeles, San Diego
Dim positions As Array = New Object() _
_
    37.62, -122.380.0_
    38.52, -121.50.0_
    33.93, -118.40.0_
    32.82, -117.130.0 _
}

Dim colors As Array = New Object() _
_
    Color.Red.ToArgb(), _
     Color.Orange.ToArgb(), _
     Color.Blue.ToArgb(), _
     Color.White.ToArgb() _
}

Dim pointBatch As IAgStkGraphicsPointBatchPrimitive = manager.Initializers.PointBatchPrimitive.Initialize()
pointBatch.SetCartographicWithColors("Earth", positions, colors)
pointBatch.PixelSize = 8

manager.Primitives.Add(DirectCast(pointBatch, IAgStkGraphicsPrimitive))


Shows the format of the Positions, Colors and Indices parameters when updating a point batch with cartographic positions.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsPointBatchPrimitive pointBatch: A point batch primitive

Dim positions As Array = New Object() {39.88, -75.25038.85, -77.040_
     29.98, -90.25037.37, -121.920}

Dim colors As Array = New Object() {Color.Red.ToArgb(), Color.Green.ToArgb(), Color.Blue.ToArgb(), Color.White.ToArgb()}

Dim indices As Array = New Object() {0123}

pointBatch.SetPartialCartographicWithColorsIndicesOrderAndRenderPass("Earth", positions, colors, indices, AgEStkGraphicsIndicesOrderHint.eStkGraphicsIndicesOrderHintSortedAscending, AgEStkGraphicsRenderPassHint.eStkGraphicsRenderPassHintOpaque)


Shows the format of the Positions, Colors and Indices parameters when updating a point batch.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsPointBatchPrimitive pointBatch: A point batch primitive

Dim positions As Array = New Object() {1247.87, -4739.744067.771115.48, -4847.093979.36_
     -24.12, -5529.313168.45, -2683.42, -4307.743850.11}

Dim colors As Array = New Object() {Color.Red.ToArgb(), Color.Green.ToArgb(), Color.Blue.ToArgb(), Color.White.ToArgb()}

Dim indices As Array = New Object() {0123}

pointBatch.SetPartialWithColorsIndicesOrderAndRenderPass(positions, colors, indices, AgEStkGraphicsIndicesOrderHint.eStkGraphicsIndicesOrderHintSortedAscending, AgEStkGraphicsRenderPassHint.eStkGraphicsRenderPassHintOpaque)


Draw a great arc on the globe

[Visual Basic .NET] Copy Code
' IAgStkGraphicsScene scene: Current Scene
' AgStkObjectRoot root: STK Object Model root

Dim manager As IAgStkGraphicsSceneManager = DirectCast(root.CurrentScenario, IAgScenario).SceneManager
Dim washingtonDC As Array = New Object() {38.85, -77.040.0}
Dim newOrleans As Array = New Object() {29.98, -90.250.0}

Dim positions As Array = New Object(5) {}
washingtonDC.CopyTo(positions, 0)
newOrleans.CopyTo(positions, 3)

Dim interpolator As IAgStkGraphicsPositionInterpolator = TryCast(manager.Initializers.GreatArcInterpolator.Initialize(), IAgStkGraphicsPositionInterpolator)
Dim line As IAgStkGraphicsPolylinePrimitive = manager.Initializers.PolylinePrimitive.InitializeWithInterpolator(interpolator)
line.SetCartographic("Earth", positions)

manager.Primitives.Add(DirectCast(line, IAgStkGraphicsPrimitive))


Draw a line between two points

[Visual Basic .NET] Copy Code
' IAgStkGraphicsScene scene: Current Scene
' AgStkObjectRoot root: STK Object Model root

Dim manager As IAgStkGraphicsSceneManager = DirectCast(root.CurrentScenario, IAgScenario).SceneManager
Dim philadelphia As Array = New Object() {39.88, -75.253000.0}
Dim washingtonDC As Array = New Object() {38.85, -77.043000.0}

Dim positions As Array = New Object(5) {}
philadelphia.CopyTo(positions, 0)
washingtonDC.CopyTo(positions, 3)

Dim line As IAgStkGraphicsPolylinePrimitive = manager.Initializers.PolylinePrimitive.Initialize()
'$planetName$Name of the planet to place primitive$
line.SetCartographic("Earth", positions)
manager.Primitives.Add(DirectCast(line, IAgStkGraphicsPrimitive))


Draw a rhumb line on the globe

[Visual Basic .NET] Copy Code
' IAgStkGraphicsScene scene: Current Scene
' AgStkObjectRoot root: STK Object Model root

Dim manager As IAgStkGraphicsSceneManager = DirectCast(root.CurrentScenario, IAgScenario).SceneManager
Dim newOrleans As Array = New Object() {29.98, -90.250.0}
Dim sanJose As Array = New Object() {37.37, -121.920.0}

Dim positions As Array = New Object(5) {}
newOrleans.CopyTo(positions, 0)
sanJose.CopyTo(positions, 3)

Dim interpolator As IAgStkGraphicsPositionInterpolator = TryCast(manager.Initializers.RhumbLineInterpolator.Initialize(), IAgStkGraphicsPositionInterpolator)
Dim line As IAgStkGraphicsPolylinePrimitive = manager.Initializers.PolylinePrimitive.InitializeWithInterpolator(interpolator)
line.SetCartographic("Earth", positions)
manager.Primitives.Add(DirectCast(line, IAgStkGraphicsPrimitive))


Draw a STK area target outline on the globe

[Visual Basic .NET] Copy Code
' IAgStkGraphicsScene scene: Current Scene
' AgStkObjectRoot root: STK Object Model root
' Array positions: The area target positions

Dim manager As IAgStkGraphicsSceneManager = DirectCast(root.CurrentScenario, IAgScenario).SceneManager

Dim line As IAgStkGraphicsPolylinePrimitive = manager.Initializers.PolylinePrimitive.Initialize()

line.Set(positions)
line.Width = 2
DirectCast(line, IAgStkGraphicsPrimitive).Color = Color.Yellow
line.DisplayOutline = True
line.OutlineWidth = 2
line.OutlineColor = Color.Black

manager.Primitives.Add(DirectCast(line, IAgStkGraphicsPrimitive))


Draw the outline of a circle on the globe

[Visual Basic .NET] Copy Code
' IAgStkGraphicsScene scene: Current Scene
' AgStkObjectRoot root: STK Object Model root

Dim manager As IAgStkGraphicsSceneManager = DirectCast(root.CurrentScenario, IAgScenario).SceneManager
Dim philadelphia As Array = New Object() {39.88, -75.250.0}

Dim shape As IAgStkGraphicsSurfaceShapesResult = manager.Initializers.SurfaceShapes.ComputeCircleCartographic("Earth", philadelphia, 10000)
Dim positions As Array = shape.Positions

Dim line As IAgStkGraphicsPolylinePrimitive = manager.Initializers.PolylinePrimitive.InitializeWithType(shape.PolylineType)
line.Set(positions)
line.Width = 2
DirectCast(line, IAgStkGraphicsPrimitive).Color = Color.White

manager.Primitives.Add(DirectCast(line, IAgStkGraphicsPrimitive))


Draw the outline of an ellipse on the globe

[Visual Basic .NET] Copy Code
' IAgStkGraphicsScene scene: Current Scene
' AgStkObjectRoot root: STK Object Model root

Dim manager As IAgStkGraphicsSceneManager = DirectCast(root.CurrentScenario, IAgScenario).SceneManager
Dim washingtonDC As Array = New Object() {38.85, -77.043000.0}

Dim shape As IAgStkGraphicsSurfaceShapesResult = manager.Initializers.SurfaceShapes.ComputeEllipseCartographic("Earth", washingtonDC, 450003000045)
Dim positions As Array = shape.Positions

Dim line As IAgStkGraphicsPolylinePrimitive = manager.Initializers.PolylinePrimitive.InitializeWithType(shape.PolylineType)
line.Set(positions)
DirectCast(line, IAgStkGraphicsPrimitive).Color = Color.Cyan

manager.Primitives.Add(DirectCast(line, IAgStkGraphicsPrimitive))


Shows the format of the Positions parameter when updating a polyline primitive with cartographic positions.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsPolylinePrimitive polyline: A polyline primitive

Dim positions As Array = New Object() {39.88, -75.25038.85, -77.040_
     29.98, -90.25037.37, -121.920}

polyline.SetSubsetCartographic("Earth", positions, 12)


Shows the format of the Positions parameter when updating a polyline primitive.

[Visual Basic .NET] Copy Code
' IAgStkGraphicsPolylinePrimitive polyline: A polyline primitive

Dim positions As Array = New Object() {1247.87, -4739.744067.771115.48, -4847.093979.36_
     -24.12, -5529.313168.45, -2683.42, -4307.743850.11}

polyline.SetSubset(positions, 12)


Shows the format of the Positions, Colors and Indices parameters when updating a polyline primitive with cartographic positions.

[Visual Basic .NET] Copy Code