Jump to content

KOS Automated Space Program - Second Tutorial


Alpha 360

Recommended Posts

Cough cough.

**Starts speaking in a dull narrator voice

This mission report documents the history of the Automated Space Program, lead by none other than the fearless HAL 9000, the A.I designed to run a space program. Why didn't a Kerbal of remarkable talent step up to the plate instead of this automaton? Because the Kraken banned space travel from kerbals. If a single cell of kerbal flesh escaped the upper atmosphere, then the Kraken would slaughter the population of Kerbin!

Or so our several hundred mages/witch doctors/wizards kerbs state after coming out of intense trances huddled together in their holy places. Everyone knew that they spoke the truth. After all, they said that sensibility was an evil not to be practiced, which we have followed up to the extreme. We have NO cities whatsoever, and yet we built a magnificent space center. There are literally no other structures on the planet, except those which were related to the space program of the distant past. Also, our mages/witch doctors/wizards have spawned in green monoliths in random places, because they were being insensible in accordance with the Kraken's laws. 

Anyway, enough backstory, lets get into the meat of this story. 

**Changes to a scholarly voice, full of appreciation for his subject

I have been messing around with the KOS mod for a little while, and I have decided to create this mission report series so that I will practice this to hopefully great effect. I will make this series primarily about the substance, that is, how I programmed X to do Y and not Z, but pop in the occasion joke, as seen above. I will launch NO kerbals, not one, doing everything with KOS. I will use kerbonauts inside the atmosphere, and rescue them from orbit, but nothing else. My install of KSP is 1.4.4, so mods that work for me probably won't work for those in KSP 1.5+.

I have installed a fairly large mod pack, roughly 30 mods, seen below. 

Spoiler

1. Kerbal Engineer

2. Kerbal Alarm Clock

3. Remote Tech

4.Community Resource Pack

5.Community Tech Tree

6. kerbal Operating Script (kOS)

7. Custom Asteroid pack

8. Kerbal Reusability Expansion 

9. Kerbnet Controller

10. Dynamic Battery Storage

11. DMagic Orbital Science

12. Contract Window +

13. Near Future Suite

14. Lithobrake technologies

15 .KSP ExtendedAntennaProgression

16. Capcom

17. Stock Remote Tech

18. B9 Part Switch

19. Community Category Kit

20. Firespitter Core

21. Contract Parser

22. Rasterprop core

23. Rasterpropmoniter

24. kOS For All!

 And with this, I wish all comers,

Happy Explosions!

Link to comment
Share on other sites

Thanks for the welcome, @Kerbalstar!

(Quick Note: It is vital to have KOS installed to do the tutorial below. Its on the forums as well as CKAN, if you use it.) 

To get down to business, here are the settings for the career mode I have created. 

Spoiler

MiEhhEg.png

mME8xDV.png

YfwNBbP.png

T9HqNYJ.png

 

So, you all know the drill. I get into the career mode, head to the mission control and take up the two contracts, launch first vessel and collect first science report. I then build the usual flea booster with the mk1 capsule on the top. 

WGLIbI1.jpg

This is where my career mode differs from any other. As I have installed, "KOS for All", I can use KOS to launch this without the special parts. So then the tutorial really starts as well. 

If you have KOS installed, when you click the icon you are confronted with a menu. By clicking on the name of the processor you want to activate, a programming terminal opens up. As I had no KOS part, when I clicked on the Mk1 Capsule tag I also brought up the programming terminal. 

hXkmIz8.jpg

To explain what I am doing here, have typed in switch to 0. This means that the programming terminal effectively resets any potential programs still running. Next, I wrote run Mk1.0AutomousDrone. This is the name of the script I wrote to control the active vessel. As one can see, just by typing these two simple lines of code, I can access a larger script in storage, eliminating cut and paste.

So where is the storage for these scripts? Open up the spoiler below to find out. 

Spoiler

Open up your KSP Game file. Scroll down to the "Ships" tab, and open it. 

oIPHaT5.png

From there, click the "Script" tag and ta-da!

jNIogbQ.png?1qpBlRY0.png

