CSharpStandalone_24_nsc_detectors
Last update: 17.07.2025using System;
using ZOSAPI;
using ZOSAPI.Editors.NCE;
namespace CSharpStandaloneApplication
{
class Program
{
static void Main(string[] args)
{
// Find the installed version of OpticStudio
bool isInitialized = ZOSAPI_NetHelper.ZOSAPI_Initializer.Initialize();
// Note -- uncomment the following line to use a custom initialization path
//bool isInitialized = ZOSAPI_NetHelper.ZOSAPI_Initializer.Initialize(@"C:\Program Files\OpticStudio\");
if (isInitialized)
{
LogInfo("Found OpticStudio at: " + ZOSAPI_NetHelper.ZOSAPI_Initializer.GetZemaxDirectory());
}
else
{
HandleError("Failed to locate OpticStudio!");
return;
}
BeginStandaloneApplication();
}
static void BeginStandaloneApplication()
{
// Create the initial connection class
// Attempt to create a Standalone connection
if (TheApplication == null)
{
HandleError("An unknown connection error occurred!");
return;
}
// Check the connection status
{
return;
}
{
HandleError("User plugin was started in the wrong mode: expected Server, found " + TheApplication.Mode.ToString());
return;
}
// creates new directory
System.IO.Directory.CreateDirectory(strPath);
// Set up primary optical system
string sampleDir = TheApplication.SamplesDir;
// Initializes NCE and loads surfaces
// Inserts objects
// Gets reference to specific object
INCERow o2 = TheNCE.GetObjectAt(2);
INCERow o3 = TheNCE.GetObjectAt(3);
INCERow o4 = TheNCE.GetObjectAt(4);
INCERow o5 = TheNCE.GetObjectAt(5);
// Changes Object Type
TheNCE.GetObjectAt(1).ChangeType(o1.GetObjectTypeSettings(ZOSAPI.Editors.NCE.ObjectType.SourceEllipse));
// Sets positions & materials
o3.YPosition = 1.5;
o3.ZPosition = 8.99;
o3.Material = "N-BK7";
o4.ZPosition = 10;
o5.RefObject = 4;
o5.ZPosition = 1e-3;
// Sets layout rays based on parameter number
// Sets analysis rays based on object data column
ZOSAPI.Editors.NCE.IObjectSourceEllipse sourcedata = o1.ObjectData as ZOSAPI.Editors.NCE.IObjectSourceEllipse;
sourcedata.NumberOfAnalysisRays = (int)1E6;
double o5_x = 10.0;
double o5_y = 12.23;
// Changes face type and coating properties
TheNCE.GetObjectAt(3).CoatScatterData.GetFaceData(0).FaceIs = ZOSAPI.Editors.NCE.FaceIsType.Absorbing;
TheNCE.GetObjectAt(3).CoatScatterData.GetFaceData(1).FaceIs = ZOSAPI.Editors.NCE.FaceIsType.ObjectDefault;
// changes scatter profile on face
ZOSAPI.Editors.NCE.IObjectScatteringSettings o3_Scatter = TheNCE.GetObjectAt(3).CoatScatterData.GetFaceData(2).CreateScatterModelSettings(ZOSAPI.Editors.NCE.ObjectScatteringTypes.Lambertian);
o3_Scatter._S_Lambertian.ScatterFraction = 0.5;
// Removes pixel interpolation for the detector
o4.TypeData.UsePixelInterpolation = false;
// Setup and run the ray trace
NSCRayTrace.SplitNSCRays = false;
NSCRayTrace.ScatterNSCRays = true;
NSCRayTrace.UsePolarization = false;
NSCRayTrace.IgnoreErrors = true;
NSCRayTrace.SaveRays = false;
NSCRayTrace.ClearDetectors(0);
NSCRayTrace.RunAndWaitForCompletion();
NSCRayTrace.Close();
// Reads in values from NCE for detector settings
int obj = 4;
double x_half = TheSystem.NCE.GetObjectAt(obj).GetObjectCell(ZOSAPI.Editors.NCE.ObjectColumn.Par1).DoubleValue;
double y_half = TheSystem.NCE.GetObjectAt(obj).GetObjectCell(ZOSAPI.Editors.NCE.ObjectColumn.Par2).DoubleValue;
double x_pixels = (double)TheSystem.NCE.GetObjectAt(obj).GetObjectCell(ZOSAPI.Editors.NCE.ObjectColumn.Par3).IntegerValue;
double y_pixels = (double)TheSystem.NCE.GetObjectAt(obj).GetObjectCell(ZOSAPI.Editors.NCE.ObjectColumn.Par4).IntegerValue;
// Creates a new detector viewer analysis reference
ZOSAPI.Analysis.IA_ d4 = TheSystem.Analyses.New_Analysis(ZOSAPI.Analysis.AnalysisIDM.DetectorViewer);
ZOSAPI.Analysis.Settings.RayTracing.IAS_DetectorViewer d4_settings = d4.GetSettings() as ZOSAPI.Analysis.Settings.RayTracing.IAS_DetectorViewer;
ZOSAPI.Analysis.Data.IAR_DataGridRgb d4_raw = d4_Results.GetDataGridRgb(0) as ZOSAPI.Analysis.Data.IAR_DataGridRgb;
// Creates System.Single[] buffers to store pixel data
// Required any time Interface Documentation shows a Single[] or Double[] output
Single[] rData = new Single[(int)(x_pixels * y_pixels)];
Single[] gData = new Single[(int)(x_pixels * y_pixels)];
Single[] bData = new Single[(int)(x_pixels * y_pixels)];
// Reads values from detector color raw data
// Prints RGB data into single file
d4_raw.FillValues((uint)(x_pixels * y_pixels), rData, gData, bData);
System.Text.StringBuilder sbReport = new System.Text.StringBuilder();
sbReport.Append(string.Concat("Red: ", string.Join(", ", rData), "\nGreen: ", string.Join(", ", gData), "\nBlue: ", string.Join(", ", bData)));
string resFile = TheApplication.SamplesDir + "\\API\\CS\\e24_nsc_detector_rgb.txt";
System.IO.File.WriteAllText(resFile, sbReport.ToString());
// Changes default values for Detector Viewer
// Plots the Incoherent Irradiance in False Color
ZOSAPI.Analysis.IA_ d5 = TheSystem.Analyses.New_Analysis(ZOSAPI.Analysis.AnalysisIDM.DetectorViewer);
ZOSAPI.Analysis.Settings.RayTracing.IAS_DetectorViewer d5_set = d5.GetSettings() as ZOSAPI.Analysis.Settings.RayTracing.IAS_DetectorViewer;
d5_set.Detector.SetDetectorNumber(5);
ZOSAPI.Analysis.Data.IAR_ d5_results = d5.GetResults();
sbReport.Clear();
double max_value = 0.0;
for (int i = 0; i < d5_values.GetLength(0); i++)
{
for (int j = 0; j < d5_values.GetLength(1); j++)
{
if (d5_values[i, j] > max_value) max_value = d5_values[i, j];
sbReport.Append(d5_values[i, j] + "\t");
}
sbReport.AppendLine("");
}
resFile = TheApplication.SamplesDir + "\\API\\CS\\e24_nsc_detector_falsecolor.txt";
System.IO.File.WriteAllText(resFile, sbReport.ToString());
Console.WriteLine("The max value is {0:F2}", max_value);
// Saves current system in memory
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
// Clean up
FinishStandaloneApplication(TheApplication);
}
{
// Note - TheApplication will close automatically when this application exits, so this isn't strictly necessary in most cases
if (TheApplication != null)
{
TheApplication.CloseApplication();
}
}
static void LogInfo(string message)
{
// TODO - add custom logging
Console.WriteLine(message);
}
static void HandleError(string errorMessage)
{
// TODO - add custom error handling
throw new Exception(errorMessage);
}
}
}
Definition: ZemaxService.cs:198
IZOSAPI_Application CreateNewApplication()
Attempts to launch a new instance of Optic Studio in 'headless' mode. Note that although the Optic St...
Definition: ZemaxService.cs:863
Definition: IAR_Base.cs:286
void FillValues(uint fullSize, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)][In][Out]float[] rData, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)][In][Out]float[] gData, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)][In][Out]float[] bData)
Retries all RGB data at once, into the specified buffers.
Properties and methods for retrieving analysis window data. This interface can be accessed via the IA...
Definition: IAR_Base.cs:21
IAR_DataGridRgb GetDataGridRgb(int index)
IAR_DataGrid GetDataGrid(int index)
Base interface for all analysis windows. This interface can be accessed via the I_Analyses interface.
Definition: IA_Base.cs:29
IAR_ GetResults()
Gets the result data (if available) for the current analysis.
IMessage ApplyAndWaitForCompletion()
Re-runs the analysis with the current settings and waits for it to finish calculating.
IMessage SetDetectorNumber(int N)
Definition: IAS_DetectorViewer.cs:23
IAS_Detector Detector
Definition: IAS_DetectorViewer.cs:25
double DoubleValue
Gets or sets the double precision value of this cell. Note that if DataType is not CellDataType....
Definition: InterfacesEditors.cs:340
int IntegerValue
Gets or sets the integer value of this cell. Note that if DataType is not CellDataType....
Definition: InterfacesEditors.cs:319
INCECoatScatterFaceData GetFaceData(int faceNumber)
Gets coat/scatter data for the specified face (0 to NumberOfFaces-1).
int NumberOfRays
Definition: InterfacesNCE.cs:6306
bool ChangeScatterModelSettings(IObjectScatteringSettings newSettings)
IObjectScatteringSettings CreateScatterModelSettings(ObjectScatteringTypes type)
All data for a Non-Sequential Component Editor object. This interface can be accessed via the INonSeq...
Definition: InterfacesNCE.cs:1198
INCECoatScatterData CoatScatterData
Gets the object Coat/Scatter data.
Definition: InterfacesNCE.cs:1355
bool ChangeType(IObjectTypeSettings settings)
Changes the current object to the specified type. Use GetObjectTypeSettings to get the relevant setti...
IEditorCell GetObjectCell(ObjectColumn Col)
Gets the specified object cell data.
IObjectTypeSettings GetObjectTypeSettings(ObjectType type)
Create the settings for the specified type. Use this method to specify any extra data required to cha...
This interface defines all properties and methods needed to interact with the Non-Sequential Componen...
Definition: InterfacesNCE.cs:363
INCERow GetObjectAt(int ObjectNumber)
Gets the object at the specified position.
INCERow InsertNewObjectAt(int ObjectNumber)
Inserts a new object at the specified position.
Scatter model settings for a specific face. This interface can be accessed via the INCECoatScatterFac...
Definition: InterfacesNCE.cs:6323
Definition: InterfacesNCE.cs:4809
Represent a complete optical system. A IOpticalSystem corresponds to a single .ZMX file....
Definition: Interfaces.cs:690
void SaveAs(string fileName)
Saves the current system to the specified file. All future calls to Save will use the same file.
ISystemData SystemData
Data for configuring everything in the System Explorer.
Definition: Interfaces.cs:848
I_Analyses Analyses
Gets the analyses for the current system.
Definition: Interfaces.cs:928
INonSeqEditor NCE
Gets the non-sequential component editor.
Definition: Interfaces.cs:887
IOpticalSystemTools Tools
Gets an interface used to run various tools on the optical system.
Definition: Interfaces.cs:935
This interface contains all information about the current ZOS-API connection, as well as methods for ...
Definition: Interfaces.cs:264
IOpticalSystem CreateNewSystem(SystemType mode)
Creates a new empty optical system, in the specified mode.
bool IsValidLicenseForAPI
Gets a value indicating whether this the API is currently useable.
Definition: Interfaces.cs:290
ZOSAPI_Mode Mode
Gets the current connetion mode. Use this to check if Optic Studio is expecting a user operand / anal...
Definition: Interfaces.cs:309
LicenseStatusType LicenseStatus
Gets the license status. Note that this displays the license edition if successful,...
Definition: Interfaces.cs:283
void CloseApplication()
Shut down the Optic Studio process.
IOpticalSystem PrimarySystem
Gets the primary system. When Mode is ZOSAPI_Mode.Server, this will initially be an empty sequential ...
Definition: Interfaces.cs:331
string SamplesDir
Gets the full path for the current user's samples directory (in the My Documents\Zemax\Samples\ folde...
Definition: Interfaces.cs:508
bool RunAndWaitForCompletion()
Sames as calling Run followed by WaitForCompletion.
Interfaces and methods for running a non-sequential ray trace. This interface can be accessed via the...
Definition: RayTrace.cs:45
ErrorType ClearDetectors(int DetectorNumber)
Clears the specified detectors.
Definition: IAR_Base.cs:11
Definition: IAS_DetectorViewer.cs:6
Definition: IAS_FieldCurvatureAndDistortion.cs:5
Definition: IAS_FieldCurvatureAndDistortion.cs:5
Definition: InterfacesNCE.cs:19
Definition: InterfacesEditors.cs:12
The ZOSAPI namespace contains classes for initially connecting to zemax. See also ZOSAPI_Connection,...
Definition: IAS_FieldCurvatureAndDistortion.cs:5