Sub-Orbital Flight#
This introductory tutorial uses kRPC to send some Kerbals on a sub-orbital flight, and return them safely to Kerbin. It covers the following topics:
Controlling a rocket, by activating stages and setting the throttle
Using the autopilot to point the vessel in a direction
Using events to wait for things to happen in the game
Tracking the amount of resources in the vessel
Tracking flight data, such as altitude and vertical speed
Setting a part’s properties, such as a parachute’s deploy altitude
Note
For details on how to write scripts and connect to kRPC, see the Getting Started guide.
The tutorial flies the Kerbal 2, one of the game’s stock craft. Load it in the Vehicle Assembly Building and launch it to the pad before you run the script.
The tutorial includes source code for the main client languages kRPC supports. Download the whole program in your chosen language:
Python,
C#,
C++,
C,
Java,
Lua,
JavaScript
Preparing for Launch#
First we open a connection to the server, passing a name for the script. The name appears in the
server window in the game. The C program also defines sleep_ms, which its polling loops pause
with:
conn = krpc.connect(name="Sub-orbital flight")
var conn = new Connection ("Sub-orbital flight");
krpc::Connection conn = krpc::connect("Sub-orbital flight");
krpc::services::SpaceCenter space_center(conn);
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#define sleep_ms(ms) Sleep(ms)
#else
#define _POSIX_C_SOURCE 200809L
#include <time.h>
static void sleep_ms(long ms) {
struct timespec duration = {ms / 1000, (ms % 1000) * 1000000};
nanosleep(&duration, NULL);
}
#endif
#include <krpc_cnano.h>
#include <krpc_cnano/services/krpc.h>
#include <krpc_cnano/services/space_center.h>
#include <stdio.h>
int main() {
krpc_connection_t conn;
if (krpc_open_serial(&conn, "COM0") != KRPC_OK) return 1;
if (krpc_connect(conn, "Sub-orbital flight") != KRPC_OK) return 1;
Connection connection = Connection.newInstance("Sub-orbital flight");
SpaceCenter spaceCenter = SpaceCenter.newInstance(connection);
local krpc = require 'krpc'
local socket = require 'socket'
local conn = krpc.connect('Sub-orbital flight')
const conn = await connect({ name: "Sub-orbital flight" });
Next we get an object representing the active vessel. We send instructions to the rocket through this object:
vessel = conn.space_center.active_vessel
var vessel = conn.SpaceCenter ().ActiveVessel;
auto vessel = space_center.active_vessel().value();
krpc_SpaceCenter_Vessel_t vessel;
krpc_SpaceCenter_ActiveVessel(conn, &vessel);
krpc_SpaceCenter_AutoPilot_t auto_pilot;
krpc_SpaceCenter_Vessel_AutoPilot(conn, &auto_pilot, vessel);
krpc_SpaceCenter_Control_t control;
krpc_SpaceCenter_Vessel_Control(conn, &control, vessel);
SpaceCenter.Vessel vessel = spaceCenter.getActiveVessel();
local vessel = conn.space_center.active_vessel
const vessel = await conn.spaceCenter.getActiveVessel();
const autoPilot = await vessel.getAutoPilot();
const control = await vessel.getControl();
Then we prepare the rocket for launch. This sets the throttle to half, and has the autopilot hold a pitch and heading of 90°, pointing straight up. It then waits a second for the settings to take effect:
vessel.auto_pilot.target_pitch_and_heading(90, 90)
vessel.auto_pilot.engaged = True
vessel.control.throttle = 0.5
time.sleep(1)
vessel.AutoPilot.TargetPitchAndHeading (90, 90);
vessel.AutoPilot.Engaged = true;
vessel.Control.Throttle = 0.5f;
System.Threading.Thread.Sleep (1000);
vessel.auto_pilot().target_pitch_and_heading(90, 90);
vessel.auto_pilot().set_engaged(true);
vessel.control().set_throttle(0.5);
std::this_thread::sleep_for(std::chrono::seconds(1));
krpc_SpaceCenter_AutoPilot_TargetPitchAndHeading(conn, auto_pilot, 90,
90);
krpc_SpaceCenter_AutoPilot_set_Engaged(conn, auto_pilot, true);
krpc_SpaceCenter_Control_set_Throttle(conn, control, 0.5);
sleep_ms(1000);
vessel.getAutoPilot().targetPitchAndHeading(90, 90);
vessel.getAutoPilot().setEngaged(true);
vessel.getControl().setThrottle(0.5f);
Thread.sleep(1000);
vessel.auto_pilot:target_pitch_and_heading(90, 90)
vessel.auto_pilot.engaged = true
vessel.control.throttle = 0.5
socket.sleep(1)
await autoPilot.targetPitchAndHeading(90, 90);
await autoPilot.setEngaged(true);
await control.setThrottle(0.5);
await new Promise((resolve) => setTimeout(resolve, 1000));
Lift-off!#
We launch by activating the first stage, which is the same as pressing the space bar. This lights the engine and releases the launch clamps:
print("Launch!")
vessel.control.activate_next_stage()
Console.WriteLine ("Launch!");
vessel.Control.ActivateNextStage ();
std::cout << "Launch!" << std::endl;
vessel.control().activate_next_stage();
printf("Launch!\n");
krpc_SpaceCenter_Control_ActivateNextStage(conn, NULL, control);
System.out.println("Launch!");
vessel.getControl().activateNextStage();
print('Launch!')
vessel.control:activate_next_stage()
console.log("Launch!");
await control.activateNextStage();
Pitching Over#
Once the rocket has cleared the launch pad, it starts to turn. We wait for an event that fires at an altitude of 500 m:
flight = vessel.flight()
event = conn.add_event(lambda: flight.mean_altitude > 500)
with event.condition:
event.wait()
var flight = vessel.Flight ();
{
var evnt = conn.AddEvent (() => flight.MeanAltitude > 500);
lock (evnt.Condition) {
evnt.Wait ();
}
}
auto e = krpc::services::KRPC::Expression::bind(conn);
auto flight = vessel.flight();
{
auto expr = e.greater_than(e.call(flight.mean_altitude_call()),
e.constant_double(500));
auto event = krpc::add_event(expr);
event.acquire();
event.wait();
event.release();
}
krpc_SpaceCenter_Flight_t flight;
krpc_SpaceCenter_Vessel_Flight(conn, &flight, vessel, KRPC_NULL);
while (true) {
double mean_altitude;
krpc_SpaceCenter_Flight_MeanAltitude(conn, &mean_altitude, flight);
if (mean_altitude > 500) break;
sleep_ms(100);
}
Expression.Bound e = Expression.bind(connection);
Flight flight = vessel.flight(null);
{
ProcedureCall meanAltitude =
connection.getCall(flight, "getMeanAltitude");
Expression expr = e.greaterThan(
e.call(meanAltitude), e.constantDouble(500));
Event event = connection.addEvent(expr);
synchronized (event.getCondition()) {
event.waitFor();
}
}
while vessel:flight().mean_altitude < 500 do
socket.sleep(0.1)
end
const flight = await vessel.flight();
const altitudeEvent = await conn.addEvent(
({ flight }) => flight.meanAltitude > 500,
{ flight },
);
await altitudeEvent.wait();
vessel.flight() returns a Flight object, which gives information about the rocket in
flight, such as its altitude, direction and velocity.
The event is a server side function that compares the altitude with 500. The server checks it every physics tick, and the script sleeps until it fires.
The Python, C# and JavaScript clients compile the lambda into the function. The C++ and Java
clients build it from expression objects: an embedded call to mean_altitude, a constant and a
comparison. The C and Lua clients do not support events, so their scripts poll in a loop, with a
short pause on each pass.
Now we tilt the rocket 20° from vertical, to a pitch of 70°, and hold a heading of 90°, due east. A target smoothing time of 10 seconds turns the rocket over gradually, rather than all at once:
print("Pitching over")
vessel.auto_pilot.target_smoothing_time = 10
vessel.auto_pilot.target_pitch_and_heading(70, 90)
Console.WriteLine ("Pitching over");
vessel.AutoPilot.TargetSmoothingTime = 10;
vessel.AutoPilot.TargetPitchAndHeading (70, 90);
std::cout << "Pitching over" << std::endl;
vessel.auto_pilot().set_target_smoothing_time(10);
vessel.auto_pilot().target_pitch_and_heading(70, 90);
printf("Pitching over\n");
krpc_SpaceCenter_AutoPilot_set_TargetSmoothingTime(conn, auto_pilot, 10);
krpc_SpaceCenter_AutoPilot_TargetPitchAndHeading(conn, auto_pilot, 70,
90);
System.out.println("Pitching over");
vessel.getAutoPilot().setTargetSmoothingTime(10);
vessel.getAutoPilot().targetPitchAndHeading(70, 90);
print('Pitching over')
vessel.auto_pilot.target_smoothing_time = 10
vessel.auto_pilot:target_pitch_and_heading(70, 90)
console.log("Pitching over");
await autoPilot.setTargetSmoothingTime(10);
await autoPilot.targetPitchAndHeading(70, 90);
The engine burns until the fuel tank is empty. We wait for an event that fires when less than 0.1 units of liquid fuel are left:
event = conn.add_event(lambda: vessel.resources.amount("LiquidFuel") < 0.1)
with event.condition:
event.wait()
{
var evnt = conn.AddEvent (
() => vessel.Resources.Amount ("LiquidFuel") < 0.1f);
lock (evnt.Condition) {
evnt.Wait ();
}
}
{
auto liquid_fuel = vessel.resources().amount_call("LiquidFuel");
auto expr = e.less_than(e.call(liquid_fuel), e.constant_float(0.1));
auto event = krpc::add_event(expr);
event.acquire();
event.wait();
event.release();
}
krpc_SpaceCenter_Resources_t resources;
krpc_SpaceCenter_Vessel_Resources(conn, &resources, vessel);
while (true) {
float liquid_fuel;
krpc_SpaceCenter_Resources_Amount(conn, &liquid_fuel, resources,
"LiquidFuel");
if (liquid_fuel < 0.1) break;
sleep_ms(100);
}
{
ProcedureCall liquidFuel = connection.getCall(
vessel.getResources(), "amount", "LiquidFuel");
Expression expr = e.lessThan(
e.call(liquidFuel), e.constantFloat(0.1f));
Event event = connection.addEvent(expr);
synchronized (event.getCondition()) {
event.waitFor();
}
}
while vessel.resources:amount('LiquidFuel') > 0.1 do
socket.sleep(0.1)
end
const fuelEvent = await conn.addEvent(
({ vessel }) => vessel.resources.amount("LiquidFuel") < 0.1,
{ vessel },
);
await fuelEvent.wait();
vessel.resources returns a Resources object, which gives the amounts of the
resources in the rocket.
At flame out we cut the throttle, and the rocket coasts up to its apoapsis. The autopilot now points the rocket prograde, so it follows its arc:
print("Flame out")
vessel.control.throttle = 0
vessel.auto_pilot.reference_frame = vessel.surface_velocity_reference_frame
vessel.auto_pilot.target_direction = (0, 1, 0)
Console.WriteLine ("Flame out");
vessel.Control.Throttle = 0;
vessel.AutoPilot.ReferenceFrame =
vessel.SurfaceVelocityReferenceFrame;
vessel.AutoPilot.TargetDirection = Tuple.Create (0.0, 1.0, 0.0);
std::cout << "Flame out" << std::endl;
vessel.control().set_throttle(0);
vessel.auto_pilot().set_reference_frame(
vessel.surface_velocity_reference_frame());
vessel.auto_pilot().set_target_direction(std::make_tuple(0.0, 1.0, 0.0));
printf("Flame out\n");
krpc_SpaceCenter_Control_set_Throttle(conn, control, 0);
krpc_SpaceCenter_ReferenceFrame_t velocity_frame;
krpc_SpaceCenter_Vessel_SurfaceVelocityReferenceFrame(
conn, &velocity_frame, vessel);
krpc_SpaceCenter_AutoPilot_set_ReferenceFrame(conn, auto_pilot,
velocity_frame);
krpc_tuple_double_double_double_t prograde = {0, 1, 0};
krpc_SpaceCenter_AutoPilot_set_TargetDirection(conn, auto_pilot,
&prograde);
System.out.println("Flame out");
vessel.getControl().setThrottle(0);
vessel.getAutoPilot().setReferenceFrame(
vessel.getSurfaceVelocityReferenceFrame());
vessel.getAutoPilot().setTargetDirection(
new Triplet<Double, Double, Double>(0.0, 1.0, 0.0));
print('Flame out')
vessel.control.throttle = 0
vessel.auto_pilot.reference_frame = vessel.surface_velocity_reference_frame
vessel.auto_pilot.target_direction = {0, 1, 0}
console.log("Flame out");
await control.setThrottle(0);
await autoPilot.setReferenceFrame(
await vessel.getSurfaceVelocityReferenceFrame(),
);
await autoPilot.setTargetDirection([0, 1, 0]);
vessel.surface_velocity_reference_frame has its y-axis along the rocket’s velocity relative to
the surface. So the direction (0, 1, 0) in this frame points prograde. The frame turns with the
velocity, and the rocket turns with it.
Returning Safely to Kerbin#
We separate the capsule at apoapsis, where the rocket stops climbing. This waits for an event that fires when the vertical speed falls below zero:
body_flight = vessel.flight(vessel.orbit.body.reference_frame)
event = conn.add_event(lambda: body_flight.vertical_speed < 0)
with event.condition:
event.wait()
var bodyFlight = vessel.Flight (vessel.Orbit.Body.ReferenceFrame);
{
var evnt = conn.AddEvent (() => bodyFlight.VerticalSpeed < 0);
lock (evnt.Condition) {
evnt.Wait ();
}
}
auto body_flight = vessel.flight(vessel.orbit().body().reference_frame());
{
auto expr = e.less_than(e.call(body_flight.vertical_speed_call()),
e.constant_double(0));
auto event = krpc::add_event(expr);
event.acquire();
event.wait();
event.release();
}
krpc_SpaceCenter_Orbit_t orbit;
krpc_SpaceCenter_Vessel_Orbit(conn, &orbit, vessel);
krpc_SpaceCenter_CelestialBody_t body;
krpc_SpaceCenter_Orbit_Body(conn, &body, orbit);
krpc_SpaceCenter_ReferenceFrame_t body_frame;
krpc_SpaceCenter_CelestialBody_ReferenceFrame(conn, &body_frame, body);
krpc_SpaceCenter_Flight_t body_flight;
krpc_SpaceCenter_Vessel_Flight(conn, &body_flight, vessel, body_frame);
while (true) {
double vertical_speed;
krpc_SpaceCenter_Flight_VerticalSpeed(conn, &vertical_speed,
body_flight);
if (vertical_speed < 0) break;
sleep_ms(100);
}
Flight bodyFlight =
vessel.flight(vessel.getOrbit().getBody().getReferenceFrame());
{
ProcedureCall verticalSpeed =
connection.getCall(bodyFlight, "getVerticalSpeed");
Expression expr = e.lessThan(
e.call(verticalSpeed), e.constantDouble(0));
Event event = connection.addEvent(expr);
synchronized (event.getCondition()) {
event.waitFor();
}
}
local body_frame = vessel.orbit.body.reference_frame
while vessel:flight(body_frame).vertical_speed > 0 do
socket.sleep(0.1)
end
const orbit = await vessel.getOrbit();
const bodyFrame = await (await orbit.getBody()).getReferenceFrame();
const bodyFlight = await vessel.flight(bodyFrame);
const apoapsisEvent = await conn.addEvent(
({ bodyFlight }) => bodyFlight.verticalSpeed < 0,
{ bodyFlight },
);
await apoapsisEvent.wait();
This calls vessel.flight() again, now with a ReferenceFrame. We want the vertical
speed relative to the surface of Kerbin, so the flight object has to give values in a frame fixed
to Kerbin. vessel.orbit.body.reference_frame has its origin at the center of Kerbin, and
rotates with the planet. See the Reference Frames guide for more.
Then we separate the capsule, and have the autopilot turn it retrograde. wait blocks until the
capsule points there. We then disengage the autopilot, and the capsule’s drag keeps it pointing
retrograde as it falls:
print("Apoapsis reached, separating")
vessel.control.activate_next_stage()
vessel.auto_pilot.target_direction = (0, -1, 0)
vessel.auto_pilot.wait()
vessel.auto_pilot.engaged = False
Console.WriteLine ("Apoapsis reached, separating");
vessel.Control.ActivateNextStage ();
vessel.AutoPilot.TargetDirection = Tuple.Create (0.0, -1.0, 0.0);
vessel.AutoPilot.Wait ();
vessel.AutoPilot.Engaged = false;
std::cout << "Apoapsis reached, separating" << std::endl;
vessel.control().activate_next_stage();
vessel.auto_pilot().set_target_direction(std::make_tuple(0.0, -1.0, 0.0));
vessel.auto_pilot().wait();
vessel.auto_pilot().set_engaged(false);
printf("Apoapsis reached, separating\n");
krpc_SpaceCenter_Control_ActivateNextStage(conn, NULL, control);
krpc_tuple_double_double_double_t retrograde = {0, -1, 0};
krpc_SpaceCenter_AutoPilot_set_TargetDirection(conn, auto_pilot,
&retrograde);
krpc_SpaceCenter_AutoPilot_Wait(conn, auto_pilot, -1);
krpc_SpaceCenter_AutoPilot_set_Engaged(conn, auto_pilot, false);
System.out.println("Apoapsis reached, separating");
vessel.getControl().activateNextStage();
vessel.getAutoPilot().setTargetDirection(
new Triplet<Double, Double, Double>(0.0, -1.0, 0.0));
vessel.getAutoPilot().wait_(-1);
vessel.getAutoPilot().setEngaged(false);
print('Apoapsis reached, separating')
vessel.control:activate_next_stage()
vessel.auto_pilot.target_direction = {0, -1, 0}
vessel.auto_pilot:wait()
vessel.auto_pilot.engaged = false
console.log("Apoapsis reached, separating");
await control.activateNextStage();
await autoPilot.setTargetDirection([0, -1, 0]);
await autoPilot.wait();
await autoPilot.setEngaged(false);
The Kerbals are now on a collision course with the surface. We wait until they fall to 2 km above the surface, then deploy the parachute. You can use time warp to skip ahead to just before this happens, and the script carries on working:
event = conn.add_event(lambda: flight.surface_altitude < 2000)
with event.condition:
event.wait()
print("Deploying the parachute")
vessel.parts.parachutes[0].deploy_altitude = 550
vessel.control.activate_next_stage()
{
var evnt = conn.AddEvent (() => flight.SurfaceAltitude < 2000);
lock (evnt.Condition) {
evnt.Wait ();
}
}
Console.WriteLine ("Deploying the parachute");
vessel.Parts.Parachutes [0].DeployAltitude = 550;
vessel.Control.ActivateNextStage ();
{
auto expr = e.less_than(e.call(flight.surface_altitude_call()),
e.constant_double(2000));
auto event = krpc::add_event(expr);
event.acquire();
event.wait();
event.release();
}
std::cout << "Deploying the parachute" << std::endl;
vessel.parts().parachutes()[0].set_deploy_altitude(550);
vessel.control().activate_next_stage();
while (true) {
double surface_altitude;
krpc_SpaceCenter_Flight_SurfaceAltitude(conn, &surface_altitude,
flight);
if (surface_altitude < 2000) break;
sleep_ms(100);
}
printf("Deploying the parachute\n");
krpc_SpaceCenter_Parts_t parts;
krpc_SpaceCenter_Vessel_Parts(conn, &parts, vessel);
krpc_list_object_t parachutes = KRPC_NULL_LIST;
krpc_SpaceCenter_Parts_Parachutes(conn, ¶chutes, parts);
krpc_SpaceCenter_Parachute_set_DeployAltitude(conn, parachutes.items[0],
550);
KRPC_FREE_LIST(parachutes);
krpc_SpaceCenter_Control_ActivateNextStage(conn, NULL, control);
{
ProcedureCall srfAltitude =
connection.getCall(flight, "getSurfaceAltitude");
Expression expr = e.lessThan(
e.call(srfAltitude), e.constantDouble(2000));
Event event = connection.addEvent(expr);
synchronized (event.getCondition()) {
event.waitFor();
}
}
System.out.println("Deploying the parachute");
vessel.getParts().getParachutes().get(0).setDeployAltitude(550);
vessel.getControl().activateNextStage();
while vessel:flight().surface_altitude > 2000 do
socket.sleep(0.1)
end
print('Deploying the parachute')
vessel.parts.parachutes[1].deploy_altitude = 550
vessel.control:activate_next_stage()
const surfaceEvent = await conn.addEvent(
({ flight }) => flight.surfaceAltitude < 2000,
{ flight },
);
await surfaceEvent.wait();
console.log("Deploying the parachute");
const parachutes = await (await vessel.getParts()).getParachutes();
await parachutes[0].setDeployAltitude(550);
await control.activateNextStage();
The parachute semi-deploys as soon as it is safe, which slows the capsule a little. It opens fully at its deploy altitude, 1000 m by default. We lower it to 550 m, so the capsule spends less time hanging under its parachute.
Finally, this prints the altitude of the capsule once a second, until it lands or splashes down:
situation = conn.space_center.VesselSituation
while vessel.situation not in (situation.landed, situation.splashed):
print("Altitude = %.1f meters" % flight.surface_altitude)
time.sleep(1)
print("Landed!")
while (vessel.Situation != VesselSituation.Landed &&
vessel.Situation != VesselSituation.Splashed) {
Console.WriteLine ("Altitude = {0:F1} meters",
flight.SurfaceAltitude);
System.Threading.Thread.Sleep (1000);
}
Console.WriteLine ("Landed!");
using krpc::services::SpaceCenter;
while (vessel.situation() != SpaceCenter::VesselSituation::landed &&
vessel.situation() != SpaceCenter::VesselSituation::splashed) {
std::cout << "Altitude = " << std::fixed << std::setprecision(1)
<< flight.surface_altitude() << " meters" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
std::cout << "Landed!" << std::endl;
krpc_SpaceCenter_VesselSituation_t situation;
while (true) {
krpc_SpaceCenter_Vessel_Situation(conn, &situation, vessel);
if (situation == KRPC_SPACECENTER_VESSELSITUATION_LANDED ||
situation == KRPC_SPACECENTER_VESSELSITUATION_SPLASHED)
break;
double altitude;
krpc_SpaceCenter_Flight_SurfaceAltitude(conn, &altitude, flight);
printf("Altitude = %.1f meters\n", altitude);
sleep_ms(1000);
}
printf("Landed!\n");
while (vessel.getSituation() != VesselSituation.LANDED &&
vessel.getSituation() != VesselSituation.SPLASHED) {
System.out.printf(
"Altitude = %.1f meters\n", flight.getSurfaceAltitude());
Thread.sleep(1000);
}
System.out.println("Landed!");
local landed = conn.space_center.VesselSituation.landed.value
local splashed = conn.space_center.VesselSituation.splashed.value
while vessel.situation.value ~= landed and
vessel.situation.value ~= splashed do
print(string.format('Altitude = %.1f meters',
vessel:flight().surface_altitude))
socket.sleep(1)
end
print('Landed!')
const { landed, splashed } = conn.spaceCenter.VesselSituation;
let situation = await vessel.getSituation();
while (situation !== landed && situation !== splashed) {
const altitude = await flight.getSurfaceAltitude();
console.log(`Altitude = ${altitude.toFixed(1)} meters`);
await new Promise((resolve) => setTimeout(resolve, 1000));
situation = await vessel.getSituation();
}
console.log("Landed!");
Your Kerbals should now be safely back on Kerbin.