Now that you are at your script tab, what do you do? Find a (preferably) free, downloadable code editor like Notepad++ or Brackets or any other program. Once you have downloaded one of these programs, open up a new script. 

Check to see which programming language your new script is using in the program. Each client does each one differently, but one should be able to change what programming language is being used in the new script when saved. Before typing any new code, be sure to save the new program as whatever you want, but add".ks" to the end of it, and save as "text file". 

KOS uses a special programming language called kerboscript, signified by the period-ks. When you write ".ks" , it makes sure that the KOS mod can interpret the text file into something it can use to manipulate the game. That's what you want to happen, obviously. 

After you have saved your new file as "--------.ks" as a text file, then start at the top and write, or copy, these lines of code.

Spoiler

lock throttle to 0. 
gear off.

clearscreen.

While kerboscript is not case sensitive, it is required that one place periods after each "Statement". 

What does this short script do? It basically is your basic "Setting". It locks the throttle to 0, and turns off the gear. Simple, right? Kerboscript is very easy to learn, so don't worry too much. The problem is mastery, something which I haven't even done yet, and plan to do by starting this tutorial. 

One notices the "clearscreen" statement at the bottom. It means that it sets the statements above 'behind the scenes' so to speak. They will be overlaid by new statements in the rest of the script, but will stay active as long as not counter-commanded. 

Next, copy this next statement. 

Spoiler

set runmode to 1.

until runmode = 0 {

     if runmode = 1 {

        lock steering to UP.
        set TVAL to 1.
        stage.
        set runmode to 2.
     }

     else if runmode = 2 and VELOCITY = -1 {

        chutes.
        set runmode to 0.    
     }
     
     set finalTVAL to TVAL.
     lock throttle to finalTVAL.
}

Now this looks like real programming, right? That is correct. This is the meat of the program I have written. By going through this one step at a time, I believe by four paragraphs, you will know enough kerboscript to start experimenting! Anyway, question one is obviously what is that line of code at the very top? That is a variable. Yes, your Algebra days have come back to haunt you. Variables in coding are not unknown values, rather they are values created by the programmer which doesn't exist anywhere else. By using the "set" command, one can create a variable or set a value to a global variable.

The next line of code is an "Until" statement. Its brackets "hold" everything inside, making sure that everything inside is only run when it is active. Also just another note, there are no periods when there are brackets used by the statement. This statement basically keeps the program running UNTIL a certain variable is met. For example, I have already created the variable "runmode" and if it is set to 0 the until statement will end. Right now it is undefined, but later I will redefine it. 

After this is an "if" statement. These are your best friends, activating when a condition is met. For the first one, it only activates if runmode equals one. This means that it activates, as this condition is true. Next come a few pre-installed variables. I lock the steer to "UP." this means that it points up at the sky. I then set the throttle to 1, or max throttle. I stage by simply typing in stage, and then I change the value of runmode, changing it to 2. As this makes the "if" statement invalid, the current statement deactivates.

The next "if" statement has two conditions, which is perfectly plausible. Also, by inserting the word, "Else", it means that this if statement will not be able to run at the same time as the previous "if" statement. By using the two and symbols, one can add as many conditions to a single function. In this case, the "if: statement will only activate if runmode equals 2, and if it is going down. Its as simple as that. When it activates, it arms the chutes and then changes runmode to 0. Since this meets the UNTIL function's criteria, the function shuts down and the program is ended! 

Time for a little housekeeping. The next sentence states, "lock throttle to final TVAL". This means that the ability to throttle the engines is transferred to this value, which is already bound to "TVAL". You've already seen the key "lock", and unlike a door, it cannot be locked and unlocked. Basically the "set" key can be reversible while the "lock" key cannot. This grouping of variables allows me to just use TVAL for any situation, instead of messing around with different variables. The one thing to remember that as a programmer, you are trying to make things EASIER for yourself all the time.

And that is all. Here are some photos of my flight. 

Spoiler

On the launch pad, about to activate the code.

6gESxG2.png

A second after hitting enter. 

GbEULfS.png

