### KOS Print Command Examples Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/tutorials/basictutorial.rst.txt Illustrates the basic usage of the 'print' command in KOS to display text, variables, numbers, and booleans. It also shows the functionality of comments (lines starting with //) which are ignored by the script. ```KOS print "hello world". // shows: hello world // print "hello world 1". print "hello world 2". ``` -------------------------------- ### Stack Initialization and Usage Example Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/structures/collections/stack.rst.txt Demonstrates how to create a new stack, add elements using PUSH, and retrieve elements using POP, illustrating the LIFO principle. This is a fundamental example for understanding stack operations in kOS. ```kOS SET S TO STACK(). S:PUSH("alice"). S:PUSH("bob"). PRINT S:POP. // will print 'bob' PRINT S:POP. // will print 'alice' ``` -------------------------------- ### GUI Button Example Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/contents.html Demonstrates how to create and use a button widget in the kOS GUI. This example showcases basic button functionality and event handling. ```kOS PRINT "Button Example" VAR myButton IS Button("Click Me", LIST(10, 10, 100, 30)). myButton:ONCLICK:ADD(PROCEDURE { PRINT "Button Clicked!". }). SCREEN:ADD(myButton). WAIT 10. ``` -------------------------------- ### Quick Sound Example with SKID Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/general.html Demonstrates a basic implementation for generating sound using the SKID sound chip. This example is intended for quick testing and may not cover all hardware capabilities or advanced features. ```kerboscript when sk1:is_ready { sk1:play_note(440, 1.0). sk1:play_note(880, 0.5). } ``` -------------------------------- ### kOS: UNTIL Loop for Reaching Altitude Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/tutorials/quickstart.rst.txt This example uses an UNTIL loop to continuously execute commands until a specific condition (apoapsis exceeding 100,000 meters) is met. It also demonstrates using PRINT AT() to update information on the screen without new lines. ```kOS SET MYSTEER TO HEADING(90,90). //90 degrees east and pitched up 90 degrees (straight up) LOCK STEERING TO MYSTEER. // from now on we'll be able to change steering by just assigning a new value to MYSTEER UNTIL APOAPSIS > 100000 { SET MYSTEER TO HEADING(90,90). //90 degrees east and pitched up 90 degrees (straight up) PRINT ROUND(SHIP:APOAPSIS,0) AT (0,16). // prints new number, rounded to the nearest integer. //We use the PRINT AT() command here to keep from printing the same thing over and //over on a new line every time the loop iterates. Instead, this will always print //the apoapsis at the same point on the screen. }. ``` -------------------------------- ### kOS Processor Module Configuration Example Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/general/kospartmodule.rst.txt An example of the kOS processor module configuration as it would appear in a part's .cfg file. It includes essential fields and comments for optional ones, demonstrating how to set up a kOS-enabled part. ```cfg MODULE { name = kOSProcessor diskSpace = 5000 ECPerBytePerSecond = 0 ECPerInstruction = 0.000004 # Optional fields shown below with default value # baseDiskSpace = 0 # diskSpaceCostFactor = 0.0244140625 # baseModuleCost = 0 # diskSpaceMassFactor = 0.0000048829 # baseModuleMass = 0 } ``` -------------------------------- ### Absolute Path Examples in kOS Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/commands/files.html Demonstrates the format of absolute paths in kOS, including optional leading slashes and the use of the '..' directory for parent directories. Shows valid and invalid path examples. ```kOS 0:flight_data/data.json secondcpu: 1:/boot.ks 0:/directory/subdirectory/../file 0:/directory/file ``` -------------------------------- ### KerboScript User-Defined Function Examples Source: https://context7.com/ksp-kos/kos_doc/llms.txt Illustrates how to define and use custom functions in KerboScript. Includes examples of functions with parameters, functions that return values, and a more advanced example of a function returning a closure (PID controller). ```kerboscript // Function with parameters FUNCTION print_corner { PARAMETER mode. PARAMETER text. LOCAL row IS 0. LOCAL col IS 0. IF mode = 2 OR mode = 4 { SET col TO TERMINAL:WIDTH - text:LENGTH. } IF mode = 3 OR mode = 4 { SET row TO TERMINAL:HEIGHT - 1. } PRINT text AT (col, row). } // Calling the function print_corner(4, "That's me in the corner"). // Function with return value FUNCTION degrees_to_radians { PARAMETER deg. RETURN CONSTANT():PI * deg/180. } SET alpha TO 45. PRINT alpha + " degrees is " + degrees_to_radians(alpha) + " radians.". // Function returning closure (PID controller example) FUNCTION PID { PARAMETER kP, kI, kD, setpoint. LOCAL integral IS 0. LOCAL lastError IS 0. LOCAL lastTime IS TIME:SECONDS. RETURN { PARAMETER measurement. LOCAL dt IS TIME:SECONDS - lastTime. SET lastTime TO TIME:SECONDS. LOCAL error IS setpoint - measurement. SET integral TO integral + error * dt. LOCAL derivative IS (error - lastError) / dt. SET lastError TO error. RETURN kP * error + kI * integral + kD * derivative. }. } // Usage of closure-based PID SET altitudePID TO PID(0.1, 0.01, 0.05, 100). LOCK THROTTLE TO altitudePID(SHIP:ALTITUDE). ``` -------------------------------- ### Basic GUI Setup and Event Handling in KOS Script Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/general/cpu_hardware.html This script demonstrates a basic GUI setup with buttons for 'beep', 'count', and 'quit'. It initializes a GUI window, adds buttons with associated click handlers, shows the window, waits for a 'done' flag, and then disposes of the window. The 'count' function simulates a countdown process. ```KOS Script local done is false. set Gwin to GUI(200). set b1 to Gwin:addbutton("beep"). set b1:onclick to { getvoice(0):play(note(300,0.2)). }. set b2 to GWin:addbutton("count"). set b2:onclick to count@. set b3 to Gwin:addbutton("quit"). set b3:onclick to { set done to true. }. GWin:show(). wait until done. GWin:Dispose(). function count { local i is 5. until i \= 0 { print "Counting.. " + i. set i to i \- 1. wait 1. } } ``` -------------------------------- ### Kos: Combined Until, Lock, and Wait Example Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/tutorials/basictutorial.rst.txt A comprehensive example combining 'set', 'lock', 'time:seconds', 'until', and 'wait'. It sets an initial value, locks a multiplier, defines a future time, and then loops until that future time is reached, printing the multiplier and incrementing an adder each second. ```kos set Adder to 0. lock Multiplier to Adder * 2. set TimePlusFive to time:seconds + 5. until time:seconds > TimePlusFive { print Multiplier. set Adder to Adder + 1. wait 1. } ``` -------------------------------- ### Kerboscript Method Suffix Examples Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/language/syntax.rst.txt Demonstrates calling methods on objects using suffix notation. These examples show how to access parts, check lengths, and modify collections. ```kerboscript set x to ship:partsnamed("rtg"). print x:length(). x:remove(0). x:clear(). ``` -------------------------------- ### KOS Function with Parameters Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/tutorials/basictutorial.html Explains the concept of functions with parameters in KOS using a pseudo-code example. Parameters allow functions to accept dynamic input, making them more versatile. The example shows a 'ShiftGear' function that takes 'StartGear' and 'EndGear' parameters. ```KOS Function ShiftGear { Parameter StartGear. Parameter EndGear. Let go of the gas pedal. Press in the clutch pedal. Shift the gear stick from StartGear to EndGear. Let go of the clutch pedal. Press in the gas pedal. } ShiftGear(first, second). ShiftGear(second, third). ShiftGear(third, second). ``` -------------------------------- ### PartModule Configuration Example (ksp-kos) Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/general/parts_and_partmodules.rst.txt An example snippet illustrating the structure of a Part.cfg file, specifically showing how a 'ModuleCommand' PartModule is declared. This format is used by KSP to define the components of a part. ```cfg MODULE { name = ModuleCommand } ``` -------------------------------- ### Initialize PIDLoop with Custom Parameters - KOS Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/structures/misc/pidloop.html These examples demonstrate initializing a PIDLoop with custom parameters. The PIDLoop constructor can accept the proportional gain (kp), integral gain (ki), derivative gain (kd), and optional minimum and maximum output values. Ensure the provided values are numerical. ```KOS SET PID TO PIDLOOP(2.5). SET PID TO PIDLOOP(2.0, 0.05, 0.1). SET PID TO PIDLOOP(2.0, 0.05, 0.1, -1, 1). ``` -------------------------------- ### Kerboscript Quick Sound Example Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/general/skid.rst.txt This snippet demonstrates basic sound playback using the SKID chip in Kerboscript. It retrieves a voice reference and plays a note with a specified frequency and duration. The example highlights that playback occurs in the background, allowing the program to continue execution. ```kerboscript SET V0 TO GETVOICE(0). V0:PLAY( NOTE(400, 2.5) ). PRINT "The note is still playing". PRINT "when this prints out." ``` -------------------------------- ### Initialize PIDLoop with Default Parameters - KOS Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/structures/misc/pidloop.html This example shows how to create a PIDLoop instance using its default parameters. The default values are kp = 1, ki = 0, kd = 0, with output limits set to the maximum and minimum representable numbers. No external libraries are required beyond the core KOS environment. ```KOS SET PID TO PIDLOOP(). ``` -------------------------------- ### Switch Volumes and Manage Files in kOS Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/tutorials/quickstart.rst.txt Demonstrates switching to the Archive volume (volume 0), creating a new file 'HELLO2', listing files, running the new script, switching back to the local volume (volume 1), listing files again, and running the original 'HELLO' script. This showcases volume management and file operations. ```kOS Script SWITCH TO 0. EDIT HELLO2. // Make a new file here that just says: PRINT "hi again". LIST FILES. RUN HELLO2. SWITCH TO 1. LIST FILES. RUN HELLO. ``` -------------------------------- ### kOS: Construct and Iterate a Range Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/structures/collections/range.html Demonstrates how to construct a Range in kOS and iterate through its values using a FOR loop. The first example shows a default range starting from 0, and the second shows a range with a custom start and an operation applied to each element. ```kos FOR I IN RANGE(5) { PRINT I. } // will print numbers 0,1,2,3,4 ``` ```kos FOR I IN RANGE(2, 5) { PRINT I*I. } // will print 4, 9 and 16 ``` -------------------------------- ### Get Substring from String Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/structures/misc/string.html Extracts a portion of the string starting from a specified index for a given length. This method is useful for isolating specific parts of a string. ```kOS s:SUBSTRING(startIndex, length) ``` -------------------------------- ### Create and Run a kOS Script Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/tutorials/quickstart.rst.txt Shows how to create, save, and run a kOS script file. The script uses multiple PRINT commands to display text. The process involves using the EDIT command to create the file, typing the script content, saving, exiting, and then running the script using the RUN command. ```kOS PRINT "=========================================". PRINT " HELLO WORLD". PRINT "THIS IS THE FIRST SCRIPT I WROTE IN kOS.". PRINT "=========================================". ``` ```kOS EDIT HELLO. ``` ```kOS RUN HELLO. ``` ```kOS RUNPATH("hello") ``` -------------------------------- ### Relative Path Operations in kOS Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/commands/files.html Illustrates how relative paths are resolved by kOS by appending them to the current directory. Includes examples for deleting, copying, and handling paths starting with '/'. ```kOS CD("0:/scripts"). DELETEPATH("launch.ks"). // this will remove 0:/scripts/launch.ks COPYPATH("../launch.ks", ""). // this will copy 0:/launch.ks to 0:/scripts/launch.ks COPYPATH("/launch.ks", "launch_scripts"). // will copy 0:/launch.ks to 0:/scripts/launch_scripts ``` -------------------------------- ### Creating and Running a kOS Script File Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/tutorials/quickstart.html This demonstrates how to create a script file named 'HELLO' using the kOS editor, write multiple PRINT statements to it, save the file, and then execute it using the RUN command. It highlights the process of programmatically generating output. ```kOS EDIT HELLO. PRINT "=========================================". PRINT " HELLO WORLD". PRINT "THIS IS THE FIRST SCRIPT I WROTE IN kOS.". PRINT "=========================================". RUN HELLO. ``` -------------------------------- ### kOS Script Execution: File Copy and Run Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/tutorials/quickstart.rst.txt This snippet shows how to manage kOS scripts by copying them from an archive volume (0) to the local drive (1) and then executing them. This is a fundamental workflow for loading and running custom scripts within the game. ```kOS SWITCH TO 0. LIST FILES. SWITCH TO 1. COPYPATH("0:/HELLOLAUNCH", ""). // copies from 0 (archive) to current default location (local drive (1)). RUN HELLOLAUNCH. ``` -------------------------------- ### Get Signal Delay to a Vessel with kOS and RemoteTech Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/addons/RemoteTech.rst.txt Calculates and prints the signal delay between Kerbal Space Center (KSC) and the current ship using RemoteTech. This requires RemoteTech to be installed and available. ```kOS Script if addons:available("RT") { local myRT is addons:RT. print "The delay from KSC to Myself is:". print myRT:KSCDELAY(ship) + " seconds.". } ``` -------------------------------- ### Kos: Lexicon Creation and Access Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/tutorials/basictutorial.rst.txt Explains and demonstrates the creation and usage of lexicons, which store key-value pairs. It shows how to initialize a lexicon with string keys and numerical values and how to access values using their corresponding keys. ```kos set MyLexicon to lexicon("MyValue1", 100, "MyValue2", 200, "MyValue3", 300). ``` ```kos set MyLexicon to lexicon( "MyValue1", 100, "MyValue2", 200, "MyValue3", 300 ). ``` ```kos print MyLexicon["MyValue1"]. // shows 100 print MyLexicon["MyValue2"]. // shows 200 print MyLexicon["MyValue3"]. // shows 300 ``` -------------------------------- ### Get a Voice - kOS Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/structures/misc/voice.html Retrieves a specific voice from the SKID sound chip. The voice is identified by its numerical index, starting from 0. This function returns a Voice structure, allowing access to its properties and functions. ```kOS SET myVoice TO GetVoice(0). // myVoice is now a VOICE structure representing hardware voice 0. ``` -------------------------------- ### Basic 'Hello World' in kerboscript Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/index.rst.txt This snippet demonstrates the most basic functionality of kOS by printing a 'Hello World' message and a descriptive sentence. It requires no external dependencies and serves as an introductory example for new users. ```kerboscript PRINT "Hello World.". PRINT "These are the documents for Kerbal Operating System.". ``` -------------------------------- ### PIDLoop Methods Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/structures/misc/pidloop.html This section details the methods available for interacting with the PIDLoop, such as resetting or updating its state. ```APIDOC ## PIDLoop Methods ### Description Perform actions on the PID controller, such as resetting or updating. ### Methods - **RESET** - Description: Reset the integral and derivative components. - Method: POST - Endpoint: /pidloop/reset - Request Body: None - **UPDATE(time, input)** - Description: Returns output based on time and input. - Method: POST - Endpoint: /pidloop/update - Parameters: - **time** (Scalar) - Required - The current time. - **input** (Scalar) - Required - The current input value. - Request Body: ```json { "time": 123.45, "input": 50.0 } ``` - Response: - Success Response (200): - **output** (Scalar) - The calculated PID output. ``` -------------------------------- ### Get PartModule by Index - kOS Script Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/structures/vessels/part.rst.txt This example demonstrates how to retrieve a specific PartModule from a part using its index. It iterates through all modules, checks their names, and then retrieves the module if a match is found. This method is recommended because module indexes are not guaranteed to remain consistent. ```kOS local moduleNames is part:modules. for idx in range(0, moduleNames:length) { if moduleNames[idx] = "test module" { local pm is part:getmodulebyindex(idx). DoSomething(pm). } } ``` -------------------------------- ### kOS: Basic Rocket Launch Sequence Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/tutorials/quickstart.rst.txt This script initializes rocket control by clearing the screen, locking throttle to maximum, executing a countdown, and handling staging when thrust is zero. It then waits until a specific altitude is reached before releasing control. ```kOS //hellolaunch //First, we'll clear the terminal screen to make it look nice CLEARSCREEN. //Next, we'll lock our throttle to 100%. LOCK THROTTLE TO 1.0. // 1.0 is the max, 0.0 is idle. //This is our countdown loop, which cycles from 10 to 0 PRINT "Counting down:". FROM {local countdown is 10.} UNTIL countdown = 0 STEP {SET countdown to countdown - 1.} DO { PRINT "..." + countdown. WAIT 1. // pauses the script here for 1 second. } //This is a trigger that constantly checks to see if our thrust is zero. //If it is, it will attempt to stage and then return to where the script //left off. The PRESERVE keyword keeps the trigger active even after it //has been triggered. WHEN MAXTHRUST = 0 THEN { PRINT "Staging". STAGE. PRESERVE. }. LOCK STEERING TO UP. WAIT UNTIL ALTITUDE > 70000. ``` -------------------------------- ### Get Object Inheritance Hierarchy (kOScript) Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/structures/reflection/structure.html The `inheritance` attribute returns a string describing the object's type hierarchy, starting from its specific type and going up to the root `Structure` type. This helps understand the lineage of an object. ```kOScript set x to SHIP. print x:inheritance. ``` -------------------------------- ### Basic Kerboscript Boot File Example Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/general/boot.html A simple kerboscript program designed to be used as a boot file. It waits for the ship to be unpacked, clears the screen, and prints messages to confirm execution. This script should be saved in the '0:/boot/' directory with a .ks extension. ```kerboscript // Place this file in your archive and call it "boot/myboot.ks". wait until ship:unpacked. clearscreen. print "Hello. I am the boot file.". print "If you see this, that proves the boot file ran.". ``` -------------------------------- ### Example: Loop until a TimeStamp condition is met in KOS Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/structures/misc/time.rst.txt This KOS code snippet demonstrates how to use a loop that continues until a specific TimeStamp is reached. It utilizes the TIMESTAMP() function to get the current time and compares it with a calculated end time. ```KOS local end_time is TIMESTAMP() + 3. // Now plus 3 seconds. until TIMESTAMP() > end_time { // Note this is a TimeStamp > TimeStamp comparison print "3 seconds aren't up yet...". wait 0.2. } print "3 seconds have passed.". ``` -------------------------------- ### Execute kOS Interactive Command Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/tutorials/quickstart.rst.txt Demonstrates how to execute a simple kOS command directly in the terminal to print text to the screen. This involves typing CLEARSCREEN and PRINT commands followed by a period and ENTER. ```kOS CLEARSCREEN. PRINT "==HELLO WORLD==". ``` -------------------------------- ### Get Furthest Corner of Bounds Box Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/structures/vessels/bounds.rst.txt Demonstrates how to find a specific corner of the vessel's bounding box using the :meth:`Bounds:FURTHESTCORNER(ray)` suffix. This example finds the bottom-most vertex by providing a downward-pointing vector. ```kerboscript set B to ship:BOUNDS. // The furthest corner of the box in the downward (negative up) direction: set bottom to B:FURTHESTCORNER( - up:vector ). ``` -------------------------------- ### Get kOS Inheritance Hierarchy (kOS Script) Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/structures/reflection/structure.rst.txt Returns a string representing the inheritance chain of an object, starting from its specific type and going up to the root 'Structure' type. This helps understand the relationships between different kOS object types. ```kOS Script set x to SHIP. print x:inheritance. // Output: Vessel derived from Orbitable derived from Structure ``` -------------------------------- ### Craft Management Methods Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/structures/misc/kuniverse.rst.txt Methods for managing craft files, including loading, launching, and listing available craft. ```APIDOC ## Craft Management Methods ### Description Methods for managing craft files, including loading, launching, and listing available craft. ### Methods #### `KUniverse:GETCRAFT(name, editor)` - **Method**: Gets the file path for the craft with the given name, saved in the given editor. - **Parameters**: - `name` (String) - The name of the craft. - `editor` (String) - The editor where the craft is saved ('SPH' or 'VAB'). - **Returns**: `CraftTemplate` #### `KUniverse:LAUNCHCRAFT(template)` - **Method**: Launches a new instance of the given craft at its default launch site. - **Parameters**: - `template` (CraftTemplate) - The craft template to launch. #### `KUniverse:LAUNCHCRAFTFROM(template, site)` - **Method**: Launches a new instance of the given craft at the specified site. - **Parameters**: - `template` (CraftTemplate) - The craft template to launch. - `site` (String) - The name of the launch site. #### `KUniverse:LAUNCHCRAFTWITHCREWFROM(template, crewlist, site)` - **Method**: Launches a new instance of the given craft with the specified crew list at the given site. - **Parameters**: - `template` (CraftTemplate) - The craft template to launch. - `crewlist` (List of String) - A list of crew member names. - `site` (String) - The name of the launch site. #### `KUniverse:CRAFTLIST()` - **Method**: Returns a list of all craft templates in the save-specific and stock folders. - **Returns**: List of `CraftTemplate`. ``` -------------------------------- ### Example Kerboscript Boot File Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/general/boot.rst.txt A simple kerboscript program that demonstrates the basic functionality of a boot file. It waits for the ship to be unpacked, clears the screen, and prints a confirmation message. ```kerboscript // Place this file in your archive and call it "boot/myboot.ks". wait until ship:unpacked. clearscreen. print "Hello. I am the boot file.". print "If you see this, that proves the boot file ran.". ``` -------------------------------- ### Get Root Part of a Vessel (KOS) Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/commands/parts.rst.txt Retrieves the primary root part of the vessel, which is typically the first part placed during construction in the VAB or SPH. This is essential for establishing a starting point for part hierarchy navigation. ```KOS SET firstPart to SHIP:ROOTPART. ``` -------------------------------- ### GUI Initialization and Showing in KOS Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/structures/gui_widgets/gui.rst.txt Demonstrates how to initialize a GUI object and make it visible using the `SHOW` method. This is a fundamental step for displaying any user interface elements created with the KOS GUI library. ```KOS set g to gui(200). // .. call G:addbutton, G:addslider, etc etc here g:show(). ``` -------------------------------- ### SKID Chip: Basic Sound Playback Example Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/changes.html Demonstrates how to use the SKID chip to play a basic sound note. It shows how to get a voice reference and play a note with specified frequency and duration. The note plays asynchronously, allowing the script to continue execution. ```kOS SET V0 TO GETVOICE(0). // Gets a reference to the zero-th voice in the chip. V0:PLAY( NOTE(400, 2.5) ). // Starts a note at 400 Hz for 2.5 seconds. // The note will play while the program continues. PRINT "The note is still playing". PRINT "when this prints out." ``` -------------------------------- ### Find Furthest Corner of Another Vessel's Bounds Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/structures/vessels/bounds.html This example shows how to get the bounding box of another vessel and then use the FURTHESTCORNER method to find the position of the corner that is furthest in the 'up' direction. This is useful for determining the extent of an object in a specific gameworld direction. ```kerboscript // Assume other_vessel has been set to some vessel nearby // other than the current SHIP: local ves_box is other_vessel:bounds. local top is ves_box:furthestcorner(up:vector). ``` -------------------------------- ### kOS GUI: Creating a Basic Window Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/structures/gui.html Illustrates the fundamental process of creating a GUI window with a button. It shows how to instantiate a GUI, add a button, display it, wait for a button press, and then hide the window. ```kOS SET my_gui TO GUI(200). SET button TO my_gui:ADDBUTTON("OK"). my_gui:SHOW(). UNTIL button:TAKEPRESS WAIT(0.1). my_gui: HIDE(). ``` -------------------------------- ### Access KOS Archive and Run Script Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/tutorials/basictutorial.rst.txt This shows the process of switching to the KOS archive (archive 0) and then running a KOS script file named 'hello.ks'. Scripts in the archive are persistent and can be accessed across different saved games. ```KOS switch to 0. run hello. ``` -------------------------------- ### Create and play a sliding note with Voice PLAY method Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/structures/misc/note.html This example shows how to create a sliding note that changes pitch linearly over its duration and play it using the Voice PLAY method. It uses the SLIDENOTE function, specifying start and end frequencies, duration, key down length, and volume. ```KOS SET V1 TO GETVOICE(0). // A fast "whoop" sound that pitches up from 300 Hz to 600 Hz quickly: V1:PLAY( SLIDENOTE(300, 600, 0.2, 0.25, 1) ). ``` -------------------------------- ### Get Landing Leg's Bottom Altitude Radar Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/structures/vessels/bounds.rst.txt Calculates and displays the radar altitude of the bottom corner of a specific landing leg part's bounding box. This example assumes the landing leg part has been tagged with 'sensing leg'. It retrieves the part's bounds and updates the display in a loop. ```kerboscript set leg_part to ship:partstagged("sensing leg")[0]. local bounds_box is leg_part:bounds. until terminal:input:haschar { clearscreen. print "PRESS ANY KEY TO QUIT". print "ALT:RADAR of ship bounding box's bottom corner is:". print round(bounds_box:BOTTOMALTRADAR, 1). wait 0. } terminal:input:getchar(). ``` -------------------------------- ### Convert Scalar Universal Time to TimeStamp (kOS) Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/structures/misc/time.html Creates a TimeStamp structure from a scalar universal time value. The universal time is represented as the number of seconds passed since the current game began, in game time. For example, 3600 seconds represents exactly 1 hour after the game started. ```kOS VAR scalarTime IS 3600. VAR myTimeStamp IS TimeStamp(scalarTime). ``` -------------------------------- ### Deploy and Run Science Experiment (kOS) Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/structures/vessels/scienceexperiment.rst.txt Demonstrates how to deploy and run a science experiment using the DEPLOY() method. This method fails if the experiment already has data or is inoperable. It requires a reference to a ModuleScienceExperiment. ```kOS SET P TO SHIP:PARTSNAMED("GooExperiment")[0]. SET M TO P:GETMODULE("ModuleScienceExperiment"). M:DEPLOY. ``` -------------------------------- ### List Files in kOS Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/tutorials/quickstart.rst.txt Lists all files on the currently selected volume. This command is fundamental for checking the contents of storage, whether on a local vessel volume or the Archive. The default is to list 'FILES'. ```kOS Script LIST FILES. ``` -------------------------------- ### Get Part by Name Tag (kOS Script) Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/general/nametag.html This kOS script example demonstrates how to retrieve a specific part using its assigned name tag. It uses the :PARTSDUBBED method and expects exactly one part with the given name. If multiple parts share the same name tag, it will only retrieve the first one in the list. ```kOS Script SET myPart TO SHIP:PARTSDUBBED("my nametag here")[0]. ``` -------------------------------- ### Create and Configure a Button with Tooltip and Click Action Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/structures/gui_widgets/tipdisplay.html Demonstrates creating a button, setting its tooltip, and defining an action to be performed when the button is clicked. The click action in this example plays a musical note. ```kOS set b3:tooltip to "Makes high pitch note.". set b3:onclick to {getvoice(0):play(note(400,0.5)).}. ``` -------------------------------- ### KOS IR Servo Control Group Iteration Example Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/addons/IR.rst.txt Provides an example of iterating through available IR control groups and their associated servos. It demonstrates how to access group names, servo counts, and individual servo names and positions, with a conditional example of moving a servo. ```kos print "IR available: " + ADDONS:IR:AVAILABLE. print "Groups:". for g in ADDONS:IR:GROUPS { print g:NAME + " contains " + g:SERVOS:LENGTH + " servos:". for s in g:servos { print " " + s:NAME + ", position: " + s:POSITION. if (g:NAME = "Hinges" and s:POSITION = 0) { s:MOVETO(30, 2). } } } ``` -------------------------------- ### ScienceExperimentModule:DEPLOY() Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/structures/vessels/scienceexperiment.html Deploys and runs the science experiment. Fails if the experiment already has data or is inoperable. ```APIDOC ## ScienceExperimentModule:DEPLOY() ### Description Deploys and runs this science experiment. This method will fail if the experiment already contains scientific data or is inoperable. ### Method * `DEPLOY()` ### Endpoint N/A (This is a method call within the KSP/Kos environment) ### Parameters None ### Request Example ```lua ScienceExperimentModule:DEPLOY() ``` ### Response #### Success Response (None explicitly defined, implies successful execution) #### Response Example None explicitly defined. ``` -------------------------------- ### KerboScript Function Example: Print Text in Terminal Corner Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/language/user_functions.rst.txt An example of a KerboScript user function named 'print_corner' that prints a given text string in one of the four terminal corners. It takes 'mode' and 'text' as parameters and uses terminal dimensions to position the output. The example also demonstrates how to call this user-defined function. ```KerboScript // Print the string you pass in, in one of the 4 corners // of the terminal: // mode = 1 for upper-left, 2 for upper-right, 3 // for lower-left, and 4 for lower-right: // function print_corner { parameter mode. parameter text. local row is 0. local col is 0. if mode = 2 or mode = 4 { set col to terminal:width - text:length. }. if mode = 3 or mode = 4 { set row to terminal:height - 1. }. print text at (col, row). }. // An example of calling it: print_corner(4,"That's me in the corner"). ``` -------------------------------- ### kOS Basic Path Commands Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/commands/files.rst.txt Provides examples of basic path manipulation commands like RUN and CD. ```kOS RUN script. // Executes a script in the current directory. CD(dir.ext) // Changes the current directory to 'dir.ext'. ``` -------------------------------- ### PIDLoop Constructor Examples in kOS Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/structures/misc/pidloop.rst.txt Demonstrates various ways to initialize a PIDLoop object in kOS. This includes using default parameters, specifying only a few parameters, or providing a full set of gains and output limits. The PIDLoop is fundamental for creating automated control systems. ```kOS SET PID TO PIDLOOP(). SET PID TO PIDLOOP(2.5). SET PID TO PIDLOOP(2.0, 0.05, 0.1). SET PID TO PIDLOOP(2.0, 0.05, 0.1, -1, 1). ``` -------------------------------- ### kOS Lexicon: Error on Non-Existent Key GET Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/structures/collections/lexicon.html Shows the expected behavior when attempting to GET a value from a lexicon using a key that does not exist. This will result in a KOSKeyNotFoundException. ```kOS SET ARR TO LEXICON(). SET X TO ARR["somekey"]. // this will produce an error. ``` -------------------------------- ### Basic kOS Script: Countdown and Screen Clear Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/tutorials/quickstart.rst.txt This script demonstrates clearing the terminal screen and implementing a countdown loop. It uses basic kOS commands and comments for readability. The script pauses for 1 second in each loop iteration. ```kOS //hellolaunch //First, we'll clear the terminal screen to make it look nice CLEARSCREEN. //This is our countdown loop, which cycles from 10 to 0 PRINT "Counting down:". FROM {local countdown is 10.} UNTIL countdown = 0 STEP {SET countdown to countdown - 1.} DO { PRINT "..." + countdown. WAIT 1. // pauses the script here for 1 second. } ``` -------------------------------- ### KerboScript Structure Access Example Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/language/features.rst.txt Demonstrates accessing components of structure variables in KerboScript using the colon operator. Examples include retrieving orbital parameters and ship velocity components. ```kerboscript PRINT "The Mun's periapsis altitude is: " + MUN:PERIAPSIS. PRINT "The ship's surface velocity is: " + SHIP:VELOCITY:SURFACE. ``` -------------------------------- ### Build Documentation Locally (Shell) Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/contribute.rst.txt Commands to clean and build the project's HTML documentation locally. This requires Sphinx and the Read The Docs Theme to be installed. Navigate to the 'doc/' directory before running these commands. ```bash make clean make html ``` -------------------------------- ### Create and Run a KOS Script In-Game Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/tutorials/basictutorial.rst.txt This demonstrates how to create a new KOS script file named 'hello' within the KOS terminal, edit its content, and then execute it. Scripts created this way are stored locally on the ship and will be lost when the vessel is removed. ```KOS edit hello. run hello. ``` -------------------------------- ### Get Target Vessel Reference - KSP Kos Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/structures/vessels/vessel.rst.txt This snippet demonstrates how to get a reference to the currently targeted vessel. Storing this in a variable ensures you maintain the reference even if the target changes. ```kos SET MY_VESS TO TARGET. ``` -------------------------------- ### Get Vessel Reference by Name - KSP Kos Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/structures/vessels/vessel.rst.txt This snippet shows how to get a reference to a specific vessel using its name. The name is case-sensitive. This is useful for interacting with a particular ship in the game. ```kos SET MY_VESS TO VESSEL("Some Ship Name"). ``` -------------------------------- ### kOS: Construct and Iterate Range with Start and Stop Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/structures/collections/range.rst.txt Illustrates creating a Range with explicit start and stop values, using the default step of 1. The loop then prints the square of each element. ```kOS FOR I IN RANGE(2, 5) { PRINT I*I. } // will print 4, 9 and 16 ``` -------------------------------- ### Deploy and Observe Science Experiment - kOS Script (Manual Interaction) Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/structures/vessels/scienceexperiment.html This kOS script shows how to get the ScienceExperimentModule and attempt to deploy or observe a science experiment. Note that this method, as described in the documentation, may result in a dialog box appearing for the user, requiring manual interaction to reset or transmit data, unlike the automated methods. ```kOS SET P TO SHIP:PARTSNAMED("GooExperiment")[1]. SET M TO P:GETMODULE("ModuleScienceExperiment"). M:DOEVENT("observe mystery goo"). ``` -------------------------------- ### Kos: Until Loop Example Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/tutorials/basictutorial.rst.txt Demonstrates the 'until' loop for repeating code until a condition is met. It initializes a variable, loops while the variable is not greater than 100, printing and incrementing the variable in each iteration. ```kos set x to 0. until x > 100 { print x. set x to x + 1. } ``` -------------------------------- ### KOS FROM Loop Example: Compact Formatting Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/language/flow.html An example of KOS FROM loop syntax with a compact, single-line header and an indented loop body. This format is suitable for shorter loop configurations. ```KOS FROM {local x is 1.} UNTIL x > 10 STEP {set x to x+1.} DO { print x. } ``` -------------------------------- ### Create and Interact with a GUI Window Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/structures/gui.rst.txt Demonstrates creating a GUI window with a specific width, adding a button, showing the GUI, waiting for a button press, and then hiding the GUI. This function requires no external dependencies. ```kos SET my_gui TO GUI(200). SET button TO my_gui:ADDBUTTON("OK"). my_gui:SHOW(). UNTIL button:TAKEPRESS WAIT(0.1). my_gui:HIDE(). ``` -------------------------------- ### KerboScript Short-Circuiting Boolean Logic Example Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/language/features.rst.txt Demonstrates the short-circuiting behavior of boolean operations (AND/OR) in KerboScript. This example shows how the evaluation of an OR expression stops early if the result is already determined, improving efficiency. ```kerboscript set x to true. if x or y+2 > 10 { print "yes". } else { print "no". }. ``` -------------------------------- ### Start Vessel Tracking Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/structures/vessels/vessel.rst.txt Initiates tracking for a vessel, similar to the 'Start Tracking' button in the Tracking Station. This changes asteroids from 'Unknown' to 'SpaceObject', preventing them from being de-spawned by KSP's management system. ```kOS Vessel:STARTTRACKING(). ``` -------------------------------- ### Scoping Examples (Kerboscript) Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/language/variables.rst.txt Provides practical examples of variable scoping in Kerboscript. It shows explicit global and local declarations, implicit global variable creation with SET, and function scope for variables. ```kerboscript GLOBAL x IS 10. // X is now a global variable with value 10, SET y TO 20. // Y is now a global variable (implicitly) with value 20. LOCAL z IS 0. // Z is now local to this file's outer scope. This is // not *quite* global because it means other program files // can't see it. SET sum to -1. // sum is now an implicitly made global variable, containing -1. // This function is declared at the file's outer scope. // It can be seen and called by other programs after this program is done. FUNCTION calcAverage { PARAMETER inputList. LOCAL sum IS 0. // sum is now local to this function's body. FOR val IN inputList { SET sum TO sum + val. }. print "Inside calcAverage, sum is " + sum. RETURN sum / inputList:LENGTH. }. SET testList TO LIST(5,10,15); print "average is " + calcAverage(testList). print "but out here where it's global, sum is still " + sum. ``` -------------------------------- ### Implement Staging Logic with kOS WHEN Trigger Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/tutorials/quickstart.rst.txt This code introduces a 'WHEN' trigger to automate staging in kOS. It continuously monitors the ship's maximum thrust and activates the next stage when thrust becomes zero. The 'PRESERVE' keyword ensures the trigger remains active. ```kOS WHEN MAXTHRUST = 0 THEN { PRINT "Staging". STAGE. PRESERVE. }. ``` -------------------------------- ### kOS RUN Command with Arguments Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/commands/runprogram.html Demonstrates how to use the RUN command in kOS to execute a script with arguments. The arguments are passed as a tuple and are assigned to declared parameters within the script. This example assumes 'AutoLaunch.ks' is in the current directory and has '.ks' or '.ksm' extension. ```kOS RUN "AutoLaunch.ks"( 75000, true, "hello" ). ``` -------------------------------- ### Check Infernal Robotics Installation (kOS) Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/addons/IR.rst.txt This snippet demonstrates how to check if the Infernal Robotics mod is installed and available for use with kOS. It utilizes the `addons:available()` function, which is the recommended method for checking mod compatibility. ```kOS if ADDONS:AVAILABLE("ir") { Print "Infernal Robotics is installed and available.". } else { Print "Infernal Robotics is not installed or not available.". } ``` -------------------------------- ### List Initialization and Creation Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/structures/collections/list.html Shows how to initialize a list with specific values or create an empty list. This is the starting point for using list functionalities. ```kos SET BAR TO LIST(5,3,6). // Creates a new list with 3 integers in it. ``` -------------------------------- ### UniqueSet Usage Example - kOS Script Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/structures/collections/uniqueset.html Demonstrates the basic usage of the UniqueSet structure in kOS. It shows how to initialize a UniqueSet, add elements, and check its length. The example highlights that adding a duplicate element has no effect. ```kOS Script SET S TO UNIQUESET(1,2,3). PRINT S:LENGTH. S:ADD(1). PRINT S:LENGTH. ``` -------------------------------- ### Example: Compare TimeStamp and TimeSpan with Scalars in KOS Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/structures/misc/time.rst.txt This KOS example demonstrates comparing TimeStamp and TimeSpan objects with Scalar values, which are interpreted as seconds. It shows how a Scalar can represent seconds since epoch for TimeStamps or duration for TimeSpans. ```KOS local how_many_seconds_in_3_hours is 3 * 3600. if TIMESTAMP() > how_many_seconds_in_3_hours { print "This campaign universe has existed for at least 3 hours of game time.". } if TIMESPAN(1,0,0,0,0) > 1000000 { print "One year is more than 1000000 seconds.". } ``` -------------------------------- ### kOS Recurring Trigger Example: VecDraw:VECUPDATER Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/general/cpu_hardware.rst.txt Shows an example of a user delegate assigned to a recurrently updating suffix, VecDraw:VECUPDATER, which is a type of recurring trigger in kOS. These triggers repeatedly execute until stopped. ```kerboscript User Delegates assigned to recurrently updating suffixes such as VecDraw:VECUPDATER. ``` -------------------------------- ### kOS Queue Initialization and Usage Example Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/structures/collections/queue.rst.txt Demonstrates how to initialize a Queue in kOS, add elements using PUSH, and retrieve them using POP. Queues follow a First-In, First-Out principle. ```kOS SET Q TO QUEUE(). Q:PUSH("alice"). Q:PUSH("bob"). PRINT Q:POP. // will print 'alice' PRINT Q:POP. // will print 'bob' ``` -------------------------------- ### KerboScript Structure Method Calling Example Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/language/features.rst.txt Provides examples of calling methods associated with structures in KerboScript. It shows methods that take arguments and return values (lists) as well as methods that perform actions without returning a value. ```kerboscript SET PLIST TO SHIP:PARTSDUBBED("my engines"). // calling a suffix // method with one // argument that // returns a list. PLIST:REMOVE(0). // calling a suffix method with one argument that // doesn't return anything. PRINT PLIST:SUBLIST(0,4). // calling a suffix method with 2 // arguments that returns a list. ``` -------------------------------- ### Kos: List Creation and Access Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/_sources/tutorials/basictutorial.rst.txt Shows how to create a list from several variables using the 'list()' constructor and how to access elements by their zero-based index. It also demonstrates iterating through a list using a 'for' loop. ```kos set Value1 to 0. set Value2 to 5. set Value3 to 10. set Value4 to 15. set Value5 to 20. set ValueList to list(Value1, Value2, Value3, Value4, Value5). print ValueList. print ValueList[2]. // shows 10 ``` ```kos for Whatever in ValueList { print Whatever. } ``` ```kos for Value in ValueList { print Value. } ``` ```kos set x to 3. print ValueList[x]. // shows 15 ``` -------------------------------- ### Vector Direction Access and Modification Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/math/vector.html Allows getting and setting the direction of a vector. When getting, the vector is converted to a Direction structure, which may result in information loss. When setting, the vector's magnitude is preserved, but its orientation is updated. ```kOS // Get the direction of a vector SET dir TO myVector:DIRECTION. // Set the direction of a vector, preserving its magnitude SET myVector:DIRECTION TO newDirection. ``` -------------------------------- ### Declare Function Syntax Examples in Kerboscript Source: https://github.com/ksp-kos/kos_doc/blob/gh-pages/language/user_functions.html Demonstrates various ways to declare functions in Kerboscript, including specifying scope (local/global) and the use of the optional 'declare' keyword. These examples illustrate the flexible syntax for defining new functions. ```kerboscript declare function hi { print "hello". } ``` ```kerboscript declare local function hi { print "hello". } ``` ```kerboscript declare global function hi { print "hello". } ``` ```kerboscript local function hi { print "hello". } ``` ```kerboscript global function hi { print "hello". } ``` ```kerboscript function hi { print "hello". } ```