
-- PROGRAMMER'S MANUAL --

-- Description of the source code ----------------------------------------------

All source files of the simulator are located in the folder "Source".

To modify the source code of the simulator, open the project file "Moon.vbp" with Microsoft Visual Basic 6.

To modify the DLL, extract the ZIP files in the same folder and open the project file "Moon.dsp" with Microsoft Visual C++ 6. The simulator uses this DLL because there are a few functions that can not be run from the EXE due to the limitations of VB6 and also to integrate the chemical simulator CPROPEP that is programmed in C.

The calculation engine and the graphics engine are located in the file "Sys.bas", the code that controls the main window is in the file "Main.frm" and the panels are each in their own file ".frm" with the name of the panel. There are also some files with the data necessary for the simulation and graphics engine, grouped in folders and are described below.

-- Description of the main functions -------------------------------------------

In the file "Sys.bas" are located all the important functions of the simulator, but the main ones are these:

1. "InitApp" runs when the simulator starts. It loads the panels, the simulator configuration and the mission by default, and initializes the application.

2. "CleanUpApp" runs when the simulator is closed. It unloads all the panels and ends all the processes that were ongoing.

3. "Init" is executed at the beginning of each simulation and restarts the simulator variables with all the parameters specified for the mission in the Setup and Stages panel. Also initializes the variables of the planets and their position is calculated according to the selected launching date.

4. "Stats" updates all the state variables of the simulation, such as static temperature, distance and gravity of the planets, the detection of the ground, etc. It is automatically called from "Init" after initializing the simulation and from "Nav" every iteration of the calculation main loop. It is also called from "LoadSnap" to reconstruct the state of the simulation variables from the snapshot previously saved with function "SaveSnap".

5. "Nav" is the main loop of the simulation. When entering this function, the simulation does not stop until the user press the "Pause" button, until an "auto-pause" event is fired or until the spacecraft lands or crashes on a planet.

6. "Render" controls the OpenGL 3D presentation. It runs "RenderEx" twice, one for the main window and another one for the View panel, to avoid duplicating code. It is called from "Nav" every few iterations of the loop, depending on the simulation speed selected by the user. If the simulation is paused, it is called by all the functions that modify the position of the camera.

-- "InitApp" - Starting the application ----------------------------------------

The starting sequence of the simulator is:

- Main window "Main" is loaded and in the "Form_Load" event, the function "InitApp" is called.

- "InitApp" checks if data folders exist and if not they are created.

- All panels are loaded to be initialized, resulting in an event "Form_Load" for each of them.

- "LoadConfig" loads the simulator configuration file "Moon.ini".

- "LoadPreset" loads the default mission located in "Presets/Default.ini".

- It loads all the data necessary for simulation: the thrust curves, the ENG type engines, the propellants, the locations, teh drag coefficient curves, the list of the stars, the atmosphere curves, the radio stations and the list of the sensors.

- OpenGL is initialized, if it fails then GDI is used in 2D mode, for compatibility with older computers.

- "Init" is called to initialize the default mission previously loaded and from there it runs "Render" to display the simulation with OpenGL.

- It shows all auxiliary panels according to the previously loaded settings from "Moon.ini"

- Finally, it hides the splash window

From here the simulator is in "pause" mode, waiting for the user to load a mission or start the simulation with the "play" button. When the user starts the simulation, the function "Nav" is called, which does not return until the simulation changes to "pause" mode.

-- "CleanUpApp" - Terminating the application ----------------------------------

When the application is closed:

- The event "Form_Unload" in the main window "Main" is fired and it calls the function "CleanUpApp".

- "CleanUpApp" stops the simulation loop if it is running.

- It stops the video recording.

- It closes the connection to the external control device and the GPS.

- It closes the OpenGL library and the chemical simulator CPROPEP.

- It saves the simulator settings, the current mission and the propellants.

- Then, the auxiliary panels are unloaded.

-- "Nav" - Simulator calculation engine ----------------------------------------

The calculation engine of the simulation is located in the function "Nav" and it works this way:

- To control the status of the simulation use the global variable "Play". While the simulation is running, it contains the value "Active" and when it is stopped the value "Paused". To stop the simulation at any time, simply assign "Play = Paused" and then function when detects the change in the variable exits the simulation loop and returns. The function itself can also automatically stop the simulation if an "auto-pause" event specified by the user is fired or if the spacecraft lands or crashes on a planet.

