Control Loops#
A control loop reads the game state, computes something from it and writes the result back, over and over. The game runs its physics on a fixed step, 50 times a second. A loop that flies a vessel needs to read and write once per step, acting on the state it read.
The Call Wait#
The server executes calls inside the game’s physics update. It measures each client’s time between calls, and waits for a client whose next call it expects soon. The max call wait bounds that wait, 5 milliseconds by default.
A control loop spends its time between the calls: it reads, then computes, then writes. Computing for longer than the max call wait is easy in Python or Lua, and each call then lands in a different physics tick.
An iteration of five calls therefore costs five ticks, and the state the last write was computed from is five ticks old.
The max call wait is a server-wide setting. A client that calls once a tick, or is idle, costs the server no wait.
Holding a Tick#
KRPC.hold_tick() holds the game on its current physics tick, and KRPC.release_tick()
lets it move on. Every call made in between is executed before the game advances. A whole read,
compute and write then happens in the state of one tick:
while True:
conn.krpc.hold_tick()
try:
pitch = vessel.flight().pitch
vessel.control.pitch = control_law(pitch)
finally:
conn.krpc.release_tick()
while (true) {
krpc.HoldTick ();
try {
var pitch = vessel.Flight ().Pitch;
vessel.Control.Pitch = ControlLaw (pitch);
} finally {
krpc.ReleaseTick ();
}
}
while (true) {
krpc.hold_tick();
try {
auto pitch = vessel.flight().pitch();
vessel.control().set_pitch(control_law(pitch));
} catch (...) {
krpc.release_tick();
throw;
}
krpc.release_tick();
}
while (true) {
if (krpc_KRPC_HoldTick(conn) != KRPC_OK) break;
float pitch;
bool ok =
krpc_SpaceCenter_Flight_Pitch(conn, &pitch, flight) == KRPC_OK &&
krpc_SpaceCenter_Control_set_Pitch(conn, control,
control_law(pitch)) == KRPC_OK;
krpc_KRPC_ReleaseTick(conn);
if (!ok) break;
}
while (true) {
krpc.holdTick();
try {
float pitch = vessel.flight(null).getPitch();
vessel.getControl().setPitch(controlLaw(pitch));
} finally {
krpc.releaseTick();
}
}
while true do
conn.krpc.hold_tick()
local ok, err = pcall(function()
local pitch = vessel:flight().pitch
vessel.control.pitch = control_law(pitch)
end)
conn.krpc.release_tick()
if not ok then error(err, 0) end
end
while (true) {
await conn.krpc.holdTick();
try {
const pitch = await (await vessel.flight()).getPitch();
await (await vessel.getControl()).setPitch(controlLaw(pitch));
} finally {
await conn.krpc.releaseTick();
}
}
Release the tick even when the code in between fails, as the example does. The game stays on the held tick until the hold is released or times out.
Consecutive Ticks#
That loop gets whole ticks, but not consecutive ones. The KRPC.hold_tick() opening an
iteration is itself a call the server has to be waiting for. A program that spends longer than
the max call wait between releasing one tick and holding the next skips ticks, and cannot tell
which ones.
KRPC.next_tick() closes that gap. It releases the tick being held and holds the one
immediately after it, in a single call. The game then runs no tick the loop has not held:
try:
while True:
conn.krpc.next_tick()
pitch = vessel.flight().pitch
vessel.control.pitch = control_law(pitch)
finally:
conn.krpc.release_tick()
try {
while (true) {
krpc.NextTick ();
var pitch = vessel.Flight ().Pitch;
vessel.Control.Pitch = ControlLaw (pitch);
}
} finally {
krpc.ReleaseTick ();
}
try {
while (true) {
krpc.next_tick();
auto pitch = vessel.flight().pitch();
vessel.control().set_pitch(control_law(pitch));
}
} catch (...) {
krpc.release_tick();
throw;
}
float pitch;
while (krpc_KRPC_NextTick(conn) == KRPC_OK &&
krpc_SpaceCenter_Flight_Pitch(conn, &pitch, flight) == KRPC_OK &&
krpc_SpaceCenter_Control_set_Pitch(
conn, control, control_law(pitch)) == KRPC_OK) {
}
krpc_KRPC_ReleaseTick(conn);
try {
while (true) {
krpc.nextTick();
float pitch = vessel.flight(null).getPitch();
vessel.getControl().setPitch(controlLaw(pitch));
}
} finally {
krpc.releaseTick();
}
local ok, err = pcall(function()
while true do
conn.krpc.next_tick()
local pitch = vessel:flight().pitch
vessel.control.pitch = control_law(pitch)
end
end)
conn.krpc.release_tick()
if not ok then error(err, 0) end
try {
while (true) {
await conn.krpc.nextTick();
const pitch = await (await vessel.flight()).getPitch();
await (await vessel.getControl()).setPitch(controlLaw(pitch));
}
} finally {
await conn.krpc.releaseTick();
}
The call returns once the next tick is held. The loop therefore runs at one iteration per
physics tick, and the game advances one tick per call. With no tick held, KRPC.next_tick()
holds the soonest one it can, and is the only call the loop needs to open with.
A Worked Example#
Holding a vessel’s pitch with a proportional controller, one iteration per tick:
import krpc
conn = krpc.connect(name="pitch hold")
vessel = conn.space_center.active_vessel
target_pitch = 45
try:
for _ in range(500):
conn.krpc.next_tick()
flight = vessel.flight()
error = target_pitch - flight.pitch
vessel.control.pitch = max(-1, min(1, 0.05 * error))
finally:
conn.krpc.release_tick()
vessel.control.pitch = 0
using System;
using KRPC.Client;
using KRPC.Client.Services.KRPC;
using KRPC.Client.Services.SpaceCenter;
class Program {
public static void Main () {
using (var connection = new Connection ("pitch hold")) {
var krpc = connection.KRPC ();
var vessel = connection.SpaceCenter ().ActiveVessel;
float targetPitch = 45;
try {
for (int i = 0; i < 500; i++) {
krpc.NextTick ();
var flight = vessel.Flight ();
var error = targetPitch - flight.Pitch;
vessel.Control.Pitch =
Math.Max (-1, Math.Min (1, 0.05f * error));
}
} finally {
krpc.ReleaseTick ();
vessel.Control.Pitch = 0;
}
}
}
}
#include <algorithm>
#include <krpc.hpp>
#include <krpc/services/krpc.hpp>
#include <krpc/services/space_center.hpp>
int main() {
auto conn = krpc::connect("pitch hold");
krpc::services::KRPC krpc(conn);
krpc::services::SpaceCenter sc(conn);
auto vessel = sc.active_vessel().value();
float target_pitch = 45;
try {
for (int i = 0; i < 500; i++) {
krpc.next_tick();
auto flight = vessel.flight();
auto error = target_pitch - flight.pitch();
vessel.control().set_pitch(
std::max(-1.0f, std::min(1.0f, 0.05f * error)));
}
} catch (...) {
krpc.release_tick();
vessel.control().set_pitch(0);
throw;
}
krpc.release_tick();
vessel.control().set_pitch(0);
}
#include <krpc_cnano.h>
#include <krpc_cnano/services/krpc.h>
#include <krpc_cnano/services/space_center.h>
int main() {
krpc_connection_t conn;
if (krpc_open_serial(&conn, "COM0") != KRPC_OK) return 1;
if (krpc_connect(conn, "pitch hold") != KRPC_OK) return 1;
krpc_SpaceCenter_Vessel_t vessel;
krpc_SpaceCenter_ActiveVessel(conn, &vessel);
krpc_SpaceCenter_Flight_t flight;
krpc_SpaceCenter_Vessel_Flight(conn, &flight, vessel, KRPC_NULL);
krpc_SpaceCenter_Control_t control;
krpc_SpaceCenter_Vessel_Control(conn, &control, vessel);
float target_pitch = 45;
for (int i = 0; i < 500; i++) {
float pitch;
if (krpc_KRPC_NextTick(conn) != KRPC_OK ||
krpc_SpaceCenter_Flight_Pitch(conn, &pitch, flight) != KRPC_OK)
break;
float command = 0.05f * (target_pitch - pitch);
if (command > 1) command = 1;
if (command < -1) command = -1;
if (krpc_SpaceCenter_Control_set_Pitch(conn, control, command) !=
KRPC_OK)
break;
}
krpc_KRPC_ReleaseTick(conn);
krpc_SpaceCenter_Control_set_Pitch(conn, control, 0);
krpc_disconnect(conn);
}
import krpc.client.Connection;
import krpc.client.services.KRPC;
import krpc.client.services.SpaceCenter;
import krpc.client.services.SpaceCenter.Flight;
import krpc.client.services.SpaceCenter.Vessel;
public class PitchHold {
public static void main(String[] args) {
try (Connection connection = Connection.newInstance("pitch hold")) {
KRPC krpc = KRPC.newInstance(connection);
Vessel vessel =
SpaceCenter.newInstance(connection).getActiveVessel();
float targetPitch = 45;
try {
for (int i = 0; i < 500; i++) {
krpc.nextTick();
Flight flight = vessel.flight(null);
float error = targetPitch - flight.getPitch();
vessel.getControl().setPitch(
Math.max(-1, Math.min(1, 0.05f * error)));
}
} finally {
krpc.releaseTick();
vessel.getControl().setPitch(0);
}
}
}
}
local krpc = require 'krpc'
local conn = krpc.connect('pitch hold')
local vessel = conn.space_center.active_vessel
local target_pitch = 45
local ok, err = pcall(function()
for _ = 1, 500 do
conn.krpc.next_tick()
local flight = vessel:flight()
local pitch_error = target_pitch - flight.pitch
vessel.control.pitch = math.max(-1, math.min(1, 0.05 * pitch_error))
end
end)
conn.krpc.release_tick()
vessel.control.pitch = 0
if not ok then error(err, 0) end
import { connect } from "@krpc-org/krpc";
const conn = await connect({ name: "pitch hold" });
const vessel = await conn.spaceCenter.getActiveVessel();
const control = await vessel.getControl();
const targetPitch = 45;
try {
for (let i = 0; i < 500; i++) {
await conn.krpc.nextTick();
const flight = await vessel.flight();
const error = targetPitch - (await flight.getPitch());
await control.setPitch(Math.max(-1, Math.min(1, 0.05 * error)));
}
} finally {
await conn.krpc.releaseTick();
await control.setPitch(0);
await conn.close();
}
Every iteration reads the pitch of one tick and writes a command that acts on that same tick. The 500 iterations cover 500 consecutive ticks, ten seconds of game time.
To actually fly a vessel, use the autopilot, which implements a far better control law than the one above.
The AutoPilot#
The autopilot’s own control loop also runs once per physics tick. By default it runs after the calls of that tick, so a target set inside a held tick is flown on that tick.
AutoPilot.update_mode chooses where in the tick the loop runs. Its manual mode splits the
tick at update: calls before it set what the loop flies the tick with, and calls after it
read what the loop did. See when the control loop runs.
Server Side Functions#
A server side function runs on the server, within a single tick. One function reads the state, computes the control and writes it, all in that tick. Python and JavaScript compile the function from code. A C# lambda cannot assign to a property, so C# compiles the computation and builds the assignment with the expression API. The other clients build the whole function with it:
@conn.compile
def step():
error = target_pitch - vessel.flight().pitch
vessel.control.pitch = max(-1, min(1, 0.05 * error))
while True:
conn.run(step)
var e = Expression.Bind (connection);
var t = Type.Bind (connection);
var command = connection.Compile (() => Math.Max (
-1.0, Math.Min (1.0, 0.05 * (targetPitch - flight.Pitch))));
// A C# lambda cannot assign to a property, so the expression API
// builds the assignment
var setPitch = Connection.GetSetCallTemplate<Control> (
nameof (Control.Pitch));
var control = RemoteObject.GetObjectId (vessel.Control);
var step = connection.Compile (e.CallWithArguments (setPitch,
new Dictionary<int, Expression> {
{ 0, e.ConstantObject (control) },
{ 1, e.Cast (command, t.Float ()) }
}));
while (true)
connection.Run (step);
auto e = Expr::bind(conn);
auto t = KType::bind(conn);
// control.set_pitch(
// std::clamp(0.05 * (target_pitch - flight.pitch()), -1.0, 1.0));
auto error = e.subtract(e.constant_double(target_pitch),
e.call(flight.pitch_call()));
auto command = e.call_with_arguments(
StdLib::clamp_call_template(),
std::map<int32_t, Expr>(
{{0, e.multiply(e.constant_double(0.05), error)},
{1, e.constant_double(-1)},
{2, e.constant_double(1)}}));
auto step = krpc::compile(e.call_with_arguments(
Control::set_pitch_call_template(),
std::map<int32_t, Expr>(
{{0, e.constant_object(krpc::get_object_id(control))},
{1, e.cast(command, t.float_())}})));
while (true) krpc::run(step);
// control.pitch = clamp(0.05 * (target_pitch - flight.pitch), -1, 1)
krpc_schema_ProcedureCall pitch_call;
krpc_SpaceCenter_Flight_Pitch_call(&pitch_call, flight);
krpc_KRPC_Expression_t target, pitch, error, gain, scaled;
krpc_KRPC_Expression_ConstantDouble(conn, &target, target_pitch);
krpc_KRPC_Expression_Call(conn, &pitch, &pitch_call);
krpc_free_procedure_call(&pitch_call);
krpc_KRPC_Expression_Subtract(conn, &error, target, pitch);
krpc_KRPC_Expression_ConstantDouble(conn, &gain, 0.05);
krpc_KRPC_Expression_Multiply(conn, &scaled, gain, error);
krpc_KRPC_Expression_t lower, upper, command;
krpc_KRPC_Expression_ConstantDouble(conn, &lower, -1);
krpc_KRPC_Expression_ConstantDouble(conn, &upper, 1);
krpc_schema_ProcedureCall clamp_call;
krpc_StdLib_Clamp_call_template(&clamp_call);
krpc_dictionary_entry_int32_object_t clamp_entries[3] = {
{0, scaled}, {1, lower}, {2, upper}};
krpc_dictionary_int32_object_t clamp_arguments = {3, clamp_entries};
krpc_KRPC_Expression_CallWithArguments(conn, &command, &clamp_call,
&clamp_arguments);
krpc_free_procedure_call(&clamp_call);
krpc_KRPC_Type_t float_type;
krpc_KRPC_Type_Float(conn, &float_type);
krpc_KRPC_Expression_t instance, value, step;
krpc_KRPC_Expression_ConstantObject(conn, &instance, control);
krpc_KRPC_Expression_Cast(conn, &value, command, float_type);
krpc_schema_ProcedureCall setter_call;
krpc_SpaceCenter_Control_set_Pitch_call_template(&setter_call);
krpc_dictionary_entry_int32_object_t setter_entries[2] = {{0, instance},
{1, value}};
krpc_dictionary_int32_object_t setter_arguments = {2, setter_entries};
krpc_KRPC_Expression_CallWithArguments(conn, &step, &setter_call,
&setter_arguments);
krpc_free_procedure_call(&setter_call);
krpc_compile_function(conn, step);
while (krpc_run_function(conn, NULL, NULL, step, NULL) == KRPC_OK) {
}
Expression.Bound e = Expression.bind(connection);
Type.Bound t = Type.bind(connection);
// control.setPitch(
// clamp(0.05 * (targetPitch - flight.getPitch()), -1, 1));
ProcedureCall pitch = connection.getCall(flight, "getPitch");
Expression error =
e.subtract(e.constantDouble(targetPitch), e.call(pitch));
Map<Integer, Expression> clampArgs = new HashMap<>();
clampArgs.put(0, e.multiply(e.constantDouble(0.05), error));
clampArgs.put(1, e.constantDouble(-1));
clampArgs.put(2, e.constantDouble(1));
Expression command = e.callWithArguments(
connection.getCallTemplate(StdLib.class, "clamp"), clampArgs);
Map<Integer, Expression> setterArgs = new HashMap<>();
setterArgs.put(
0, e.constantObject(RemoteObject.getObjectId(control)));
setterArgs.put(1, e.cast(command, t.float_()));
Expression step = connection.compile(e.callWithArguments(
connection.getCallTemplate(Control.class, "setPitch"),
setterArgs));
while (true) {
connection.run(step);
}
local Expression = conn.krpc.Expression
-- control.pitch = clamp(0.05 * (target_pitch - flight.pitch), -1, 1)
local pitch = conn:get_call(flight.get_pitch, flight)
local pitch_error = Expression.subtract(
Expression.constant_double(target_pitch), Expression.call(pitch))
local command = Expression.call_with_arguments(conn.std_lib.clamp, Map{
[0] = Expression.multiply(
Expression.constant_double(0.05), pitch_error),
[1] = Expression.constant_double(-1),
[2] = Expression.constant_double(1)
})
local step = conn:compile(Expression.call_with_arguments(
conn.space_center.Control.set_pitch, Map{
[0] = Expression.constant_object(krpc.get_object_id(control)),
[1] = Expression.cast(command, conn.krpc.Type.float())
}))
while true do
conn:run(step)
end
const step = await conn.compile(
({ vessel, targetPitch }) => {
const error = targetPitch - vessel.flight().pitch;
vessel.control.pitch = Math.max(-1, Math.min(1, 0.05 * error));
},
{ vessel, targetPitch },
);
while (true) {
await conn.run(step);
}
Each iteration is one call, and runs in whichever tick the call lands on. The game can run ticks
between the iterations, so a loop that has to act on every tick still uses
KRPC.next_tick(). A stream of the function runs it on every tick instead, with no call at
all. See Control Loops on the Server.
The Cost of a Hold#
A hold costs real time. The game renders no frame, takes no input and runs no physics while a tick is held. A hold of five milliseconds costs five milliseconds of the update it happens in, and a hold of a hundred leaves the game running at about ten frames a second.
A loop using KRPC.next_tick() holds every tick, and the game runs at the rate of the loop
for as long as the loop runs. Physics runs on a fixed time step. A game whose ticks are held
runs slower than real time and simulates every tick in turn.
Keep the held section short, and keep anything that does not need the tick, such as logging or plotting, outside it.
Limits of a Hold#
A hold ends by itself after the tick hold timeout, one second by default, and when the client disconnects. The timeout is a server setting, in the advanced section of the server window, as it bounds how long the server’s owner has their game frozen.
One client holds the tick at a time, and only a client making a call can hold it. A second client’s attempt is refused, as is a hold attempted from a stream or an event.
Streams do not update while a tick is held, as the server sends stream updates once it has finished executing calls. Read with calls inside a hold. A wait for a stream or an event there runs the hold out to its timeout.
Calling a procedure that takes more than one tick to finish, such as staging or warping, ends the hold. Such a call can only finish in the tick the hold is holding back.
A tick lost to the timeout is not reported. The next
KRPC.next_tick()takes whatever tick it lands on, so a loop that has to know whether it kept up reads the game’s own clock throughSpaceCenter.ut.A hold gains nothing while the game is paused, since physics is not advancing, and it blocks the pause menu for as long as it lasts.