(I forgot to edit the code directly, leading to the second statement being mixed up. Don't worry though, the version of the code I have posted here works, because I tested it after this launch.)

Da47qVw.png

Touching down after the flight which brought kerbalkind 10,000 meters above sea level.

QAVu82A.png

Tech tree after completing the contracts and such. 

pgGISJt.png

Now that I have the probe, crews will be nearly worthless except for planes as they will not leave the atmosphere. In the next installment, we will be launching into space itself and hopefully autonomously collecting science reports.

The next tutorial should be up in a week, documenting how to get to use multiple stages in a launch sequence. If you want to go to the source of all my information, here is the link. Until then, 

Happy Explosions!

Edited by Alpha 360
Link to comment
Share on other sites

Neat.  Happy kOSing.

Just a heads-up about something that will likely come back to bite you later - this code:

if runmode = 2 and ALT:RADAR = 1000 

There's almost no chance that check will ever be true.

Because, let's say you're descending.  One moment when you check, your ALT:RADAR might be 1021.3, then the next time you check it's 1004.12, then you check again and it's 999.83, then again and it's 994.1, then again and it's 990.43, etc...  It's never going to be *exactly* 1000.00000 right at the very instant you happen to be checking it.  You might prefer something like a "<" to an "=" check here.

 

Link to comment
Share on other sites

Thank you @Steven Mading, for the tip. I realized just now that there are actually several different ways to do this, but due to an interesting overlay of remote-tech and KOS, I couldn't do it. Specifically, if remote tech is installed, it is necessary for the active vessel to be connected to it to run different parts of the code. For example, I was going to branch out the "Background Settings" to include shutting off SAS, but since in the early game I had no connection, remote tech said no. Same with less than and greater than signs. It just wouldn't work and there would be an error. 

Now that I have unlocked communications antennae, I will be using everything that KOS has to offer. The next tutorial should be much more fleshed out than this one with more fallback and should work 100% of the time. Thanks for the comments, and until the next post, 

Happy Explosions! 

Link to comment
Share on other sites

Here's the next tutorial!

I will be covering how to fly multiple stages, set fallbacks, and use Remote Tech and its pros and cons. 

First, below is the rocket I will be using, "Piloted_Drone_2"

Spoiler

s0HqiVK.jpg

(outdated photo. The one on the launch pad simply had one less canard)

Here it is on the launch pad as well. Jebediah is bravely sitting on the top of this hazardous candle of BOOM, sweating apprehensively. If his code goes wrong, then the rocket might breach the atmosphere, and UNLEASH THE KRAKEN. 

2FdvcBY.jpg

*voice changes abruptly* At least according to the lore :sticktongue:.

Now, to the code!

Spoiler

SAS off.
RCS on.
lock throttle to 0.
gear off.
lights on.

clearscreen.

You have already seen a gutted version of this. As I have said before, this is just a background program. These setting will be overrode eventually, but they get your code going in the right direction. 

Next, there's a few more things. 

Spoiler

set targetApoapsis to 60000.

set activeStaging to true.

set runmode to 2. 
if ALT:RADAR < 50 {
        set runmode to 1.
}

You can guess at what the top is. Its a variable, stating the target Apoapsis, or the highest point of the trajectory. Since kerbals are not allowed to breech the atmosphere in my play-through, I'll put it the target Apoapsis at 60,000 meters.

I set another variable here. You needn't worry about that right now, for I will explain its meaning when the time comes. 

After this, I have set the runmode outside of this if statement, and you notice I have set it at two. Why? In the if statement, it states that if the ship's altitude is less than 50 meters above the ground, then it will switch the runmode to 1. 

Here's a nice, large block of copiable text which I will break up into two parts: the runtime, and the housekeeping. 

PART 1

Spoiler

until runmode = 0 {
    
    if runmode = 1 {
    
        set heading to UP.
        stage.                                                                                                                                                                                                                                        wait 2.
        set runmode to 2.
    }
    
    else if runmode = 2 {
        
        if SHIP:SOLIDFUEL < 1 {
        
            set activeStaging to false.
        }
        
        if ALT:RADAR >= 5000 {
        
            set heading to PROGRADE.
        }
        
        if   activeStaging = false  {
        
            set runmode to 3.
        }
    }
    
    else if runmode = 3 {
        
        lock heading to RETROGRADE.
        
        if ALT:RADAR < 10000 and VELOCITY < 300 {
        
            set runmode to 0.
        
        }
    }

Again, here is the until statement. Extremely useful to define large lines of code and run them as previously demonstrated. 

In the first IF statement, its much like my previous one, excepting one more line of code: "wait". The "WAIT" global variable delays the next action by the number of seconds written down. This is extremely useful when transitioning between active stages. Here I use it to make sure my vessel keeps going up, and then sets heading to PROGADE and starts its gravity turn. Later on, I will be creating a code to carry a vessel to orbit in the most efficient manner. But that is for another day. 

The second IF statement contains several IF statements within it. At the beginning, I set a variable called, "activeStaging" and I set it to true. What does that mean? It means that "activeStaging" is the carrier of a 'Boolean': "TRUE". (Look up Booleans!) Booleans are basically a form of data type which can either be true or false. This can be an easy On/Off switch, which I used here. The first interior IF Statement states that if APOAPSIS is greater than the targetApoapsis, then "activeStaging" is false, or switched off. 

The next IF Statement inside the second container (That's what I'll start calling statements using brackets as a vague term so that I don't repeat myself too often ;)), has a single requirement, that is activeStaging is off, which changes the runmode to 3 and the program switches over to the final "runtime" container. 

Then there's this short IF statement that locks the capsule to face retrograde for reentry and then ends the program. This is where you deploy the chutes quick, fast, and in a hurry. 

(Still haven't figured out how to use chutes in kOS yet :/)

PART 2

Spoiler

If stage:SOLIDFUEL < 1 and activeStaging = true {
    
            stage.
            wait 5.
            stage.
    }
    
    print "RUNMODE:    " + runmode + "      " at (5,4).
    print "ALTITUDE:   " + round(SHIP:ALTITUDE) + "      " at (5,5).
    print "APOAPSIS:   " + round(SHIP:APOAPSIS) + "      " at (5,6).
    print "ETA to AP:  " + round(ETA:APOAPSIS) + "      " at (5,8).
}
 

Here is more housekeeping! A little bit more complex, however. This IF statement will be active the entire time, as long as activeStaging is true, and will be activated when the stage's SOLIDFUEL is less than 1, or empty. Because I have so many stages that would need to be timed, I decided to go the repeatable route. Basically, it stages and decouples the empty stage, waits 5 seconds, and then activates the next stage. 

Finally, there is a list of commands which print words to the screen. These give the info on which Runmode is currently active, the current Altitude, the Apoapsis, and the time to Apoapsis. 

And that is all. Rather more complex than the previous code, but with more reliability, and flexibility. I would suggest altering this code to suit one's needs, as this code will not allow the breaching of the atmosphere. 

Spoiler

ZTwHrtX.png

pd6LQgk.jpg

And then I hit enter.

VpDnB3i.jpg

QfiDjQi.jpg

The Staging IF Statements works! Boy I was happy about that.

v2ECwO5.png

And we hit the upper atmosphere, and gather all the useful science! I had too take the craft down manually, due to an error in my code. I fixed it up here though, so you shouldn't have this problem. After landing safely, I did some research.

TX1an6Q.png

I unlocked all the liquid fuel technologies necessary to reach orbit! Our next destination in this Tutorial. 

Above are the photos of the mission. Next time we will achieve orbit and deorbit, using two separate programs which should be versatile enough to launch anything to orbit and return it (provided it has a heatshield) back to Kerbin. Until then, 

Happy Explosions!

Edited by Alpha 360
Link to comment
Share on other sites

Please tell me if my code doesn't work, or if there is a better solution. This request goes out to all viewers of this thread. I would hate it if my code didn't work, and that some poor kerbal(s) would suffer because of it. 

Anyway, the next tutorial should be soon(ish). Until then,

Happy Explosions!

Link to comment
Share on other sites

This thread is quite old. Please consider starting a new thread rather than reviving this one.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...