- The simulator uses the global variable "Status" to know at what stage of the mission is. This variable controls the parts of the simulation loop that refer to the control of the spacecraft.

- Before entering the loop, it calculates the number of iterations to be executed without passing control to the user, depending on the selected simulation speed. This is done this way to use as much CPU as possible at high simulation speeds, at cost of a loss of response in the graphic interface. Each loop iteration, the time variable is increased by the value specified in the Setup panel, which by default is 50ms. If you selected "Simulation->Adaptive step", the time step is automatically multiplied by 10 when the spacecraft go more than one radius away from the planet and by 100 when it goes out into interplanetary space. This way the simulation speed can be increased without losing much accuracy in the calculation.

- In "Test stations visibility", "Path points" and "Graph points" sections, once per second then simulation checks the radio stations visibility, saves the spacecraft's position to display the path and saves the state of the variables used in Graph panel. It is done this way because they are less important parts of the simulation, so they not use much CPU.

- In "External link control" section, if the connection to the external device specified in the Link panel is active, it passes the state variables to the external device and is expected to command response. If it comes, it will keep the control variables for later use instead of the control algorithm of the simulator.

- From here you enter "Phase selection" section, the control algorithm of the spacecraft. In the statement "Select Case", depending on the state of the global variable "Status" is excuted a specific section for each phase of the simulation. The phases are these:

1. "Case Launch". This is the starting phase sequence. If the selected abort stage is 0, it means that the sequence is already aborted and it jumps to "Abort". If not, it changes the phase to "TakeOff" and jumps to "StartEngine".

2. "Case TakeOff". This is the launch phase. If the engine is off it means that the spacecraft is in the transition phase between stages. It checks if the waiting time elapsed between stages has passed and if so, if the stage has not spent all the fuel, it means that it is waiting in a parking orbit and it restarts the engine without changing the phase. If not, it changes to the next stage and if this is not the last, it starts the engine. If there are no more stages, depending on whether there is a "Hover" stage or not, it changes to "Transfer" or "Satellite" phase. Then, if the external device control is enabled, it is applied to the spacecraft. If not, it calculates the angle of elevation of the spacecraft as a function of the specified parameters of the launch trajectory and it applies the correction thrust.

3. "Case Transfer". This is the transition phase between the Earth and the target planet should have specified a "Hover" stage. If the braking distance is not specified, it is estimated. It checks if the stopping distance has been overcome and if so, it starts the engine to start the landing sequence and passes to the "Landing" phase.

4. "Case Landing". This is the braking phase to land on the target planet. If the external device control is enabled, it is applied to the spacecraft. If not, it guides the spacecraft into the opposite direction of the relative velocity vector to the planet. If the engine is off means that the spacecraft is waiting in a parking orbit and checks if the specified time has elapsed. If so, it starts the engine and if the time is negative, it changes to "Revert" phase. If not, it adjusts the engine thrust for a soft landing.

5. "Case Revert". This phase is used to return to Earth after waiting in a parking orbit around the target planet. It aligns the spacecraft with the relative velocity vector to the planet to get away from it. When the "Hover" stage runs out of fuel, it passes to "StandBy" phase.

6. "Case Satellite". This phase is used to control the satellite once deployed. If the external device control is enabled, it is applied to the satellite. If not, if there is any visible ground station, it applies the correction thrust for the satellite to look at it. If not, it looks to the ground or to the planet specified in the "LookAt" mode of the Sensor window, if any.

7. "Case StandBy". This is the phase used to return to Earth after orbiting the target planet. As there is no more fuel, nothing is done.

8. "Case Aborted". This phase is used when the spacecraft's control sequence has been aborted so nothing is done.

- Once the spacecraft's control phase is done, it continues with the rest of calculations common to all phases.

- In "Engine thrust" section it is calculated everything related to engine thrust. If the engine is on, should be a stage with power curve, it gets the thrust from the point of the curve as a function of time. With this value, the fuel consumption is calculated and the mass of fuel spent is subtracted from the spacecraft's mass. If it detects that it has run out of fuel, the engine stops. If the spacecraft did not take off, it checks if there is sufficient thrust for takeoff. If not, it skips to "NoGravity" to simulate the contact with the ground and avoid the effect of gravity. Next, it calculates the acceleration due to the engine thrust and also various data related to the thrust: the thrust Delta-V achieved, the total impulse and the Delta-V lost because of gravity.

- In "Air drag and lift" section it is calculated everything related to the atmosphere of the nearest planet. It is only used if the air density calculated by the function "Stats" is greater than zero. This only happens when the spacecraft is less than 500km from the surface of the Earth or Mars. First, it calculates the air drag based on the front surface, the drag coefficient and the velocity relative to the air. It is applied on the spacecraft and it calculates the Delta-V lost due to the air drag. Next, it calculates the angle of attack between the spacecraft and the air and using this value it calculates the air lift and it is applied also to the spacecraft using the lift / drag factor or LD specified in the Stages panel. It also calculates the Delta-V won by the air lift.

- In "Gravity and Kinetics" section it is calculated everything related to the gravity of the planets. Depending on the state of gravity options in the "Simulation" menu, it calculates the gravity of the Earth, the Moon, the Sun and the other planets in the Solar System and it is applied to the spacecraft. Then, it calculates the acceleration, velocity and position of all the planets to keep them orbiting around the Sun. Finally, it applies the acceleration on the spacecraft.

- In "Time step" section, the simulation time variable is increased.

- In "Auxiliary variables" section, it saves the last vertical height and speed respect to all the planets to detect the apoapsis and the periapsis. Then it calls the function "Stats" to update all the variables related to the state of the simulation.

- The last part "Statistics" is only used if the option "Simulation->Statistics" is selected. This way the simulation speed can be increased if the are not needed. The only part of the simulation that needs them is the part that use parking orbits. In that case it needs to know if the orbital velocity is reached in order to stop the engine and keep the spacecraft in standby.

- Next, it calculates the maximum and minimum altitude over the Earth and the Moon and the maximum and minimum velocity relative to Earth. Also it is calculated the maximum acceleration felt by the spacecraft to check if it is under the limits.

- Then, it calculates if any events have fired. If so, they will be written to the Log panel or it will save a snapshot or stop the simulation so the user can observe carefully the situation in which they occur. Events related to the Earth and the Moon are always calculated, but the events related to the Sun and other planets are only calculated if the option "Simulation->All planets gravity" is selected, to speed the simulation when they are not used. Everything related to events is controlled in function "Msg".

- Finally, it checks all the events related to the engine or the change of the stages and the detection of the spacecraft landing and take off.

- This is the end of the main loop and it decreases the counter of iterations. When it reaches zero, it exits the loop to transfer control to the graphic interface allowing the user to control the main window and the panels.

- Then it calls the functions "Render", "Info" and "Plot" to update the OpenGL viewer, the data in the Data panel and the graphic in the Graph panel. If video recording is activated, it calls the "RecordVideo" function to capture the screen and save the frame in the video file.

- If the control variable of the simulation "Play" is in "Active" it returns to the beginning of the loop to continue with the simulation. If not, it checks if a restart is required with "Reset" or "Restart" values. If so, it calls the function "Init" and restarts the simulation.

- If "Play" is in "Pause" it stops the simulations and exits the function.

-- Description of all the files and folders of the simulator -------------------

Moon.exe		Simulator executable file
Moon.dll		Special routines that can not be compiled in VB6
Moon.ini		Configuration of the simulation, the graphics engine and panels
Moon.pdf		User manual
License.txt		Licensing

Data			Folder for various simulation data
			*.cd  - drag coefficient curves (CD)
			*.air - atmospheric density, pressure and temperature curves
Cube.cd			CD curve "Cube"
Earth.air		Earth atmosphere curve
Mars.air		Mars atmosphere curve
Round Nose.cd		CD curve "Round Nose"
Sharp Nose.cd		CD curve "Sharp Nose"
Sphere.cd		CD curve "Sphere"
Stars.lst		List of the position and magnitude of the stars and galaxies
Wing.cd			CD curve "Wing"

Engines			Folder with the list of engines and thrust curves
			*.eng - definition and thrust curve of the engine type .ENG
			*.cur - simulator generic thrust curve
AT-J99.eng		ENG engine type "AT-J99"
AT-N1000.eng		ENG engine type "AT-N1000"
Circular Bore.cur	Thrust curve "Circular Bore"
C-Slot.cur		Thrust curve "C-Slot"
Finocyl 5-Star.cur	Thrust curve "Finocyl 5-Star"
Moon Burner.cur		Thrust curve "Moon Burner"
Rod and Tube.cur	Thrust curve "Rod and Tube"

Images			Folder with image files
Crosshair.bmp		Crosshair used in the camera mode "Follow mode->Onboard"
Flare.bmp		Sun flare
Logo.bmp		Logo that appears in the upper-right corner
Moon.ico		32-bit icon for the executable
Splash.jpg		Image for the splash window

Locations		Folder with custom locations
Locations.lst		List of locations

Logs			Folder where the event logs from the Log panel are saved

Models			Folder for custom 3D models in .COB format

Paths			Folder where the paths are saved

Presets			Folder where the missions are saved
			DS*   - missions to planets in the Solar System
			LEO*  - missions to low Earth orbit
			Moon* - missions to the Moon
			SOF*  - sub-orbital flights to cities on Earth
			*.Kml - flight path to the launch point of the mission
Default.ini		File where the current mission is saved on exit 
DS Jupiter.ini		Journey to Jupiter
DS Mars Lander.ini	Journey to Mars with landing sequence
DS Mars Minimal.ini	Journey to Mars with landing sequence using minimal fuel
DS Mars.ini		Journey to Mars
DS Mercury.ini		Journey to Mercury
DS Neptune.ini		Journey to Neptune using Jupiter's gravity assist
DS Pluto.ini		Journey to Pluto using Jupiter's gravity assist
DS Saturn.ini		Journey to Saturn
DS Sun.ini		Journey to the Sun
DS Uranus.ini		Journey to Uranus using Jupiter's gravity assist
DS Venus.ini		Journey to Venus
LEO 3 Stages.ini		LEO orbit using 3 stages
LEO AeroTech.ini		Sub-orbital flight using AeroTech engines
LEO N-Prize Balloon 4 Worst.ini	Sub-orbital flight using inefficient fuel
LEO N-Prize Balloon 4 Worst.kml	Flight path of the balloon used to reach the launch point
LEO N-Prize Balloon 4.ini	LEO orbit for the N-Prize using a balloon
LEO N-Prize Balloon 4A.ini	LEO orbit for the N-Prize using a balloon
LEO N-Prize Balloon.ini		LEO orbit for the N-Prize using a balloon
LEO N-Prize.ini			LEO orbit for the N-Prize
LEO Polar Sync.ini		LEO polar orbit aligned with the meridians
LEO Polar.ini			LEO polar orbit
LEO Short.ini			LEO low orbit of 200km and 3-day duration
LEO Terrain.ini			LEO orbit using elevation data for the launch site
Moon 3 Stages.ini	Journey to the Moon using 3 stages
Moon Apollo.ini		Journey to the Moon landing on the same place as the Apollo XI
Moon Balloon.ini	Journey to the Moon using a balloon
Moon Cannon.ini		Journey to the Moon using a ground cannon
Moon Direct Polar.ini	Journey to the Moon passing over the North Pole
Moon Direct.ini		Journey to the Moon using a linear trajectory
Moon Fast.ini		Journey to the Moon in 1.5 days
Moon Minimal.ini	Journey to the Moon without the laser altimeter mass
Moon Park High.ini	Journey to the Moon from a higher latitude
Moon Park Lunar.ini	Journey to the Moon using parking orbits in Earth and Moon
Moon Park Polar.ini	Journey to the Moon using a polar parking orbit in Earth
Moon Park Return.ini	Journey to the Moon using parking orbits and returning to Earth
Moon Park Short.ini	Journey to the Moon using a parking orbit when the Moon is nearer
Moon Park.ini		Journey to the Moon using a parking orbit in Earth
Moon Polar.ini		Journey to the Moon using a polar trajectory
Moon Record.ini		Journey to the Moon using the best fuel possible
Moon Slow.ini		Journey to the Moon in 5 days
Moon Terrain.ini	Journey to the Moon using elevation data for the launch site
SOF Madrid.ini		Sub-orbital flight to Madrid
SOF Moscow.ini		Sub-orbital flight to Moscow
SOF NewYork.ini		Sub-orbital flight to New York
SOF Paris.ini		Sub-orbital flight to Paris
SOF Sydney Mini.ini	Sub-orbital flight to Sydney for a single passenger
SOF Sydney.ini		Sub-orbital flight to Sydney

Propellants		Folder with propellants
Propellant.dat		Components list for the chemical simulator CPROPEP
Propellants.lst		List of custom propellants for the Propellant editor panel
Thermo.dat		Properties of components for the chemical simulator CPROPEP

Sensors			Folder with the list of sensors
Sensors.lst		List of sensors

Source			Folder with source files
Arduino			Sub-folder with examples of Arduino programs for the MCU
Cpp.c			Source code of the chemical simulator CPROPEP for the DLL
CProPEP.zip		Original source code in C of the chemical simulator CPROPEP
Data.frm		Source code of the Data panel
Data.frx		Resources of the Data panel
Editor.frm		Source code of the Propellant editor panel
Editor.frx		Resources of the Propellant editor panel
Gl.cpp			Source code of the OpenGL functions for the DLL 
Graph.frm		Source code of the Graph panel
Graph.frx		Resources of the Graph panel
Help.frm		Source code of the Help panel
Help.frx		Resources of the Help panel
Icon.ctl		Source code of the IconEx control for the Toolbar
Info.txt		Information and data of planets
Intro.frm		Source code of the splash window
Intro.frx		Resources of the splash window
Link.frm		Source code of the Link panel
Link.frx		Resources of the Link panel
Log.frm			Source code of the Log panel
Log.frx			Resources of the Log panel
Main.frm		Source code of the main window
Main.frx		Resources of the main window
Moon.vbp		Visual Basic 6 project file
Moon.vbw		Visual Basic 6 project settings
Note.frm		Source code of the message window
Note.frx		Resources of the message window
Preset.frm		Source code of the Preset panel
Preset.frx		Resources of the Preset panel
Setup.frm		Source code of the Setup panel
Setup.frx		Resources of the Setup panel
Stages.frm		Source of the Stages panel
Stages.frx		Resources of the Stages panel
Sys.bas			Source of the calculation and graphics engines
ToolBar.frm		Source code of the Toolbar
ToolBar.frx		Resources of the Toolbar
View.frm		Source code of the View panel
View.frx		Resources of the View panel

Stations		Folder with the list of the ground stations
Stations.csv		List of the ground stations

Terrain			Folder for files with the elevation data (optional)
Geoid.bin		Goeid elevation data with a resolution of 2.5'
Mars.bin		Mars elevation data with a resolution of 3.75'
Moon.bin		Moon elevation data with a resolution of 3.75'
Terrain.bin		Earth elevation data with a resolution of 30''

Textures		Folder with the textures of the planets for the OpenGL viewer
			*.bmp - uncompressed textures
			*.dds - compressed, high-resolution textures (optional)
Earth.bmp		Texture for the Earth
Jupiter.bmp		Texture for Jupiter
Mars.bmp		Texture for Mars
Mercury.bmp		Texture for Mercury
Moon.bmp		Texture for the Moon
Neptune.bmp		Texture for Neptune
Pluto.bmp		Texture for Pluto
Saturn.bmp		Texture for Saturn
Sun.bmp			Texture for the Sun
Uranus.bmp		Texture for Uranus
Venus.bmp		Texture for Venus

Toolbar			Folder with icons for the toolbar
AddPath.ico		Icon for button "Save path"
Arrow.ico		Icon with overlay arrow for buttons with drop-down menu
AutoPause.ico		Icon for button "Auto pause events"
AutoSave.ico		Icon for button "Auto save events"
DelPath.ico		Icon for button "Delete path"
Exit.ico		Icon for button "Exit application"
FollowTo.ico		Icon for button "Follow mode"
Help.ico		Icon for button "Show help"
LogEvents.ico		Icon for button "Log events"
LookAt.ico		Icon for button "Look at target"
NextPath.ico		Icon for button "Next path"
NextSnap.ico		Icon for button "Next snapshot"
Options.ico		Icon for button "Options"
Panels.ico		Icon for button "Show or hide panels"
Paths.ico		Icon for button "Paths"
Pause.ico		Icon for button "Pause simulation"
Play.ico		Icon for button "Resume simulation"
Presets.ico		Icon for button "Presets"
PrevPath.ico		Icon for button "Previous path"
PrevSnap.ico		Icon for button "Previous snapshot"
Record.ico		Icon for button "Start video recording"
RelativeTo.ico		Icon for button "Points relative to"
Reset.ico		Icon for button "Reset simulation"
SaveSnap.ico		Icon for button "Save snapshot"
Simulation.ico		Icon for button "Simulation options"
SpeedDown.ico		Icon for button "Slow down simulation"
SpeedUp.ico		Icon for button "Speed up simulation"
StepDown.ico		Icon for button "Decrease time step"
StepUp.ico		Icon for button "Increase time step"
Stop.ico		Icon for button "Stop video recording"
Tools.ico		Icon for button "Render tools"

Videos			Folder where the videos and screenshots are saved
